Skip to content

StandartCoder/azubiheft-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

1 Commit
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ“š azubiheft-api

The ultimate TypeScript/Node.js API client for azubiheft.de Automate your German apprenticeship training records (Berichtsheft) with ease!

npm version TypeScript Node.js License: MIT


๐Ÿš€ Quick Start

npm install azubiheft-api
import { Session, Entry, EntryType } from 'azubiheft-api';

const session = new Session();
await session.login({ username: 'your-username', password: 'your-password' });

// Create a report entry
const entry = new Entry(
  new Date(),
  'Learned advanced TypeScript patterns and API design',
  '08:00',
  EntryType.BETRIEB
);

await session.writeReports([entry]);
console.log('๐Ÿ“ Report submitted successfully!');

๐ŸŒŸ Features

๐Ÿ” Authentication & Session Management

  • Secure login/logout with persistent cookie sessions
  • Automatic session validation and renewal
  • Built-in authentication error handling

๐Ÿ“‹ Comprehensive Report Management

  • Create single or batch report entries
  • Read existing reports with optional HTML formatting
  • Delete individual entries or entire days
  • Support for all standard subject types

๐Ÿท๏ธ Dynamic Subject Management

  • Add custom subjects beyond the default ones
  • Delete user-created subjects
  • List all available subjects (static + dynamic)
  • Subject ID resolution by name

โฐ Advanced Time Utilities

  • Parse and validate time strings (HH:MM format)
  • Convert between different time representations
  • Add/subtract time durations with overflow protection
  • ISO week calculations for German calendar system

๐Ÿ›ก๏ธ Type Safety & Error Handling

  • Full TypeScript support with strict typing
  • Custom error classes for different scenarios
  • Comprehensive input validation
  • Detailed error messages for debugging

๐Ÿ“ฆ Modern Package Design

  • Dual module support (CommonJS + ES Modules)
  • Tree-shakeable exports
  • Source maps and declaration files
  • Zero-config TypeScript integration

๐Ÿ“– Documentation

๐ŸŽฏ Core Concepts

Session Management

The Session class is your main entry point for all API interactions. It manages authentication, cookies, and HTTP requests automatically.

import { Session } from 'azubiheft-api';

const session = new Session({
  baseUrl: 'https://www.azubiheft.de', // Optional: custom base URL
  timeout: 30000,                      // Optional: request timeout in ms
  userAgent: 'MyApp/1.0.0'            // Optional: custom user agent
});

Report Entries

Report entries represent individual training activities. Each entry contains:

  • Date: When the activity took place
  • Message: Description of what was done
  • Time Spent: Duration in HH:MM format (max 19:59)
  • Type: Subject/category ID (1-7 for built-in types, higher for custom)
import { Entry, EntryType } from 'azubiheft-api';

const workEntry = new Entry(
  new Date('2024-01-15'),
  'Implemented REST API endpoints for user management',
  '06:30',
  EntryType.BETRIEB
);

const schoolEntry = new Entry(
  new Date('2024-01-15'),
  'Attended software architecture seminar',
  '01:30',
  EntryType.SCHULE
);

๐Ÿ”ง API Reference

Session Class

Authentication Methods
// Login with credentials
await session.login({
  username: 'your-username',
  password: 'your-password'
});

// Check authentication status
const isLoggedIn = await session.isLoggedIn();

// Logout and clean up session
await session.logout();
Report Management Methods
// Write a single report
await session.writeReport(
  new Date(),              // date
  'Daily activities',      // message
  '08:00',                // timeSpent
  EntryType.BETRIEB       // entryType
);

// Write multiple reports at once
const entries = [entry1, entry2, entry3];
await session.writeReports(entries);

// Get reports for a specific date
const reports = await session.getReport(new Date());

// Get reports with HTML formatting preserved
const formattedReports = await session.getReport(new Date(), true);

// Delete all reports for a date
await session.deleteReport(new Date());

// Delete specific report (1-based index)
await session.deleteReport(new Date(), 1);
Subject Management Methods
// Get all available subjects
const subjects = await session.getSubjects();

// Add a custom subject
await session.addSubject('Machine Learning');

// Delete a custom subject by ID
await session.deleteSubject('customSubjectId');

// Find subject ID by name
const subjectId = await session.getArtIdFromText('Betrieb');

// Get week ID for calendar calculations
const weekId = await session.getReportWeekId(new Date());

Entry Class

// Create entry with validation
const entry = new Entry(date, message, timeSpent, type);

// Validate entry data
entry.validate(); // throws error if invalid

// Create from plain object
const entry2 = Entry.fromObject({
  date: new Date(),
  message: 'Task description',
  timeSpent: '04:30',
  type: 1
});

// Convert to plain object
const data = entry.toObject();

// Create modified copy
const modifiedEntry = entry.with({
  timeSpent: '05:00',
  message: 'Updated description'
});

// String representation
console.log(entry.toString());

// Equality comparison
const isEqual = entry1.equals(entry2);

TimeHelper Class

import { TimeHelper } from 'azubiheft-api';

// Date formatting
const dateStr = TimeHelper.dateTimeToString(new Date()); // "20240115"
const timestamp = TimeHelper.getActualTimestamp();        // "1705123456"

// Time string operations
const total = TimeHelper.addTimeStrings('04:30', '03:15');     // "07:45"
const diff = TimeHelper.subtractTimeStrings('08:00', '02:30'); // "05:30"

// Time conversions
const minutes = TimeHelper.timeStringToMinutes('08:45');       // 525
const timeStr = TimeHelper.minutesToTimeString(525);           // "08:45"

// Duration from milliseconds
const duration = TimeHelper.millisecondsToTimeString(8 * 60 * 60 * 1000); // "08:00"

// Validation
TimeHelper.validateTimeString('25:00'); // throws error
TimeHelper.validateTimeString('08:30'); // returns true

// ISO week calculations
const { year, week } = TimeHelper.getISOWeek(new Date());

// Parse date strings
const date = TimeHelper.stringToDateTime('20240115');
const { hours, minutes } = TimeHelper.parseTimeString('08:30');

๐Ÿท๏ธ Built-in Subject Types

import { EntryType, STATIC_SUBJECTS } from 'azubiheft-api';

// Enum values
EntryType.BETRIEB        // 1 - Company work
EntryType.SCHULE         // 2 - School/vocational college
EntryType.UBA            // 3 - Inter-company training
EntryType.URLAUB         // 4 - Vacation/holiday
EntryType.FEIERTAG       // 5 - Public holiday
EntryType.ARBEITSUNFAHIG // 6 - Sick leave
EntryType.FREI           // 7 - Free time

// Static subjects array
console.log(STATIC_SUBJECTS);
// [
//   { id: '1', name: 'Betrieb' },
//   { id: '2', name: 'Schule' },
//   { id: '3', name: 'รœBA' },
//   { id: '4', name: 'Urlaub' },
//   { id: '5', name: 'Feiertag' },
//   { id: '6', name: 'Arbeitsunfรคhig' },
//   { id: '7', name: 'Frei' }
// ]

๐Ÿšจ Error Handling

The library provides specific error types for different scenarios:

import {
  AuthError,
  NotLoggedInError,
  ValueTooLargeError,
  ApiError,
  ParseError,
  NetworkError,
  NotFoundError,
  isAuthError,
  isNotLoggedInError
} from 'azubiheft-api';

try {
  await session.login({ username: 'invalid', password: 'wrong' });
} catch (error) {
  if (isAuthError(error)) {
    console.log('๐Ÿ” Authentication failed:', error.message);
    // Handle login failure
  } else if (error instanceof NetworkError) {
    console.log('๐ŸŒ Network issue:', error.message);
    // Handle network problems
  } else if (error instanceof ApiError) {
    console.log('๐Ÿ“ก API error:', error.message, 'Status:', error.statusCode);
    // Handle API-specific errors
  }
}

// Automatic retry with backoff
async function loginWithRetry(credentials, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      await session.login(credentials);
      return;
    } catch (error) {
      if (isAuthError(error)) {
        throw error; // Don't retry auth failures
      }
      if (i === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
}

๐ŸŽจ TypeScript Integration

Perfect TypeScript support out of the box:

import type {
  Subject,
  ReportEntry,
  SessionOptions,
  LoginCredentials,
  Entry as IEntry
} from 'azubiheft-api';

// Type-safe configuration
const config: SessionOptions = {
  baseUrl: 'https://custom-azubiheft.com',
  timeout: 60000
};

// Type-safe data handling
const subjects: Subject[] = await session.getSubjects();
const reports: ReportEntry[] = await session.getReport(new Date());

// Generic utility function
async function processReports<T>(
  session: Session,
  date: Date,
  processor: (reports: ReportEntry[]) => T
): Promise<T> {
  const reports = await session.getReport(date);
  return processor(reports);
}

๐ŸŽฏ Examples & Use Cases

Check out our comprehensive examples in the /examples folder:


๐Ÿ”ง Installation & Setup

Prerequisites

  • Node.js 16.0.0 or higher
  • TypeScript 5.0+ (for development)
  • Valid azubiheft.de account

Installation

# Install the package
npm install azubiheft-api

# For TypeScript projects (types included automatically)
npm install azubiheft-api
npm install -D typescript @types/node

# For development/contribution
git clone https://github.com/yourusername/azubiheft-api.git
cd azubiheft-api
npm install
npm run build

Environment Setup

Create a .env file for your credentials (never commit this!):

AZUBIHEFT_USERNAME=your-username
AZUBIHEFT_PASSWORD=your-password
AZUBIHEFT_BASE_URL=https://www.azubiheft.de

๐Ÿ“Š Migration from Python Version

Migrating from the Python version? Check our Migration Guide for a smooth transition.

Key Differences

Python TypeScript/Node.js
requests axios
BeautifulSoup cheerio
Synchronous Async/await
Duck typing Static typing
session.writeReport() await session.writeReport()

๐Ÿค Contributing

We welcome contributions! Please read our Contributing Guide for details.

Development Setup

git clone https://github.com/yourusername/azubiheft-api.git
cd azubiheft-api
npm install
npm run dev  # Start development mode

Available Scripts

npm run build      # Build for production
npm run dev        # Development with watch mode
npm run clean      # Clean build directory
npm run test       # Run tests (coming soon)
npm run lint       # Lint code (coming soon)

๐Ÿ“š Additional Resources


๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


โš ๏ธ Disclaimer

This is an unofficial API client for azubiheft.de. Use responsibly and respect the platform's terms of service. The authors are not responsible for any misuse or violations of the platform's policies.


๐Ÿ™ Acknowledgments

  • Thanks to the azubiheft.de platform for providing digital training record management
  • Inspired by the need for automation in German apprenticeship documentation
  • Built with โค๏ธ for the developer and apprentice community

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published