@classytic/payroll 2.7.5 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/enums.ts","../../src/config.ts","../../src/schemas/common.ts","../../src/utils/logger.ts","../../src/models/leave-request.model.ts","../../src/schemas/leave.ts","../../src/core/state-machine.ts","../../src/core/payroll-states.ts","../../src/models/tax-withholding.model.ts","../../src/schemas/tax-withholding.ts","../../src/schemas/index.ts"],"names":["Schema","mongoose"],"mappings":";;;;;AAwBO,IAAM,eAAA,GAAkB;AAAA,EAC7B,SAAA,EAAW,WAAA;AAAA,EACX,SAAA,EAAW,WAAA;AAAA,EACX,QAAA,EAAU,UAAA;AAAA,EACV,MAAA,EAAQ,QAAA;AAAA,EACR,UAAA,EAAY;AACd,CAAA;AAEO,IAAM,sBAAA,GAAyB,MAAA,CAAO,MAAA,CAAO,eAAe,CAAA;AAU5D,IAAM,eAAA,GAAkB;AAAA,EAC7B,MAAA,EAAQ,QAAA;AAAA,EACR,QAAA,EAAU,UAAA;AAAA,EACV,SAAA,EAAW,WAAA;AAAA,EACX,UAAA,EAAY;AACd,CAAA;AAEO,IAAM,sBAAA,GAAyB,MAAA,CAAO,MAAA,CAAO,eAAe,CAAA;AAsB5D,IAAM,UAAA,GAAa;AAAA,EACxB,UAAA,EAAY,YAAA;AAAA,EACZ,QAAA,EAAU,UAAA;AAAA,EACV,KAAA,EAAO,OAAA;AAAA,EACP,UAAA,EAAY,YAAA;AAAA,EACZ,OAAA,EAAS,SAAA;AAAA,EACT,EAAA,EAAI,IAAA;AAAA,EACJ,WAAA,EAAa,aAAA;AAAA,EACb,SAAA,EAAW,WAAA;AAAA,EACX,OAAA,EAAS,SAAA;AAAA,EACT,EAAA,EAAI;AACN,CAAA;AAEO,IAAM,iBAAA,GAAoB,MAAA,CAAO,MAAA,CAAO,UAAU,CAAA;AAUlD,IAAM,iBAAA,GAAoB;AAAA,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,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,aAAA,GAAgB,aAAA;AACrB,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB,CAAA;AAGA,EAAA,MAAA,CAAO,OAAA,CAAQ,iBAAiB,WAAY;AAC1C,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA;AAChB,IAAA,IAAA,CAAK,UAAA,uBAAiB,IAAA,EAAK;AAAA,EAC7B,CAAA;AAGA,EAAA,MAAA,CAAO,OAAA,CAAQ,eAAe,WAAqB;AACjD,IAAA,OAAO,IAAA,CAAK,QAAA,IAAY,IAAA,CAAK,MAAA,KAAW,MAAA;AAAA,EAC1C,CAAA;AAEA,EAAA,OAAO,MAAA;AACT;AAkCA,IAAO,eAAA,GAAQ;AAAA;AAAA,EAEb,eAAA;AAAA,EACA,eAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,uBAAA;AAAA,EACA,kBAAA;AAAA,EACA,sBAAA;AAAA,EACA,YAAA;AAAA;AAAA,EAEA,sBAAA;AAAA,EACA,yBAAA;AAAA;AAAA,EAEA,eAAA;AAAA,EACA,oBAAA;AAAA,EACA,oBAAA;AAAA,EACA,yBAAA;AAAA;AAAA,EAEA,oBAAA;AAAA,EACA;AACF","file":"index.js","sourcesContent":["/**\n * @classytic/payroll - Enums\n *\n * Type-safe enum definitions with const assertions\n * Single source of truth for all enum values\n */\n\nimport type {\n EmploymentType,\n EmployeeStatus,\n Department,\n PaymentFrequency,\n PaymentMethod,\n AllowanceType,\n DeductionType,\n PayrollStatus,\n TerminationReason,\n SalaryBand,\n} from './types.js';\n\n// ============================================================================\n// Employment Type\n// ============================================================================\n\nexport const EMPLOYMENT_TYPE = {\n FULL_TIME: 'full_time',\n PART_TIME: 'part_time',\n CONTRACT: 'contract',\n INTERN: 'intern',\n CONSULTANT: 'consultant',\n} as const satisfies Record<string, EmploymentType>;\n\nexport const EMPLOYMENT_TYPE_VALUES = Object.values(EMPLOYMENT_TYPE);\n\nexport function isValidEmploymentType(value: string): value is EmploymentType {\n return EMPLOYMENT_TYPE_VALUES.includes(value as EmploymentType);\n}\n\n// ============================================================================\n// Employee Status\n// ============================================================================\n\nexport const EMPLOYEE_STATUS = {\n ACTIVE: 'active',\n ON_LEAVE: 'on_leave',\n SUSPENDED: 'suspended',\n TERMINATED: 'terminated',\n} as const satisfies Record<string, EmployeeStatus>;\n\nexport const EMPLOYEE_STATUS_VALUES = Object.values(EMPLOYEE_STATUS);\n\nexport function isValidEmployeeStatus(value: string): value is EmployeeStatus {\n return EMPLOYEE_STATUS_VALUES.includes(value as EmployeeStatus);\n}\n\nexport function isActiveStatus(status: EmployeeStatus): boolean {\n return status === EMPLOYEE_STATUS.ACTIVE;\n}\n\nexport function isEmployedStatus(status: EmployeeStatus): boolean {\n return status !== EMPLOYEE_STATUS.TERMINATED;\n}\n\nexport function canReceiveSalaryStatus(status: EmployeeStatus): boolean {\n return status === EMPLOYEE_STATUS.ACTIVE || status === EMPLOYEE_STATUS.ON_LEAVE;\n}\n\n// ============================================================================\n// Department\n// ============================================================================\n\nexport const DEPARTMENT = {\n MANAGEMENT: 'management',\n TRAINING: 'training',\n SALES: 'sales',\n OPERATIONS: 'operations',\n SUPPORT: 'support',\n HR: 'hr',\n MAINTENANCE: 'maintenance',\n MARKETING: 'marketing',\n FINANCE: 'finance',\n IT: 'it',\n} as const satisfies Record<string, Department>;\n\nexport const DEPARTMENT_VALUES = Object.values(DEPARTMENT);\n\nexport function isValidDepartment(value: string): value is Department {\n return DEPARTMENT_VALUES.includes(value as Department);\n}\n\n// ============================================================================\n// Payment Frequency\n// ============================================================================\n\nexport const PAYMENT_FREQUENCY = {\n MONTHLY: 'monthly',\n BI_WEEKLY: 'bi_weekly',\n WEEKLY: 'weekly',\n HOURLY: 'hourly',\n DAILY: 'daily',\n} as const satisfies Record<string, PaymentFrequency>;\n\nexport const PAYMENT_FREQUENCY_VALUES = Object.values(PAYMENT_FREQUENCY);\n\nexport function isValidPaymentFrequency(value: string): value is PaymentFrequency {\n return PAYMENT_FREQUENCY_VALUES.includes(value as PaymentFrequency);\n}\n\n// ============================================================================\n// Payment Method\n// ============================================================================\n\nexport const PAYMENT_METHOD = {\n BANK: 'bank',\n CASH: 'cash',\n MOBILE: 'mobile',\n BKASH: 'bkash',\n NAGAD: 'nagad',\n ROCKET: 'rocket',\n CHECK: 'check',\n} as const satisfies Record<string, PaymentMethod>;\n\nexport const PAYMENT_METHOD_VALUES = Object.values(PAYMENT_METHOD);\n\nexport function isValidPaymentMethod(value: string): value is PaymentMethod {\n return PAYMENT_METHOD_VALUES.includes(value as PaymentMethod);\n}\n\n// ============================================================================\n// Allowance Type\n// ============================================================================\n\nexport const ALLOWANCE_TYPE = {\n HOUSING: 'housing',\n TRANSPORT: 'transport',\n MEAL: 'meal',\n MOBILE: 'mobile',\n MEDICAL: 'medical',\n EDUCATION: 'education',\n BONUS: 'bonus',\n OTHER: 'other',\n} as const satisfies Record<string, AllowanceType>;\n\nexport const ALLOWANCE_TYPE_VALUES = Object.values(ALLOWANCE_TYPE);\n\nexport function isValidAllowanceType(value: string): value is AllowanceType {\n return ALLOWANCE_TYPE_VALUES.includes(value as AllowanceType);\n}\n\n// ============================================================================\n// Deduction Type\n// ============================================================================\n\nexport const DEDUCTION_TYPE = {\n TAX: 'tax',\n LOAN: 'loan',\n ADVANCE: 'advance',\n PROVIDENT_FUND: 'provident_fund',\n INSURANCE: 'insurance',\n ABSENCE: 'absence',\n OTHER: 'other',\n} as const satisfies Record<string, DeductionType>;\n\nexport const DEDUCTION_TYPE_VALUES = Object.values(DEDUCTION_TYPE);\n\nexport function isValidDeductionType(value: string): value is DeductionType {\n return DEDUCTION_TYPE_VALUES.includes(value as DeductionType);\n}\n\n// ============================================================================\n// Payroll Status\n// ============================================================================\n\nexport const PAYROLL_STATUS = {\n PENDING: 'pending',\n PROCESSING: 'processing',\n PAID: 'paid',\n FAILED: 'failed',\n VOIDED: 'voided',\n REVERSED: 'reversed',\n} as const satisfies Record<string, PayrollStatus>;\n\nexport const PAYROLL_STATUS_VALUES = Object.values(PAYROLL_STATUS);\n\nexport function isValidPayrollStatus(value: string): value is PayrollStatus {\n return PAYROLL_STATUS_VALUES.includes(value as PayrollStatus);\n}\n\nexport function isCompletedPayrollStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.PAID;\n}\n\nexport function isPendingPayrollStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.PENDING || status === PAYROLL_STATUS.PROCESSING;\n}\n\n/** Check if payroll can be voided (not yet paid) */\nexport function isVoidablePayrollStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.PENDING ||\n status === PAYROLL_STATUS.PROCESSING ||\n status === PAYROLL_STATUS.FAILED;\n}\n\n/** Check if payroll requires reversal (already paid) */\nexport function requiresReversalPayrollStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.PAID;\n}\n\n/** Check if payroll is in a terminal void/reverse state */\nexport function isVoidedOrReversedStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.VOIDED || status === PAYROLL_STATUS.REVERSED;\n}\n\n// ============================================================================\n// Termination Reason\n// ============================================================================\n\nexport const TERMINATION_REASON = {\n RESIGNATION: 'resignation',\n RETIREMENT: 'retirement',\n TERMINATION: 'termination',\n CONTRACT_END: 'contract_end',\n MUTUAL_AGREEMENT: 'mutual_agreement',\n OTHER: 'other',\n} as const satisfies Record<string, TerminationReason>;\n\nexport const TERMINATION_REASON_VALUES = Object.values(TERMINATION_REASON);\n\nexport function isValidTerminationReason(value: string): value is TerminationReason {\n return TERMINATION_REASON_VALUES.includes(value as TerminationReason);\n}\n\n// ============================================================================\n// Salary Band\n// ============================================================================\n\nexport const SALARY_BAND = {\n INTERN: 'intern',\n JUNIOR: 'junior',\n MID: 'mid',\n SENIOR: 'senior',\n LEAD: 'lead',\n EXECUTIVE: 'executive',\n CUSTOM: 'custom',\n} as const satisfies Record<string, SalaryBand>;\n\nexport const SALARY_BAND_VALUES = Object.values(SALARY_BAND);\n\nexport function isValidSalaryBand(value: string): value is SalaryBand {\n return SALARY_BAND_VALUES.includes(value as SalaryBand);\n}\n\n// ============================================================================\n// Leave Type\n// ============================================================================\n\nimport type { LeaveType, LeaveRequestStatus } from './types.js';\n\nexport const LEAVE_TYPE = {\n ANNUAL: 'annual',\n SICK: 'sick',\n UNPAID: 'unpaid',\n MATERNITY: 'maternity',\n PATERNITY: 'paternity',\n BEREAVEMENT: 'bereavement',\n COMPENSATORY: 'compensatory',\n OTHER: 'other',\n} as const satisfies Record<string, LeaveType>;\n\nexport const LEAVE_TYPE_VALUES = Object.values(LEAVE_TYPE);\n\nexport function isValidLeaveType(value: string): value is LeaveType {\n return LEAVE_TYPE_VALUES.includes(value as LeaveType);\n}\n\nexport function isPaidLeaveType(type: LeaveType): boolean {\n return type !== LEAVE_TYPE.UNPAID;\n}\n\n// ============================================================================\n// Leave Request Status\n// ============================================================================\n\nexport const LEAVE_REQUEST_STATUS = {\n PENDING: 'pending',\n APPROVED: 'approved',\n REJECTED: 'rejected',\n CANCELLED: 'cancelled',\n} as const satisfies Record<string, LeaveRequestStatus>;\n\nexport const LEAVE_REQUEST_STATUS_VALUES = Object.values(LEAVE_REQUEST_STATUS);\n\nexport function isValidLeaveRequestStatus(value: string): value is LeaveRequestStatus {\n return LEAVE_REQUEST_STATUS_VALUES.includes(value as LeaveRequestStatus);\n}\n\nexport function isPendingLeaveStatus(status: LeaveRequestStatus): boolean {\n return status === LEAVE_REQUEST_STATUS.PENDING;\n}\n\nexport function isApprovedLeaveStatus(status: LeaveRequestStatus): boolean {\n return status === LEAVE_REQUEST_STATUS.APPROVED;\n}\n\n// ============================================================================\n// Tax Type\n// ============================================================================\n\nexport const TAX_TYPE = {\n INCOME_TAX: 'income_tax',\n SOCIAL_SECURITY: 'social_security',\n HEALTH_INSURANCE: 'health_insurance',\n PENSION: 'pension',\n EMPLOYMENT_INSURANCE: 'employment_insurance',\n LOCAL_TAX: 'local_tax',\n OTHER: 'other',\n} as const satisfies Record<string, import('./types.js').TaxType>;\n\nexport const TAX_TYPE_VALUES = Object.values(TAX_TYPE);\n\nexport function isValidTaxType(value: string): value is import('./types.js').TaxType {\n return TAX_TYPE_VALUES.includes(value as import('./types.js').TaxType);\n}\n\n// ============================================================================\n// Tax Status\n// ============================================================================\n\nexport const TAX_STATUS = {\n PENDING: 'pending',\n SUBMITTED: 'submitted',\n PAID: 'paid',\n CANCELLED: 'cancelled',\n} as const satisfies Record<string, import('./types.js').TaxStatus>;\n\nexport const TAX_STATUS_VALUES = Object.values(TAX_STATUS);\n\nexport function isValidTaxStatus(value: string): value is import('./types.js').TaxStatus {\n return TAX_STATUS_VALUES.includes(value as import('./types.js').TaxStatus);\n}\n\nexport function isPendingTaxStatus(status: import('./types.js').TaxStatus): boolean {\n return status === TAX_STATUS.PENDING;\n}\n\nexport function isPaidTaxStatus(status: import('./types.js').TaxStatus): boolean {\n return status === TAX_STATUS.PAID;\n}\n\nexport function isCancelledTaxStatus(status: import('./types.js').TaxStatus): boolean {\n return status === TAX_STATUS.CANCELLED;\n}\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default {\n EMPLOYMENT_TYPE,\n EMPLOYMENT_TYPE_VALUES,\n EMPLOYEE_STATUS,\n EMPLOYEE_STATUS_VALUES,\n DEPARTMENT,\n DEPARTMENT_VALUES,\n PAYMENT_FREQUENCY,\n PAYMENT_FREQUENCY_VALUES,\n PAYMENT_METHOD,\n PAYMENT_METHOD_VALUES,\n ALLOWANCE_TYPE,\n ALLOWANCE_TYPE_VALUES,\n DEDUCTION_TYPE,\n DEDUCTION_TYPE_VALUES,\n PAYROLL_STATUS,\n PAYROLL_STATUS_VALUES,\n TERMINATION_REASON,\n TERMINATION_REASON_VALUES,\n SALARY_BAND,\n SALARY_BAND_VALUES,\n LEAVE_TYPE,\n LEAVE_TYPE_VALUES,\n LEAVE_REQUEST_STATUS,\n LEAVE_REQUEST_STATUS_VALUES,\n TAX_TYPE,\n TAX_TYPE_VALUES,\n TAX_STATUS,\n TAX_STATUS_VALUES,\n};\n","/**\n * @classytic/payroll - Configuration\n *\n * Centralized configuration with type safety\n * Configurable defaults for different use cases\n */\n\nimport type {\n HRMConfig,\n TaxBracket,\n SalaryBandRange,\n RoleMappingConfig,\n OrgRole,\n SalaryBand,\n Department,\n EmploymentType,\n PaymentFrequency,\n DeepPartial,\n EmployeeIdentityMode,\n} from './types.js';\nimport { roundMoney } from './utils/money.js';\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\nexport const HRM_CONFIG: HRMConfig = {\n dataRetention: {\n /**\n * Default retention period for payroll records in seconds\n *\n * STANDARD APPROACH: expireAt field + configurable TTL index\n *\n * ## How It Works:\n * 1. Set expireAt date on each payroll record\n * 2. Call PayrollRecord.configureRetention() at app startup\n * 3. MongoDB deletes documents when expireAt is reached\n *\n * ## Usage:\n *\n * @example Configure at initialization\n * ```typescript\n * await payroll.init({ ... });\n * await PayrollRecord.configureRetention(0); // 0 = delete when expireAt reached\n * ```\n *\n * @example Set expireAt per record\n * ```typescript\n * const expireAt = PayrollRecord.calculateExpireAt(7); // 7 years\n * await PayrollRecord.updateOne({ _id }, { expireAt });\n * ```\n *\n * ## Jurisdiction Requirements:\n * - USA: 7 years → 220752000 seconds\n * - EU/UK: 6 years → 189216000 seconds\n * - Germany: 10 years → 315360000 seconds\n * - India: 8 years → 252288000 seconds\n *\n * Set to 0 to disable TTL\n */\n payrollRecordsTTL: 63072000, // 2 years - adjust per jurisdiction\n exportWarningDays: 30,\n archiveBeforeDeletion: true,\n },\n\n payroll: {\n defaultCurrency: 'USD',\n allowProRating: true,\n attendanceIntegration: true,\n autoDeductions: true,\n overtimeEnabled: false,\n overtimeMultiplier: 1.5,\n },\n\n salary: {\n minimumWage: 0,\n maximumAllowances: 10,\n maximumDeductions: 10,\n defaultFrequency: 'monthly',\n },\n\n employment: {\n defaultProbationMonths: 3,\n maxProbationMonths: 6,\n allowReHiring: true,\n trackEmploymentHistory: true,\n },\n\n validation: {\n requireBankDetails: false,\n requireUserId: false, // Modern: Allow guest employees by default\n identityMode: 'employeeId', // Modern: Use human-readable IDs as primary\n identityFallbacks: ['email', 'userId'], // Smart fallback chain\n },\n};\n\n// ============================================================================\n// Salary Bands Configuration\n// ============================================================================\n\nexport const SALARY_BANDS: Record<Exclude<SalaryBand, 'custom'>, SalaryBandRange> = {\n intern: { min: 10000, max: 20000 },\n junior: { min: 20000, max: 40000 },\n mid: { min: 40000, max: 70000 },\n senior: { min: 70000, max: 120000 },\n lead: { min: 100000, max: 200000 },\n executive: { min: 150000, max: 500000 },\n};\n\n// ============================================================================\n// Tax Brackets Configuration\n// ============================================================================\n\nexport const TAX_BRACKETS: Record<string, TaxBracket[]> = {\n BDT: [\n { min: 0, max: 300000, rate: 0 },\n { min: 300000, max: 400000, rate: 0.05 },\n { min: 400000, max: 500000, rate: 0.10 },\n { min: 500000, max: 600000, rate: 0.15 },\n { min: 600000, max: 3000000, rate: 0.20 },\n { min: 3000000, max: Infinity, rate: 0.25 },\n ],\n USD: [\n { min: 0, max: 10000, rate: 0.10 },\n { min: 10000, max: 40000, rate: 0.12 },\n { min: 40000, max: 85000, rate: 0.22 },\n { min: 85000, max: 165000, rate: 0.24 },\n { min: 165000, max: 215000, rate: 0.32 },\n { min: 215000, max: 540000, rate: 0.35 },\n { min: 540000, max: Infinity, rate: 0.37 },\n ],\n};\n\n// ============================================================================\n// Organization Roles Configuration\n// ============================================================================\n\nexport interface OrgRoleDefinition {\n key: OrgRole;\n label: string;\n description: string;\n}\n\nexport const ORG_ROLES: Record<Uppercase<OrgRole>, OrgRoleDefinition> = {\n OWNER: {\n key: 'owner',\n label: 'Owner',\n description: 'Full organization access (set by Organization model)',\n },\n MANAGER: {\n key: 'manager',\n label: 'Manager',\n description: 'Management and administrative features',\n },\n TRAINER: {\n key: 'trainer',\n label: 'Trainer',\n description: 'Training and coaching features',\n },\n STAFF: {\n key: 'staff',\n label: 'Staff',\n description: 'General staff access to basic features',\n },\n INTERN: {\n key: 'intern',\n label: 'Intern',\n description: 'Limited access for interns',\n },\n CONSULTANT: {\n key: 'consultant',\n label: 'Consultant',\n description: 'Project-based consultant access',\n },\n};\n\nexport const ORG_ROLE_KEYS = Object.values(ORG_ROLES).map((role) => role.key);\n\n// ============================================================================\n// Role Mapping Configuration\n// ============================================================================\n\nexport const ROLE_MAPPING: RoleMappingConfig = {\n byDepartment: {\n management: 'manager',\n training: 'trainer',\n sales: 'staff',\n operations: 'staff',\n finance: 'staff',\n hr: 'staff',\n marketing: 'staff',\n it: 'staff',\n support: 'staff',\n maintenance: 'staff',\n },\n\n byEmploymentType: {\n full_time: 'staff',\n part_time: 'staff',\n contract: 'consultant',\n intern: 'intern',\n consultant: 'consultant',\n },\n\n default: 'staff',\n};\n\n// ============================================================================\n// Configuration Functions\n// ============================================================================\n\n/**\n * Calculate tax based on annual income\n *\n * Uses banker's rounding to prevent systematic bias in tax calculations.\n * Tax is calculated progressively across brackets and rounded once at the end.\n *\n * @param annualIncome - Annual income in major units (dollars/rupees/taka)\n * @param currency - Currency code (default: 'USD')\n * @returns Tax amount in major units, properly rounded with banker's rounding\n */\nexport function calculateTax(annualIncome: number, currency = 'USD'): number {\n const brackets = TAX_BRACKETS[currency];\n if (!brackets) return 0;\n\n let tax = 0;\n for (const bracket of brackets) {\n if (annualIncome > bracket.min) {\n const taxableAmount = Math.min(annualIncome, bracket.max) - bracket.min;\n tax += taxableAmount * bracket.rate;\n }\n }\n\n // Use roundMoney for consistency with all other money calculations\n // This ensures identical rounding behavior across all tax calculations\n return roundMoney(tax);\n}\n\n/**\n * Get salary band for a given amount\n */\nexport function getSalaryBand(amount: number): SalaryBand {\n for (const [band, range] of Object.entries(SALARY_BANDS)) {\n if (amount >= range.min && amount <= range.max) {\n return band as SalaryBand;\n }\n }\n return 'custom';\n}\n\n/**\n * Determine the appropriate organization role for an employee\n */\nexport function determineOrgRole(employmentData: {\n department?: Department | string;\n type?: EmploymentType | string;\n position?: string;\n}): OrgRole {\n const { department, type: employmentType } = employmentData;\n\n // Priority 1: Department-based mapping\n if (department && department in ROLE_MAPPING.byDepartment) {\n return ROLE_MAPPING.byDepartment[department as keyof typeof ROLE_MAPPING.byDepartment];\n }\n\n // Priority 2: Employment type mapping\n if (employmentType && employmentType in ROLE_MAPPING.byEmploymentType) {\n return ROLE_MAPPING.byEmploymentType[employmentType as keyof typeof ROLE_MAPPING.byEmploymentType];\n }\n\n // Priority 3: Default role\n return ROLE_MAPPING.default;\n}\n\n/**\n * Get pay periods per year based on frequency\n */\nexport function getPayPeriodsPerYear(frequency: PaymentFrequency): number {\n const periodsMap: Record<PaymentFrequency, number> = {\n monthly: 12,\n bi_weekly: 26,\n weekly: 52,\n daily: 365,\n hourly: 2080, // Assuming 40 hours/week * 52 weeks\n };\n return periodsMap[frequency];\n}\n\n/**\n * Calculate monthly equivalent from any frequency\n */\nexport function toMonthlyAmount(amount: number, frequency: PaymentFrequency): number {\n const periodsPerYear = getPayPeriodsPerYear(frequency);\n return Math.round((amount * periodsPerYear) / 12);\n}\n\n/**\n * Calculate annual equivalent from any frequency\n */\nexport function toAnnualAmount(amount: number, frequency: PaymentFrequency): number {\n const periodsPerYear = getPayPeriodsPerYear(frequency);\n return Math.round(amount * periodsPerYear);\n}\n\n/**\n * Merge configuration with defaults\n */\nexport function mergeConfig(\n customConfig: Partial<HRMConfig> | DeepPartial<HRMConfig> | undefined\n): HRMConfig {\n if (!customConfig) return HRM_CONFIG;\n\n return {\n dataRetention: { ...HRM_CONFIG.dataRetention, ...customConfig.dataRetention },\n payroll: { ...HRM_CONFIG.payroll, ...customConfig.payroll },\n salary: { ...HRM_CONFIG.salary, ...customConfig.salary },\n employment: { ...HRM_CONFIG.employment, ...customConfig.employment },\n validation: {\n ...HRM_CONFIG.validation,\n ...customConfig.validation,\n // Ensure fallbacks is always EmployeeIdentityMode[]\n identityFallbacks: (customConfig.validation?.identityFallbacks ?? HRM_CONFIG.validation.identityFallbacks) as EmployeeIdentityMode[]\n },\n };\n}\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default {\n HRM_CONFIG,\n SALARY_BANDS,\n TAX_BRACKETS,\n ORG_ROLES,\n ORG_ROLE_KEYS,\n ROLE_MAPPING,\n calculateTax,\n getSalaryBand,\n determineOrgRole,\n getPayPeriodsPerYear,\n toMonthlyAmount,\n toAnnualAmount,\n mergeConfig,\n};\n\n","/**\n * @classytic/payroll - Common Schema Definitions\n *\n * Shared sub-schemas used across multiple schema modules\n * Extracted to prevent circular dependencies\n */\n\nimport { Schema } from 'mongoose';\n\n// ============================================================================\n// Period Schema\n// ============================================================================\n\n/**\n * Payroll period schema\n * Shared across PayrollRecord and TaxWithholding schemas\n */\nexport const periodSchema = new Schema(\n {\n month: { type: Number, required: true, min: 1, max: 12 },\n year: { type: Number, required: true, min: 2020 },\n startDate: { type: Date, required: true },\n endDate: { type: Date, required: true },\n payDate: { type: Date, required: true },\n },\n { _id: false }\n);\n","/**\n * @classytic/payroll - Logger\n *\n * Pluggable logger abstraction\n * Defaults to console, can be replaced with pino, winston, etc.\n */\n\nimport type { Logger } from '../types.js';\n\n// ============================================================================\n// Default Logger Implementation\n// ============================================================================\n\nconst createConsoleLogger = (): Logger => ({\n info: (message: string, meta?: Record<string, unknown>) => {\n if (meta) {\n console.log(`[Payroll] INFO: ${message}`, meta);\n } else {\n console.log(`[Payroll] INFO: ${message}`);\n }\n },\n error: (message: string, meta?: Record<string, unknown>) => {\n if (meta) {\n console.error(`[Payroll] ERROR: ${message}`, meta);\n } else {\n console.error(`[Payroll] ERROR: ${message}`);\n }\n },\n warn: (message: string, meta?: Record<string, unknown>) => {\n if (meta) {\n console.warn(`[Payroll] WARN: ${message}`, meta);\n } else {\n console.warn(`[Payroll] WARN: ${message}`);\n }\n },\n debug: (message: string, meta?: Record<string, unknown>) => {\n if (process.env.NODE_ENV !== 'production') {\n if (meta) {\n console.log(`[Payroll] DEBUG: ${message}`, meta);\n } else {\n console.log(`[Payroll] DEBUG: ${message}`);\n }\n }\n },\n});\n\n// ============================================================================\n// Logger State\n// ============================================================================\n\nlet currentLogger: Logger = createConsoleLogger();\nlet loggingEnabled = true;\n\n// ============================================================================\n// Logger Functions\n// ============================================================================\n\n/**\n * Get the current logger instance (respects loggingEnabled flag)\n */\nexport function getLogger(): Logger {\n return {\n info: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.info(message, meta);\n },\n error: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.error(message, meta);\n },\n warn: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.warn(message, meta);\n },\n debug: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.debug(message, meta);\n },\n };\n}\n\n/**\n * Set a custom logger instance\n */\nexport function setLogger(logger: Logger): void {\n currentLogger = logger;\n}\n\n/**\n * Reset to default console logger\n */\nexport function resetLogger(): void {\n currentLogger = createConsoleLogger();\n}\n\n/**\n * Create a child logger with prefix (respects loggingEnabled flag)\n */\nexport function createChildLogger(prefix: string): Logger {\n const parent = currentLogger;\n return {\n info: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) parent.info(`[${prefix}] ${message}`, meta);\n },\n error: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) parent.error(`[${prefix}] ${message}`, meta);\n },\n warn: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) parent.warn(`[${prefix}] ${message}`, meta);\n },\n debug: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) parent.debug(`[${prefix}] ${message}`, meta);\n },\n };\n}\n\n/**\n * Create a silent logger (for testing)\n */\nexport function createSilentLogger(): Logger {\n return {\n info: () => {},\n error: () => {},\n warn: () => {},\n debug: () => {},\n };\n}\n\n/**\n * Enable logging globally\n */\nexport function enableLogging(): void {\n loggingEnabled = true;\n}\n\n/**\n * Disable logging globally (useful for production)\n */\nexport function disableLogging(): void {\n loggingEnabled = false;\n}\n\n/**\n * Check if logging is enabled\n */\nexport function isLoggingEnabled(): boolean {\n return loggingEnabled;\n}\n\n// ============================================================================\n// Logger Proxy Object\n// ============================================================================\n\n/**\n * Logger proxy that always delegates to currentLogger\n * Respects global logging enabled/disabled state\n */\nexport const logger: Logger = {\n info: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.info(message, meta);\n },\n error: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.error(message, meta);\n },\n warn: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.warn(message, meta);\n },\n debug: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.debug(message, meta);\n },\n};\n\nexport default logger;\n\n","/**\n * @classytic/payroll - LeaveRequest Model\n *\n * Mongoose schema for leave requests with TTL support\n */\n\nimport mongoose, { Schema, Model } from 'mongoose';\nimport type {\n LeaveRequestDocument,\n LeaveType,\n LeaveRequestStatus,\n} from '../types.js';\nimport {\n LEAVE_REQUEST_STATUS,\n LEAVE_TYPE_VALUES,\n LEAVE_REQUEST_STATUS_VALUES,\n} from '../enums.js';\nimport { logger } from '../utils/logger.js';\n\n// ============================================================================\n// Schema Definition\n// ============================================================================\n\nconst leaveRequestSchema = new Schema(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n required: false, // Optional for single-tenant mode\n ref: 'Organization',\n },\n employeeId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'Employee',\n },\n userId: {\n type: Schema.Types.ObjectId,\n required: false, // Optional for guest employees\n ref: 'User',\n },\n type: {\n type: String,\n enum: LEAVE_TYPE_VALUES,\n required: true,\n },\n startDate: {\n type: Date,\n required: true,\n validate: {\n validator: function (this: { endDate?: Date }, value: Date) {\n return !this.endDate || value <= this.endDate;\n },\n message: 'Start date must be before or equal to end date',\n },\n },\n endDate: {\n type: Date,\n required: true,\n validate: {\n validator: function (this: { startDate?: Date }, value: Date) {\n return !this.startDate || value >= this.startDate;\n },\n message: 'End date must be after or equal to start date',\n },\n },\n days: {\n type: Number,\n required: true,\n min: [0.5, 'Days must be at least 0.5'],\n },\n halfDay: { type: Boolean, default: false },\n reason: String,\n status: {\n type: String,\n enum: LEAVE_REQUEST_STATUS_VALUES,\n default: 'pending',\n },\n reviewedBy: { type: Schema.Types.ObjectId, ref: 'User' },\n reviewedAt: Date,\n reviewNotes: String,\n attachments: [String],\n metadata: { type: Schema.Types.Mixed, default: {} },\n },\n { timestamps: true }\n);\n\n// ============================================================================\n// Indexes (opt-in via applyLeaveRequestIndexes)\n// ============================================================================\n\n// Note: Indexes are NOT applied automatically\n// Use applyLeaveRequestIndexes() from schemas/leave.ts if needed\n\n// ============================================================================\n// Virtuals\n// ============================================================================\n\nleaveRequestSchema.virtual('isPending').get(function () {\n return this.status === LEAVE_REQUEST_STATUS.PENDING;\n});\n\nleaveRequestSchema.virtual('isApproved').get(function () {\n return this.status === LEAVE_REQUEST_STATUS.APPROVED;\n});\n\nleaveRequestSchema.virtual('isRejected').get(function () {\n return this.status === LEAVE_REQUEST_STATUS.REJECTED;\n});\n\nleaveRequestSchema.virtual('isCancelled').get(function () {\n return this.status === LEAVE_REQUEST_STATUS.CANCELLED;\n});\n\n// ============================================================================\n// Methods\n// ============================================================================\n\nleaveRequestSchema.methods.approve = function (\n reviewerId: mongoose.Types.ObjectId,\n notes?: string\n) {\n if (this.status !== LEAVE_REQUEST_STATUS.PENDING) {\n throw new Error('Can only approve pending requests');\n }\n this.status = LEAVE_REQUEST_STATUS.APPROVED;\n this.reviewedBy = reviewerId;\n this.reviewedAt = new Date();\n if (notes) this.reviewNotes = notes;\n\n logger.info('Leave request approved', {\n requestId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n type: this.type,\n days: this.days,\n });\n};\n\nleaveRequestSchema.methods.reject = function (\n reviewerId: mongoose.Types.ObjectId,\n notes?: string\n) {\n if (this.status !== LEAVE_REQUEST_STATUS.PENDING) {\n throw new Error('Can only reject pending requests');\n }\n this.status = LEAVE_REQUEST_STATUS.REJECTED;\n this.reviewedBy = reviewerId;\n this.reviewedAt = new Date();\n if (notes) this.reviewNotes = notes;\n\n logger.info('Leave request rejected', {\n requestId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n type: this.type,\n days: this.days,\n });\n};\n\nleaveRequestSchema.methods.cancel = function () {\n if (this.status !== LEAVE_REQUEST_STATUS.PENDING) {\n throw new Error('Can only cancel pending requests');\n }\n this.status = LEAVE_REQUEST_STATUS.CANCELLED;\n\n logger.info('Leave request cancelled', {\n requestId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n type: this.type,\n days: this.days,\n });\n};\n\n// ============================================================================\n// Statics\n// ============================================================================\n\nleaveRequestSchema.statics.findByEmployee = function (\n employeeId: mongoose.Types.ObjectId,\n options: { status?: LeaveRequestStatus; year?: number; limit?: number } = {}\n) {\n const query: Record<string, unknown> = { employeeId };\n\n if (options.status) query.status = options.status;\n if (options.year) {\n query.startDate = {\n $gte: new Date(options.year, 0, 1),\n $lt: new Date(options.year + 1, 0, 1),\n };\n }\n\n return this.find(query)\n .sort({ startDate: -1 })\n .limit(options.limit || 50);\n};\n\nleaveRequestSchema.statics.findPendingByOrganization = function (\n organizationId?: mongoose.Types.ObjectId\n) {\n const query: Record<string, unknown> = {\n status: LEAVE_REQUEST_STATUS.PENDING,\n };\n\n if (organizationId) {\n query.organizationId = organizationId;\n }\n\n return this.find(query).sort({ createdAt: -1 });\n};\n\nleaveRequestSchema.statics.findByPeriod = function (\n organizationId: mongoose.Types.ObjectId | undefined,\n startDate: Date,\n endDate: Date,\n options: { status?: LeaveRequestStatus; type?: LeaveType } = {}\n) {\n const query: Record<string, unknown> = {\n $or: [\n { startDate: { $gte: startDate, $lte: endDate } },\n { endDate: { $gte: startDate, $lte: endDate } },\n {\n startDate: { $lte: startDate },\n endDate: { $gte: endDate },\n },\n ],\n };\n\n if (organizationId) {\n query.organizationId = organizationId;\n }\n\n if (options.status) query.status = options.status;\n if (options.type) query.type = options.type;\n\n return this.find(query).sort({ startDate: 1 });\n};\n\nleaveRequestSchema.statics.getLeaveStats = function (\n employeeId: mongoose.Types.ObjectId,\n year: number\n) {\n return this.aggregate([\n {\n $match: {\n employeeId,\n status: LEAVE_REQUEST_STATUS.APPROVED,\n startDate: {\n $gte: new Date(year, 0, 1),\n $lt: new Date(year + 1, 0, 1),\n },\n },\n },\n {\n $group: {\n _id: '$type',\n totalDays: { $sum: '$days' },\n count: { $sum: 1 },\n },\n },\n ]).then((results: unknown[]) =>\n results as Array<{ _id: LeaveType; totalDays: number; count: number }>\n );\n};\n\nleaveRequestSchema.statics.getOrganizationSummary = function (\n organizationId: mongoose.Types.ObjectId | undefined,\n year: number\n) {\n const matchStage: Record<string, unknown> = {\n startDate: {\n $gte: new Date(year, 0, 1),\n $lt: new Date(year + 1, 0, 1),\n },\n };\n\n if (organizationId) {\n matchStage.organizationId = organizationId;\n }\n\n return this.aggregate([\n {\n $match: matchStage,\n },\n {\n $group: {\n _id: { status: '$status', type: '$type' },\n totalDays: { $sum: '$days' },\n count: { $sum: 1 },\n },\n },\n ]);\n};\n\nleaveRequestSchema.statics.findOverlapping = function (\n employeeId: mongoose.Types.ObjectId,\n startDate: Date,\n endDate: Date,\n excludeRequestId?: mongoose.Types.ObjectId\n) {\n const query: Record<string, unknown> = {\n employeeId,\n status: { $in: [LEAVE_REQUEST_STATUS.PENDING, LEAVE_REQUEST_STATUS.APPROVED] },\n // Overlapping condition: new request overlaps with existing\n startDate: { $lte: endDate },\n endDate: { $gte: startDate },\n };\n\n if (excludeRequestId) {\n query._id = { $ne: excludeRequestId };\n }\n\n return this.find(query).sort({ startDate: 1 });\n};\n\nleaveRequestSchema.statics.hasOverlap = async function (\n employeeId: mongoose.Types.ObjectId,\n startDate: Date,\n endDate: Date,\n excludeRequestId?: mongoose.Types.ObjectId\n): Promise<boolean> {\n const query: Record<string, unknown> = {\n employeeId,\n status: { $in: [LEAVE_REQUEST_STATUS.PENDING, LEAVE_REQUEST_STATUS.APPROVED] },\n startDate: { $lte: endDate },\n endDate: { $gte: startDate },\n };\n\n if (excludeRequestId) {\n query._id = { $ne: excludeRequestId };\n }\n\n const count = await this.countDocuments(query);\n return count > 0;\n};\n\n// ============================================================================\n// Model Interface\n// ============================================================================\n\nexport interface LeaveRequestModel extends Model<LeaveRequestDocument> {\n findByEmployee(\n employeeId: mongoose.Types.ObjectId,\n options?: { status?: LeaveRequestStatus; year?: number; limit?: number }\n ): ReturnType<Model<LeaveRequestDocument>['find']>;\n\n findPendingByOrganization(\n organizationId?: mongoose.Types.ObjectId\n ): ReturnType<Model<LeaveRequestDocument>['find']>;\n\n findByPeriod(\n organizationId: mongoose.Types.ObjectId | undefined,\n startDate: Date,\n endDate: Date,\n options?: { status?: LeaveRequestStatus; type?: LeaveType }\n ): ReturnType<Model<LeaveRequestDocument>['find']>;\n\n getLeaveStats(\n employeeId: mongoose.Types.ObjectId,\n year: number\n ): Promise<Array<{ _id: LeaveType; totalDays: number; count: number }>>;\n\n getOrganizationSummary(\n organizationId: mongoose.Types.ObjectId | undefined,\n year: number\n ): Promise<\n Array<{\n _id: { status: LeaveRequestStatus; type: LeaveType };\n totalDays: number;\n count: number;\n }>\n >;\n\n findOverlapping(\n employeeId: mongoose.Types.ObjectId,\n startDate: Date,\n endDate: Date,\n excludeRequestId?: mongoose.Types.ObjectId\n ): ReturnType<Model<LeaveRequestDocument>['find']>;\n\n hasOverlap(\n employeeId: mongoose.Types.ObjectId,\n startDate: Date,\n endDate: Date,\n excludeRequestId?: mongoose.Types.ObjectId\n ): Promise<boolean>;\n}\n\n// ============================================================================\n// Model Factory\n// ============================================================================\n\n/**\n * Get or create LeaveRequest model\n *\n * @example\n * const LeaveRequest = getLeaveRequestModel();\n *\n * // With custom connection\n * const LeaveRequest = getLeaveRequestModel(customConnection);\n */\nexport function getLeaveRequestModel(\n connection: mongoose.Connection = mongoose.connection\n): LeaveRequestModel {\n const modelName = 'LeaveRequest';\n\n if (connection.models[modelName]) {\n return connection.models[modelName] as LeaveRequestModel;\n }\n\n return connection.model<LeaveRequestDocument, LeaveRequestModel>(\n modelName,\n leaveRequestSchema\n );\n}\n\nexport { leaveRequestSchema };\nexport default leaveRequestSchema;\n","/**\n * @classytic/payroll - Leave Schemas\n *\n * Leave balance sub-schema (for Employee embedding) and re-exports from\n * the authoritative LeaveRequest model definition.\n *\n * Single source of truth for LeaveRequest: models/leave-request.model.ts\n */\n\nimport { Schema, type SchemaDefinition } from 'mongoose';\nimport { LEAVE_TYPE_VALUES, LEAVE_REQUEST_STATUS_VALUES } from '../enums.js';\nimport {\n leaveRequestSchema,\n getLeaveRequestModel,\n type LeaveRequestModel,\n} from '../models/leave-request.model.js';\n\n// Re-export the authoritative LeaveRequest schema and model\nexport { leaveRequestSchema, getLeaveRequestModel, type LeaveRequestModel };\n\n// ============================================================================\n// Leave Balance Sub-Schema (for Employee embedding)\n// ============================================================================\n\n/**\n * Leave balance schema (embedded in Employee documents)\n * This is NOT a standalone model - it's for embedding.\n */\nexport const leaveBalanceSchema = new Schema(\n {\n type: {\n type: String,\n enum: LEAVE_TYPE_VALUES,\n required: true,\n },\n allocated: { type: Number, default: 0, min: 0 },\n used: { type: Number, default: 0, min: 0 },\n pending: { type: Number, default: 0, min: 0 },\n carriedOver: { type: Number, default: 0, min: 0 },\n expiresAt: { type: Date },\n year: { type: Number, required: true },\n },\n { _id: false }\n);\n\n/**\n * Leave balance fields for embedding in Employee schema\n *\n * @example\n * const employeeSchema = new Schema({\n * ...createEmploymentFields({ organizationRef: 'Branch' }),\n * ...leaveBalanceFields,\n * });\n */\nexport const leaveBalanceFields: SchemaDefinition = {\n leaveBalances: [leaveBalanceSchema],\n};\n\n// ============================================================================\n// Index Definitions (for custom schema composition)\n// ============================================================================\n\n/**\n * Recommended indexes for LeaveRequest collection\n */\nexport const leaveRequestIndexes = [\n { fields: { organizationId: 1, employeeId: 1, startDate: -1 } },\n { fields: { organizationId: 1, status: 1, createdAt: -1 } },\n { fields: { employeeId: 1, status: 1 } },\n { fields: { organizationId: 1, type: 1, status: 1 } },\n];\n\n/**\n * TTL index config for auto-cleanup (opt-in)\n */\nexport const leaveRequestTTLIndex = {\n fields: { createdAt: 1 },\n options: {\n expireAfterSeconds: 63072000, // 2 years\n partialFilterExpression: {\n status: { $in: ['approved', 'rejected', 'cancelled'] },\n },\n },\n};\n\n/**\n * Apply indexes to a LeaveRequest schema\n */\nexport function applyLeaveRequestIndexes(\n schema: Schema,\n options: { createIndexes?: boolean; enableTTL?: boolean; ttlSeconds?: number } = {}\n): void {\n if (!options.createIndexes) return;\n\n for (const { fields } of leaveRequestIndexes) {\n schema.index(fields as any);\n }\n\n if (options.enableTTL) {\n schema.index(leaveRequestTTLIndex.fields as Record<string, 1>, {\n ...leaveRequestTTLIndex.options,\n expireAfterSeconds: options.ttlSeconds ?? leaveRequestTTLIndex.options.expireAfterSeconds,\n });\n }\n}\n\n// ============================================================================\n// Schema Field Extraction (for custom schema composition)\n// ============================================================================\n\n/**\n * Extract field definitions from the authoritative LeaveRequest schema.\n * Use this when composing custom schemas.\n *\n * @example\n * const customSchema = new Schema({\n * ...getLeaveRequestFields(),\n * myCustomField: String,\n * });\n */\nexport function getLeaveRequestFields(): SchemaDefinition {\n const paths = leaveRequestSchema.paths;\n const fields: SchemaDefinition = {};\n\n for (const [key, pathObj] of Object.entries(paths)) {\n if (key === '_id' || key === '__v' || key === 'createdAt' || key === 'updatedAt') {\n continue;\n }\n fields[key] = (pathObj as { options?: SchemaDefinition[string] }).options || {};\n }\n\n return fields;\n}\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default {\n leaveBalanceSchema,\n leaveBalanceFields,\n leaveRequestSchema,\n leaveRequestIndexes,\n leaveRequestTTLIndex,\n applyLeaveRequestIndexes,\n getLeaveRequestFields,\n getLeaveRequestModel,\n};\n","/**\r\n * @classytic/payroll - State Machine\r\n *\r\n * Minimal state machine implementation for status management.\r\n * Enforces valid transitions and provides clear error messages.\r\n */\r\n\r\n// ============================================================================\r\n// Types\r\n// ============================================================================\r\n\r\n/**\r\n * State transition definition\r\n */\r\nexport interface StateTransition<TState extends string> {\r\n from: TState | TState[];\r\n to: TState;\r\n}\r\n\r\n/**\r\n * State machine configuration\r\n */\r\nexport interface StateMachineConfig<TState extends string> {\r\n /** All valid states */\r\n states: readonly TState[];\r\n /** Initial state */\r\n initial: TState;\r\n /** Valid transitions */\r\n transitions: StateTransition<TState>[];\r\n /** Terminal states (no outgoing transitions) */\r\n terminal?: TState[];\r\n}\r\n\r\n/**\r\n * Transition result\r\n */\r\nexport type TransitionResult<TState extends string> =\r\n | { success: true; from: TState; to: TState }\r\n | { success: false; from: TState; to: TState; error: string };\r\n\r\n// ============================================================================\r\n// State Machine Class\r\n// ============================================================================\r\n\r\n/**\r\n * Minimal state machine for status management\r\n *\r\n * @example\r\n * const machine = new StateMachine({\r\n * states: ['pending', 'processing', 'paid', 'voided'] as const,\r\n * initial: 'pending',\r\n * transitions: [\r\n * { from: 'pending', to: 'processing' },\r\n * { from: 'pending', to: 'voided' },\r\n * { from: 'processing', to: 'paid' },\r\n * ],\r\n * terminal: ['paid', 'voided'],\r\n * });\r\n *\r\n * machine.canTransition('pending', 'processing'); // true\r\n * machine.canTransition('paid', 'pending'); // false\r\n */\r\nexport class StateMachine<TState extends string> {\r\n private readonly validTransitions: Map<TState, Set<TState>>;\r\n private readonly terminalStates: Set<TState>;\r\n\r\n constructor(private readonly config: StateMachineConfig<TState>) {\r\n // Build transition map for O(1) lookup\r\n this.validTransitions = new Map();\r\n for (const state of config.states) {\r\n this.validTransitions.set(state, new Set());\r\n }\r\n\r\n for (const transition of config.transitions) {\r\n const fromStates = Array.isArray(transition.from)\r\n ? transition.from\r\n : [transition.from];\r\n\r\n for (const from of fromStates) {\r\n this.validTransitions.get(from)?.add(transition.to);\r\n }\r\n }\r\n\r\n this.terminalStates = new Set(config.terminal || []);\r\n }\r\n\r\n /**\r\n * Get the initial state\r\n */\r\n get initial(): TState {\r\n return this.config.initial;\r\n }\r\n\r\n /**\r\n * Get all valid states\r\n */\r\n get states(): readonly TState[] {\r\n return this.config.states;\r\n }\r\n\r\n /**\r\n * Check if a state is valid\r\n */\r\n isValidState(state: string): state is TState {\r\n return this.config.states.includes(state as TState);\r\n }\r\n\r\n /**\r\n * Check if a state is terminal (no outgoing transitions)\r\n */\r\n isTerminal(state: TState): boolean {\r\n return this.terminalStates.has(state);\r\n }\r\n\r\n /**\r\n * Check if transition from one state to another is valid\r\n */\r\n canTransition(from: TState, to: TState): boolean {\r\n return this.validTransitions.get(from)?.has(to) ?? false;\r\n }\r\n\r\n /**\r\n * Get all valid next states from current state\r\n */\r\n getNextStates(from: TState): TState[] {\r\n return Array.from(this.validTransitions.get(from) || []);\r\n }\r\n\r\n /**\r\n * Validate a transition and return result\r\n */\r\n validateTransition(from: TState, to: TState): TransitionResult<TState> {\r\n if (!this.isValidState(from)) {\r\n return {\r\n success: false,\r\n from,\r\n to,\r\n error: `Invalid current state: '${from}'`,\r\n };\r\n }\r\n\r\n if (!this.isValidState(to)) {\r\n return {\r\n success: false,\r\n from,\r\n to,\r\n error: `Invalid target state: '${to}'`,\r\n };\r\n }\r\n\r\n if (this.isTerminal(from)) {\r\n return {\r\n success: false,\r\n from,\r\n to,\r\n error: `Cannot transition from terminal state '${from}'`,\r\n };\r\n }\r\n\r\n if (!this.canTransition(from, to)) {\r\n const validNext = this.getNextStates(from);\r\n return {\r\n success: false,\r\n from,\r\n to,\r\n error: `Invalid transition: '${from}' → '${to}'. Valid transitions from '${from}': [${validNext.join(', ')}]`,\r\n };\r\n }\r\n\r\n return { success: true, from, to };\r\n }\r\n\r\n /**\r\n * Assert a transition is valid, throw if not\r\n */\r\n assertTransition(from: TState, to: TState): void {\r\n const result = this.validateTransition(from, to);\r\n if (!result.success) {\r\n throw new Error(result.error);\r\n }\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Factory Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Create a state machine instance\r\n */\r\nexport function createStateMachine<TState extends string>(\r\n config: StateMachineConfig<TState>\r\n): StateMachine<TState> {\r\n return new StateMachine(config);\r\n}\r\n","/**\r\n * @classytic/payroll - Payroll State Machines\r\n *\r\n * Defines valid state transitions for all status types.\r\n * Single source of truth for status management.\r\n */\r\n\r\nimport { createStateMachine, type StateMachine } from './state-machine.js';\r\n\r\n// ============================================================================\r\n// Payroll Record Status\r\n// ============================================================================\r\n\r\n/**\r\n * PayrollStatus state machine\r\n *\r\n * State diagram:\r\n * ```\r\n * PENDING ──┬──> PROCESSING ──┬──> PAID ──> REVERSED\r\n * │ │ │\r\n * │ │ └──> FAILED ──┐\r\n * │ │ │\r\n * │ └──> VOIDED <──────────┘\r\n * │ ↑\r\n * └──────────────┘\r\n * ```\r\n *\r\n * - PENDING: Initial state, payroll created but not processed\r\n * - PROCESSING: Currently being processed (bulk operations)\r\n * - PAID: Payment completed successfully\r\n * - FAILED: Processing failed (can retry → pending, or void)\r\n * - VOIDED: Cancelled before payment (can restore → pending)\r\n * - REVERSED: Payment reversed after completion (terminal)\r\n */\r\nexport const PayrollStatusMachine = createStateMachine({\r\n states: ['pending', 'processing', 'paid', 'failed', 'voided', 'reversed'] as const,\r\n initial: 'pending',\r\n transitions: [\r\n // Normal flow\r\n { from: 'pending', to: 'processing' },\r\n { from: 'processing', to: 'paid' },\r\n\r\n // Direct payment (skip processing for single salary)\r\n { from: 'pending', to: 'paid' },\r\n\r\n // Failure handling\r\n { from: 'processing', to: 'failed' },\r\n { from: 'failed', to: 'pending' }, // Retry\r\n\r\n // Void (unpaid only - pending, processing, or failed)\r\n { from: ['pending', 'processing', 'failed'], to: 'voided' },\r\n\r\n // Reversal (paid only)\r\n { from: 'paid', to: 'reversed' },\r\n\r\n // Restore voided (back to pending for re-processing)\r\n { from: 'voided', to: 'pending' },\r\n ],\r\n terminal: ['reversed'], // Only reversed is truly terminal\r\n});\r\n\r\nexport type PayrollStatusState = typeof PayrollStatusMachine.states[number];\r\n\r\n// ============================================================================\r\n// Tax Withholding Status\r\n// ============================================================================\r\n\r\n/**\r\n * TaxStatus state machine\r\n *\r\n * State diagram:\r\n * ```\r\n * PENDING ──┬──> SUBMITTED ──> PAID\r\n * │\r\n * └──> CANCELLED\r\n * ```\r\n *\r\n * - PENDING: Tax withheld, not yet submitted to government\r\n * - SUBMITTED: Submitted to tax authority, awaiting confirmation\r\n * - PAID: Payment confirmed by tax authority\r\n * - CANCELLED: Invalidated (payroll voided/reversed)\r\n */\r\nexport const TaxStatusMachine = createStateMachine({\r\n states: ['pending', 'submitted', 'paid', 'cancelled'] as const,\r\n initial: 'pending',\r\n transitions: [\r\n { from: 'pending', to: 'submitted' },\r\n { from: 'submitted', to: 'paid' },\r\n\r\n // Direct payment (some jurisdictions)\r\n { from: 'pending', to: 'paid' },\r\n\r\n // Cancellation (from any non-terminal state)\r\n { from: ['pending', 'submitted'], to: 'cancelled' },\r\n ],\r\n terminal: ['paid', 'cancelled'],\r\n});\r\n\r\nexport type TaxStatusState = typeof TaxStatusMachine.states[number];\r\n\r\n// ============================================================================\r\n// Leave Request Status\r\n// ============================================================================\r\n\r\n/**\r\n * LeaveRequestStatus state machine\r\n *\r\n * State diagram:\r\n * ```\r\n * PENDING ──┬──> APPROVED\r\n * │\r\n * ├──> REJECTED\r\n * │\r\n * └──> CANCELLED\r\n * ```\r\n */\r\nexport const LeaveRequestStatusMachine = createStateMachine({\r\n states: ['pending', 'approved', 'rejected', 'cancelled'] as const,\r\n initial: 'pending',\r\n transitions: [\r\n { from: 'pending', to: 'approved' },\r\n { from: 'pending', to: 'rejected' },\r\n { from: 'pending', to: 'cancelled' },\r\n\r\n // Cancel approved leave (before it starts)\r\n { from: 'approved', to: 'cancelled' },\r\n ],\r\n terminal: ['rejected', 'cancelled'],\r\n});\r\n\r\nexport type LeaveRequestStatusState = typeof LeaveRequestStatusMachine.states[number];\r\n\r\n// ============================================================================\r\n// Employee Status\r\n// ============================================================================\r\n\r\n/**\r\n * EmployeeStatus state machine\r\n *\r\n * State diagram:\r\n * ```\r\n * ACTIVE ←──┬──→ ON_LEAVE\r\n * │\r\n * ├──→ SUSPENDED ──→ ACTIVE\r\n * │\r\n * └──→ TERMINATED\r\n * ```\r\n */\r\nexport const EmployeeStatusMachine = createStateMachine({\r\n states: ['active', 'on_leave', 'suspended', 'terminated'] as const,\r\n initial: 'active',\r\n transitions: [\r\n // Leave management\r\n { from: 'active', to: 'on_leave' },\r\n { from: 'on_leave', to: 'active' },\r\n\r\n // Suspension\r\n { from: ['active', 'on_leave'], to: 'suspended' },\r\n { from: 'suspended', to: 'active' },\r\n\r\n // Termination (from any state)\r\n { from: ['active', 'on_leave', 'suspended'], to: 'terminated' },\r\n\r\n // Re-hire (back to active)\r\n { from: 'terminated', to: 'active' },\r\n ],\r\n terminal: [], // No terminal states (re-hire possible)\r\n});\r\n\r\nexport type EmployeeStatusState = typeof EmployeeStatusMachine.states[number];\r\n\r\n// ============================================================================\r\n// Exports\r\n// ============================================================================\r\n\r\nexport {\r\n StateMachine,\r\n createStateMachine,\r\n type StateMachineConfig,\r\n type StateTransition,\r\n type TransitionResult,\r\n} from './state-machine.js';\r\n","/**\n * @classytic/payroll - TaxWithholding Model\n *\n * Mongoose schema for tax withholding tracking with aggregation support\n */\n\nimport mongoose, { Schema, Model } from 'mongoose';\nimport type {\n TaxWithholdingDocument,\n TaxType,\n TaxStatus,\n} from '../types.js';\nimport {\n TAX_STATUS,\n TAX_TYPE_VALUES,\n TAX_STATUS_VALUES,\n} from '../enums.js';\nimport { TaxStatusMachine } from '../core/payroll-states.js';\nimport { logger } from '../utils/logger.js';\nimport { periodSchema } from '../schemas/common.js';\n\n// ============================================================================\n// Schema Definition\n// ============================================================================\n\nconst taxWithholdingSchema = new Schema(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'Organization',\n },\n employeeId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'Employee',\n },\n userId: {\n type: Schema.Types.ObjectId,\n required: false,\n ref: 'User',\n },\n payrollRecordId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'PayrollRecord',\n },\n transactionId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'Transaction',\n },\n\n period: {\n type: periodSchema,\n required: true,\n },\n\n amount: {\n type: Number,\n required: true,\n min: 0,\n },\n currency: {\n type: String,\n default: 'USD',\n },\n\n taxType: {\n type: String,\n enum: TAX_TYPE_VALUES,\n required: true,\n },\n taxRate: {\n type: Number,\n required: true,\n min: 0,\n max: 1,\n },\n taxableAmount: {\n type: Number,\n required: true,\n min: 0,\n },\n\n status: {\n type: String,\n enum: TAX_STATUS_VALUES,\n default: 'pending',\n },\n\n submittedAt: Date,\n paidAt: Date,\n governmentTransactionId: {\n type: Schema.Types.ObjectId,\n ref: 'Transaction',\n },\n referenceNumber: String,\n\n // Void metadata (when payroll is voided/reversed)\n voidedAt: { type: Date },\n voidedBy: { type: Schema.Types.ObjectId, ref: 'User' },\n voidReason: { type: String },\n voidMetadata: { type: Schema.Types.Mixed },\n\n notes: String,\n metadata: { type: Schema.Types.Mixed, default: {} },\n },\n { timestamps: true }\n);\n\n// ============================================================================\n// Indexes\n// ============================================================================\n\ntaxWithholdingSchema.index({ organizationId: 1, status: 1, 'period.year': 1, 'period.month': 1 });\ntaxWithholdingSchema.index({ employeeId: 1, 'period.year': -1, 'period.month': -1 });\ntaxWithholdingSchema.index({ payrollRecordId: 1 });\ntaxWithholdingSchema.index({ transactionId: 1 });\ntaxWithholdingSchema.index({ organizationId: 1, taxType: 1, status: 1 });\ntaxWithholdingSchema.index({ governmentTransactionId: 1 }, { sparse: true });\n\n// ============================================================================\n// Virtuals\n// ============================================================================\n\ntaxWithholdingSchema.virtual('isPending').get(function () {\n return this.status === TAX_STATUS.PENDING;\n});\n\ntaxWithholdingSchema.virtual('isPaid').get(function () {\n return this.status === TAX_STATUS.PAID;\n});\n\ntaxWithholdingSchema.virtual('isSubmitted').get(function () {\n return this.status === TAX_STATUS.SUBMITTED;\n});\n\n// ============================================================================\n// Methods\n// ============================================================================\n\ntaxWithholdingSchema.methods.markAsSubmitted = function (submittedAt = new Date()) {\n // Validate state transition\n const transition = TaxStatusMachine.validateTransition(this.status, TAX_STATUS.SUBMITTED);\n if (!transition.success) {\n throw new Error(transition.error);\n }\n\n this.status = TAX_STATUS.SUBMITTED;\n this.submittedAt = submittedAt;\n\n logger.info('Tax withholding marked as submitted', {\n withholdingId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n taxType: this.taxType,\n amount: this.amount,\n });\n};\n\ntaxWithholdingSchema.methods.markAsPaid = function (\n transactionId: mongoose.Types.ObjectId,\n referenceNumber?: string,\n paidAt = new Date()\n) {\n // Validate state transition\n const transition = TaxStatusMachine.validateTransition(this.status, TAX_STATUS.PAID);\n if (!transition.success) {\n throw new Error(transition.error);\n }\n\n this.status = TAX_STATUS.PAID;\n this.governmentTransactionId = transactionId;\n this.referenceNumber = referenceNumber;\n this.paidAt = paidAt;\n\n logger.info('Tax withholding marked as paid', {\n withholdingId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n taxType: this.taxType,\n amount: this.amount,\n referenceNumber,\n });\n};\n\n// ============================================================================\n// Statics\n// ============================================================================\n\ntaxWithholdingSchema.statics.findByPeriod = function (\n organizationId: mongoose.Types.ObjectId,\n month: number,\n year: number\n) {\n return this.find({\n organizationId,\n 'period.month': month,\n 'period.year': year,\n });\n};\n\ntaxWithholdingSchema.statics.findByEmployee = function (\n employeeId: mongoose.Types.ObjectId,\n options: { year?: number; taxType?: TaxType; status?: TaxStatus; limit?: number } = {}\n) {\n const query: Record<string, unknown> = { employeeId };\n\n if (options.year) {\n query['period.year'] = options.year;\n }\n if (options.taxType) {\n query.taxType = options.taxType;\n }\n if (options.status) {\n query.status = options.status;\n }\n\n return this.find(query)\n .sort({ 'period.year': -1, 'period.month': -1 })\n .limit(options.limit || 50);\n};\n\ntaxWithholdingSchema.statics.findPending = function (\n organizationId: mongoose.Types.ObjectId,\n options: {\n fromMonth?: number;\n fromYear?: number;\n toMonth?: number;\n toYear?: number;\n taxType?: TaxType;\n } = {}\n) {\n const query: Record<string, unknown> = {\n organizationId,\n status: TAX_STATUS.PENDING,\n };\n\n if (options.taxType) {\n query.taxType = options.taxType;\n }\n\n if (options.fromMonth && options.fromYear) {\n query.$or = query.$or || [];\n (query.$or as Array<Record<string, unknown>>).push({\n $and: [\n { 'period.year': { $gt: options.fromYear } },\n ],\n });\n (query.$or as Array<Record<string, unknown>>).push({\n $and: [\n { 'period.year': options.fromYear },\n { 'period.month': { $gte: options.fromMonth } },\n ],\n });\n }\n\n if (options.toMonth && options.toYear) {\n const existingOr = query.$or;\n delete query.$or;\n\n query.$and = query.$and || [];\n if (existingOr) {\n (query.$and as Array<Record<string, unknown>>).push({ $or: existingOr });\n }\n\n (query.$and as Array<Record<string, unknown>>).push({\n $or: [\n { 'period.year': { $lt: options.toYear } },\n {\n $and: [\n { 'period.year': options.toYear },\n { 'period.month': { $lte: options.toMonth } },\n ],\n },\n ],\n });\n }\n\n return this.find(query).sort({ 'period.year': 1, 'period.month': 1 });\n};\n\ntaxWithholdingSchema.statics.getSummaryByType = function (\n organizationId: mongoose.Types.ObjectId,\n fromPeriod: { month: number; year: number },\n toPeriod: { month: number; year: number }\n) {\n return this.aggregate([\n {\n $match: {\n organizationId,\n $or: [\n { 'period.year': { $gt: fromPeriod.year } },\n {\n $and: [\n { 'period.year': fromPeriod.year },\n { 'period.month': { $gte: fromPeriod.month } },\n ],\n },\n ],\n $and: [\n {\n $or: [\n { 'period.year': { $lt: toPeriod.year } },\n {\n $and: [\n { 'period.year': toPeriod.year },\n { 'period.month': { $lte: toPeriod.month } },\n ],\n },\n ],\n },\n ],\n },\n },\n {\n $group: {\n _id: '$taxType',\n totalAmount: { $sum: '$amount' },\n count: { $sum: 1 },\n withholdingIds: { $push: '$_id' },\n },\n },\n {\n $project: {\n _id: 0,\n taxType: '$_id',\n totalAmount: 1,\n count: 1,\n withholdingIds: 1,\n },\n },\n ]).then((results) =>\n results.map((r) => ({\n taxType: r.taxType,\n totalAmount: r.totalAmount,\n count: r.count,\n withholdingIds: r.withholdingIds,\n }))\n );\n};\n\ntaxWithholdingSchema.statics.getByPayrollRecord = function (\n payrollRecordId: mongoose.Types.ObjectId\n) {\n return this.find({ payrollRecordId });\n};\n\ntaxWithholdingSchema.statics.getTotalByOrganization = function (\n organizationId: mongoose.Types.ObjectId,\n options: { status?: TaxStatus; year?: number } = {}\n) {\n const match: Record<string, unknown> = { organizationId };\n\n if (options.status) {\n match.status = options.status;\n }\n if (options.year) {\n match['period.year'] = options.year;\n }\n\n return this.aggregate([\n { $match: match },\n {\n $group: {\n _id: null,\n totalAmount: { $sum: '$amount' },\n count: { $sum: 1 },\n },\n },\n ]).then((results) =>\n results[0] || { totalAmount: 0, count: 0 }\n );\n};\n\n// ============================================================================\n// TTL Index Management\n// ============================================================================\n\n/**\n * Add TTL index on any date field for automatic cleanup\n *\n * Creates a TTL index that automatically deletes documents after a specified time\n * from the date stored in the field. Useful for auto-cleanup of voided tax withholdings.\n *\n * @param fieldName - Name of the date field (e.g., 'voidedAt', 'paidAt')\n * @param ttlSeconds - Time in seconds after field date when document should be deleted\n * @param options - Optional configuration\n *\n * @example Auto-delete voided withholdings after 90 days\n * ```typescript\n * await TaxWithholding.addTTLIndex('voidedAt', 90 * 24 * 60 * 60);\n * ```\n *\n * @example Auto-delete paid withholdings after 7 years\n * ```typescript\n * const YEARS = 365.25 * 24 * 60 * 60;\n * await TaxWithholding.addTTLIndex('paidAt', 7 * YEARS);\n * ```\n */\ntaxWithholdingSchema.statics.addTTLIndex = async function (\n fieldName: string,\n ttlSeconds: number,\n options: { partialFilter?: Record<string, unknown> } = {}\n): Promise<void> {\n const collection = this.collection;\n const indexName = `${fieldName}_ttl_1`;\n\n try {\n // Drop existing TTL index if it exists\n const indexes = await collection.indexes();\n const hasTTLIndex = indexes.some((idx) => idx.name === indexName);\n\n if (hasTTLIndex) {\n await collection.dropIndex(indexName);\n logger.info('Dropped existing TTL index', { indexName, fieldName });\n }\n\n // Build index options\n const indexOptions: {\n name: string;\n expireAfterSeconds: number;\n partialFilterExpression?: Record<string, unknown>;\n } = {\n name: indexName,\n expireAfterSeconds: ttlSeconds,\n };\n\n // Add partial filter to only apply TTL to documents with this field set\n // Note: MongoDB partial filters don't support $ne operator\n indexOptions.partialFilterExpression = {\n [fieldName]: { $exists: true },\n ...options.partialFilter,\n };\n\n // Create TTL index\n await collection.createIndex(\n { [fieldName]: 1 },\n indexOptions\n );\n\n logger.info('Added TTL index for auto-cleanup', {\n fieldName,\n indexName,\n expireAfterSeconds: ttlSeconds,\n retentionDays: Math.round(ttlSeconds / (24 * 60 * 60)),\n partialFilter: indexOptions.partialFilterExpression,\n });\n } catch (error) {\n logger.error('Failed to add TTL index', {\n fieldName,\n error: (error as Error).message,\n });\n throw error;\n }\n};\n\n/**\n * Remove TTL index from a field\n *\n * @param fieldName - Name of the field to remove TTL index from\n *\n * @example\n * ```typescript\n * await TaxWithholding.removeTTLIndex('voidedAt');\n * ```\n */\ntaxWithholdingSchema.statics.removeTTLIndex = async function (\n fieldName: string\n): Promise<void> {\n const collection = this.collection;\n const indexName = `${fieldName}_ttl_1`;\n\n try {\n const indexes = await collection.indexes();\n const hasTTLIndex = indexes.some((idx) => idx.name === indexName);\n\n if (hasTTLIndex) {\n await collection.dropIndex(indexName);\n logger.info('Removed TTL index', { fieldName, indexName });\n } else {\n logger.warn('TTL index not found', { fieldName, indexName });\n }\n } catch (error) {\n logger.error('Failed to remove TTL index', {\n fieldName,\n error: (error as Error).message,\n });\n throw error;\n }\n};\n\n// ============================================================================\n// Model Interface\n// ============================================================================\n\nexport interface TaxWithholdingModel extends Model<TaxWithholdingDocument> {\n findByPeriod(\n organizationId: mongoose.Types.ObjectId,\n month: number,\n year: number\n ): ReturnType<Model<TaxWithholdingDocument>['find']>;\n\n findByEmployee(\n employeeId: mongoose.Types.ObjectId,\n options?: { year?: number; taxType?: TaxType; status?: TaxStatus; limit?: number }\n ): ReturnType<Model<TaxWithholdingDocument>['find']>;\n\n findPending(\n organizationId: mongoose.Types.ObjectId,\n options?: {\n fromMonth?: number;\n fromYear?: number;\n toMonth?: number;\n toYear?: number;\n taxType?: TaxType;\n }\n ): ReturnType<Model<TaxWithholdingDocument>['find']>;\n\n getSummaryByType(\n organizationId: mongoose.Types.ObjectId,\n fromPeriod: { month: number; year: number },\n toPeriod: { month: number; year: number }\n ): Promise<\n Array<{\n taxType: TaxType;\n totalAmount: number;\n count: number;\n withholdingIds: mongoose.Types.ObjectId[];\n }>\n >;\n\n getByPayrollRecord(\n payrollRecordId: mongoose.Types.ObjectId\n ): ReturnType<Model<TaxWithholdingDocument>['find']>;\n\n getTotalByOrganization(\n organizationId: mongoose.Types.ObjectId,\n options?: { status?: TaxStatus; year?: number }\n ): Promise<{ totalAmount: number; count: number }>;\n\n addTTLIndex(\n fieldName: string,\n ttlSeconds: number,\n options?: { partialFilter?: Record<string, unknown> }\n ): Promise<void>;\n removeTTLIndex(fieldName: string): Promise<void>;\n}\n\n// ============================================================================\n// Model Factory\n// ============================================================================\n\n/**\n * Get or create TaxWithholding model\n *\n * @example\n * const TaxWithholding = getTaxWithholdingModel();\n *\n * // With custom connection\n * const TaxWithholding = getTaxWithholdingModel(customConnection);\n */\nexport function getTaxWithholdingModel(\n connection: mongoose.Connection = mongoose.connection\n): TaxWithholdingModel {\n const modelName = 'TaxWithholding';\n\n if (connection.models[modelName]) {\n return connection.models[modelName] as TaxWithholdingModel;\n }\n\n return connection.model<TaxWithholdingDocument, TaxWithholdingModel>(\n modelName,\n taxWithholdingSchema\n );\n}\n\nexport { taxWithholdingSchema };\nexport default taxWithholdingSchema;\n","/**\n * @classytic/payroll - Tax Withholding Schema\n *\n * Re-exports from the authoritative model definition.\n * Use this for schema composition when building custom schemas.\n *\n * Single source of truth: models/tax-withholding.model.ts\n */\n\nimport {\n taxWithholdingSchema,\n getTaxWithholdingModel,\n type TaxWithholdingModel,\n} from '../models/tax-withholding.model.js';\nimport type { Schema, SchemaDefinition } from 'mongoose';\n\n// Re-export the authoritative schema\nexport { taxWithholdingSchema, getTaxWithholdingModel, type TaxWithholdingModel };\n\n// ============================================================================\n// Index Definitions (for custom schema composition)\n// ============================================================================\n\n/**\n * Recommended indexes for tax withholding collection\n */\nexport const taxWithholdingIndexes = [\n { fields: { organizationId: 1, status: 1, 'period.year': 1, 'period.month': 1 } },\n { fields: { employeeId: 1, 'period.year': -1, 'period.month': -1 } },\n { fields: { payrollRecordId: 1 } },\n { fields: { transactionId: 1 } },\n { fields: { organizationId: 1, taxType: 1, status: 1 } },\n { fields: { governmentTransactionId: 1 }, options: { sparse: true } },\n];\n\n/**\n * Apply recommended indexes to a custom tax withholding schema\n */\nexport function applyTaxWithholdingIndexes(schema: Schema): void {\n for (const { fields, options } of taxWithholdingIndexes) {\n schema.index(fields as any, options);\n }\n}\n\n// ============================================================================\n// Schema Field Extraction (for custom schema composition)\n// ============================================================================\n\n/**\n * Extract field definitions from the authoritative schema.\n * Use this when composing custom schemas that need tax withholding fields.\n *\n * @example\n * const customSchema = new Schema({\n * ...getTaxWithholdingFields(),\n * myCustomField: String,\n * });\n */\nexport function getTaxWithholdingFields(): SchemaDefinition {\n const paths = taxWithholdingSchema.paths;\n const fields: SchemaDefinition = {};\n\n for (const [key, pathObj] of Object.entries(paths)) {\n if (key === '_id' || key === '__v' || key === 'createdAt' || key === 'updatedAt') {\n continue;\n }\n fields[key] = (pathObj as { options?: SchemaDefinition[string] }).options || {};\n }\n\n return fields;\n}\n\nexport default taxWithholdingSchema;\n","/**\n * @classytic/payroll - Mongoose Schemas\n *\n * Reusable schema definitions for employee and payroll models\n * Can be spread into your own schemas\n */\n\nimport { Schema, type SchemaDefinition, type Types } from 'mongoose';\nimport {\n EMPLOYMENT_TYPE_VALUES,\n EMPLOYEE_STATUS_VALUES,\n DEPARTMENT_VALUES,\n PAYMENT_FREQUENCY_VALUES,\n ALLOWANCE_TYPE_VALUES,\n DEDUCTION_TYPE_VALUES,\n TERMINATION_REASON_VALUES,\n PAYROLL_STATUS_VALUES,\n PAYMENT_METHOD_VALUES,\n} from '../enums.js';\nimport { HRM_CONFIG } from '../config.js';\nimport { periodSchema } from './common.js';\n\n// ============================================================================\n// Schema Options (Multi-Tenant / Multi-Branch Flexibility)\n// ============================================================================\n\n/**\n * Options for configuring schema references.\n *\n * Use these to customize what collection `organizationId` references.\n * This supports multi-branch, multi-tenant, or any other hierarchy structure.\n *\n * @example\n * ```typescript\n * // Multi-branch setup (one company, multiple branches)\n * const employeeSchema = createEmployeeSchema({}, {\n * organizationRef: 'Branch',\n * });\n *\n * // Multi-tenant SaaS\n * const employeeSchema = createEmployeeSchema({}, {\n * organizationRef: 'Tenant',\n * });\n *\n * // Enterprise with workspaces\n * const employeeSchema = createEmployeeSchema({}, {\n * organizationRef: 'Workspace',\n * });\n * ```\n */\nexport interface PayrollSchemaOptions {\n /**\n * The collection name that `organizationId` references.\n *\n * This is used for Mongoose's `populate()` feature. The multi-tenant\n * plugin filters by the ObjectId value regardless of what collection\n * it references.\n *\n * @default 'Organization'\n *\n * @example 'Branch' | 'Company' | 'Tenant' | 'Workspace' | 'Team'\n */\n organizationRef?: string;\n\n /**\n * The collection name that `userId` references.\n *\n * @default 'User'\n */\n userRef?: string;\n}\n\n// ============================================================================\n// Sub-Schemas\n// ============================================================================\n\n/**\n * Allowance schema definition\n */\nexport const allowanceSchema = new Schema(\n {\n type: {\n type: String,\n enum: ALLOWANCE_TYPE_VALUES,\n required: true,\n },\n name: { type: String },\n amount: { type: Number, required: true, min: 0 },\n isPercentage: { type: Boolean, default: false },\n value: { type: Number },\n taxable: { type: Boolean, default: true },\n recurring: { type: Boolean, default: true },\n effectiveFrom: { type: Date, default: () => new Date() },\n effectiveTo: { type: Date },\n },\n { _id: false }\n);\n\n/**\n * Deduction schema definition\n */\nexport const deductionSchema = new Schema(\n {\n type: {\n type: String,\n enum: DEDUCTION_TYPE_VALUES,\n required: true,\n },\n name: { type: String },\n amount: { type: Number, required: true, min: 0 },\n isPercentage: { type: Boolean, default: false },\n value: { type: Number },\n auto: { type: Boolean, default: false },\n recurring: { type: Boolean, default: true },\n effectiveFrom: { type: Date, default: () => new Date() },\n effectiveTo: { type: Date },\n description: { type: String },\n },\n { _id: false }\n);\n\n/**\n * Compensation schema definition\n */\nexport const compensationSchema = new Schema(\n {\n baseAmount: { type: Number, required: true, min: 0 },\n frequency: {\n type: String,\n enum: PAYMENT_FREQUENCY_VALUES,\n default: 'monthly',\n },\n currency: { type: String }, // No default - use config or USD fallback in application logic\n allowances: [allowanceSchema],\n deductions: [deductionSchema],\n grossSalary: { type: Number, default: 0 },\n netSalary: { type: Number, default: 0 },\n effectiveFrom: { type: Date, default: () => new Date() },\n lastModified: { type: Date, default: () => new Date() },\n },\n { _id: false }\n);\n\n/**\n * Work schedule schema definition\n */\nexport const workScheduleSchema = new Schema(\n {\n hoursPerWeek: { type: Number, min: 0, max: 168 },\n hoursPerDay: { type: Number, min: 0, max: 24 },\n workingDays: [{ type: Number, min: 0, max: 6 }],\n shiftStart: { type: String },\n shiftEnd: { type: String },\n },\n { _id: false }\n);\n\n/**\n * Bank details schema definition\n */\nexport const bankDetailsSchema = new Schema(\n {\n accountName: { type: String },\n accountNumber: { type: String },\n bankName: { type: String },\n branchName: { type: String },\n routingNumber: { type: String },\n },\n { _id: false }\n);\n\n/**\n * Employment history entry schema\n */\nexport const employmentHistorySchema = new Schema(\n {\n hireDate: { type: Date, required: true },\n terminationDate: { type: Date, required: true },\n reason: { type: String, enum: TERMINATION_REASON_VALUES },\n finalSalary: { type: Number },\n position: { type: String },\n department: { type: String },\n notes: { type: String },\n },\n { timestamps: true }\n);\n\n/**\n * Payroll stats schema (pre-calculated)\n */\nexport const payrollStatsSchema = new Schema(\n {\n totalPaid: { type: Number, default: 0, min: 0 },\n lastPaymentDate: { type: Date },\n nextPaymentDate: { type: Date },\n paymentsThisYear: { type: Number, default: 0, min: 0 },\n averageMonthly: { type: Number, default: 0, min: 0 },\n updatedAt: { type: Date, default: () => new Date() },\n },\n { _id: false }\n);\n\n// ============================================================================\n// Employment Fields (Spread into Employee Schema)\n// ============================================================================\n\n/**\n * Employment fields to spread into your Employee schema.\n * Use `createEmploymentFields()` for configurable references.\n */\n/**\n * Create employment fields with configurable references.\n *\n * @param options - Schema options for configuring references\n * @returns SchemaDefinition for employment fields\n */\nexport function createEmploymentFields(options: PayrollSchemaOptions = {}): SchemaDefinition {\n const { organizationRef = 'Organization', userRef = 'User' } = options;\n\n return {\n userId: {\n type: Schema.Types.ObjectId,\n ref: userRef,\n required: false, // Allow guest employees (no user account)\n },\n email: {\n type: String,\n trim: true,\n lowercase: true,\n required: false, // For guest employees without user account\n },\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: organizationRef, // Configurable: 'Branch', 'Company', 'Tenant', etc.\n required: true,\n },\n employeeId: { type: String, required: true },\n employmentType: {\n type: String,\n enum: EMPLOYMENT_TYPE_VALUES,\n default: 'full_time',\n },\n status: {\n type: String,\n enum: EMPLOYEE_STATUS_VALUES,\n default: 'active',\n },\n department: { type: String, enum: DEPARTMENT_VALUES },\n position: { type: String, required: true },\n hireDate: { type: Date, required: true },\n terminationDate: { type: Date },\n probationEndDate: { type: Date },\n employmentHistory: [employmentHistorySchema],\n compensation: { type: compensationSchema, required: true },\n workSchedule: workScheduleSchema,\n bankDetails: bankDetailsSchema,\n payrollStats: { type: payrollStatsSchema, default: () => ({}) },\n };\n}\n\n\n// ============================================================================\n// Payroll Record Sub-Schemas\n// ============================================================================\n\n/**\n * Payroll breakdown schema\n */\nexport const payrollBreakdownSchema = new Schema(\n {\n baseAmount: { type: Number, required: true, min: 0 },\n allowances: [\n {\n type: { type: String, required: true },\n amount: { type: Number, required: true, min: 0 },\n taxable: { type: Boolean, default: true },\n },\n ],\n deductions: [\n {\n type: { type: String, required: true },\n amount: { type: Number, required: true, min: 0 },\n description: { type: String },\n },\n ],\n grossSalary: { type: Number, required: true, min: 0 },\n netSalary: { type: Number, required: true, min: 0 },\n taxableAmount: { type: Number, default: 0, min: 0 },\n taxAmount: { type: Number, default: 0, min: 0 },\n workingDays: { type: Number, min: 0 },\n actualDays: { type: Number, min: 0 },\n proRatedAmount: { type: Number, default: 0, min: 0 },\n attendanceDeduction: { type: Number, default: 0, min: 0 },\n overtimeAmount: { type: Number, default: 0, min: 0 },\n bonusAmount: { type: Number, default: 0, min: 0 },\n },\n { _id: false }\n);\n\n/**\n * Payroll period schema (imported from common to avoid circular dependencies)\n * Re-exported for external use\n */\nexport { periodSchema };\n\n/**\n * Create payroll record fields with configurable references.\n *\n * @param options - Schema options for configuring references\n * @returns SchemaDefinition for payroll record fields\n */\nexport function createPayrollRecordFields(options: PayrollSchemaOptions = {}): SchemaDefinition {\n const { organizationRef = 'Organization', userRef = 'User' } = options;\n\n return {\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: organizationRef, // Configurable: 'Branch', 'Company', 'Tenant', etc.\n required: true,\n },\n employeeId: {\n type: Schema.Types.ObjectId,\n required: true,\n },\n userId: {\n type: Schema.Types.ObjectId,\n ref: userRef,\n required: false, // Optional for guest employees\n },\n period: { type: periodSchema, required: true },\n breakdown: { type: payrollBreakdownSchema, required: true },\n transactionId: { type: Schema.Types.ObjectId },\n status: {\n type: String,\n enum: PAYROLL_STATUS_VALUES,\n default: 'pending',\n },\n paidAt: { type: Date },\n processedAt: { type: Date },\n paymentMethod: { type: String, enum: PAYMENT_METHOD_VALUES },\n metadata: { type: Schema.Types.Mixed },\n processedBy: { type: Schema.Types.ObjectId, ref: userRef },\n notes: { type: String },\n payslipUrl: { type: String },\n exported: { type: Boolean, default: false },\n exportedAt: { type: Date },\n // Void / Reversal fields (v2.4.0+)\n isVoided: { type: Boolean, default: false },\n voidedAt: { type: Date },\n voidedBy: { type: Schema.Types.ObjectId, ref: userRef },\n voidReason: { type: String },\n reversedAt: { type: Date },\n reversedBy: { type: Schema.Types.ObjectId, ref: userRef },\n reversalReason: { type: String },\n reversalTransactionId: { type: Schema.Types.ObjectId },\n originalPayrollId: { type: Schema.Types.ObjectId },\n // TTL expiration (per-document)\n expireAt: { type: Date },\n };\n}\n\n\n// ============================================================================\n// Index Definitions\n// ============================================================================\n\n/**\n * Recommended indexes for Employee schema\n */\nexport const employeeIndexes = [\n { fields: { organizationId: 1, employeeId: 1 }, options: { unique: true } },\n // Partial unique index: Only includes docs with userId field (excludes guest employees)\n // Uses partialFilterExpression instead of sparse for compound indexes\n {\n fields: { userId: 1, organizationId: 1 },\n options: {\n unique: true,\n partialFilterExpression: { userId: { $exists: true } }\n }\n },\n // Partial unique index: Only includes non-terminated docs with email\n // This allows email reuse when employees are terminated and rehired\n {\n fields: { email: 1, organizationId: 1 },\n options: {\n unique: true,\n partialFilterExpression: {\n email: { $exists: true },\n status: { $in: ['active', 'on_leave', 'suspended'] }\n }\n }\n },\n { fields: { organizationId: 1, status: 1 } },\n { fields: { organizationId: 1, department: 1 } },\n { fields: { organizationId: 1, 'compensation.netSalary': -1 } },\n];\n\n/**\n * Recommended indexes for PayrollRecord schema\n *\n * Note: No unique constraint on employee+period - handled at application level\n * to support re-processing after reversal. Add your own unique index if needed.\n */\nexport const payrollRecordIndexes = [\n // Composite index for common queries (not unique - app handles duplicates)\n { fields: { organizationId: 1, employeeId: 1, 'period.month': 1, 'period.year': 1 } },\n { fields: { organizationId: 1, 'period.year': 1, 'period.month': 1 } },\n { fields: { employeeId: 1, 'period.year': -1, 'period.month': -1 } },\n { fields: { status: 1, createdAt: -1 } },\n { fields: { organizationId: 1, status: 1, 'period.payDate': 1 } },\n {\n fields: { createdAt: 1 },\n options: {\n expireAfterSeconds: HRM_CONFIG.dataRetention.payrollRecordsTTL,\n // TTL applies to ALL records (user handles backups/exports at app level)\n },\n },\n];\n\n/**\n * Apply indexes to schema\n */\nexport function applyEmployeeIndexes(schema: Schema): void {\n for (const { fields, options } of employeeIndexes) {\n schema.index(fields as unknown as Record<string, 1 | -1>, options);\n }\n}\n\n/**\n * Apply payroll record indexes to schema\n */\nexport function applyPayrollRecordIndexes(schema: Schema): void {\n for (const { fields, options } of payrollRecordIndexes) {\n schema.index(fields as unknown as Record<string, 1 | -1>, options);\n }\n}\n\n// ============================================================================\n// Complete Schema Creators\n// ============================================================================\n\n/**\n * Create a complete Employee schema with all HRM fields.\n *\n * @param additionalFields - Extra fields to add to the schema\n * @param options - Schema options (organizationRef, userRef)\n * @returns Mongoose Schema for Employee\n *\n * @example\n * ```typescript\n * // Default (references 'Organization')\n * const employeeSchema = createEmployeeSchema();\n *\n * // Multi-branch setup\n * const employeeSchema = createEmployeeSchema({}, {\n * organizationRef: 'Branch',\n * });\n *\n * // With additional fields\n * const employeeSchema = createEmployeeSchema({\n * customField: { type: String },\n * }, {\n * organizationRef: 'Company',\n * });\n * ```\n */\nexport function createEmployeeSchema(\n additionalFields: SchemaDefinition = {},\n options: PayrollSchemaOptions = {}\n): Schema {\n const schema = new Schema(\n {\n ...createEmploymentFields(options),\n ...additionalFields,\n },\n { timestamps: true }\n );\n\n // Note: Pre-save hooks are not needed for partial indexes since:\n // - Guest employees use insertOne() which bypasses Mongoose hooks\n // - User-linked employees use Model.create() which properly sets userId\n // - Partial indexes with partialFilterExpression handle inclusion/exclusion\n\n applyEmployeeIndexes(schema);\n return schema;\n}\n\n/**\n * Create a complete PayrollRecord schema.\n *\n * @param additionalFields - Extra fields to add to the schema\n * @param options - Schema options (organizationRef, userRef)\n * @returns Mongoose Schema for PayrollRecord\n *\n * @example\n * ```typescript\n * // Multi-branch setup\n * const payrollRecordSchema = createPayrollRecordSchema({}, {\n * organizationRef: 'Branch',\n * });\n * ```\n */\nexport function createPayrollRecordSchema(\n additionalFields: SchemaDefinition = {},\n options: PayrollSchemaOptions = {}\n): Schema {\n const schema = new Schema(\n {\n ...createPayrollRecordFields(options),\n ...additionalFields,\n },\n { timestamps: true }\n );\n\n applyPayrollRecordIndexes(schema);\n\n // Virtual: totalAmount\n schema.virtual('totalAmount').get(function () {\n return this.breakdown?.netSalary || 0;\n });\n\n // Virtual: isPaid\n schema.virtual('isPaid').get(function () {\n return this.status === 'paid';\n });\n\n // Virtual: periodLabel\n schema.virtual('periodLabel').get(function () {\n const months = [\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',\n ];\n return `${months[this.period.month - 1]} ${this.period.year}`;\n });\n\n // Method: markAsPaid\n schema.methods.markAsPaid = function (\n transactionId: Types.ObjectId,\n paidAt = new Date()\n ) {\n this.status = 'paid';\n this.transactionId = transactionId;\n this.paidAt = paidAt;\n };\n\n // Method: markAsExported\n schema.methods.markAsExported = function () {\n this.exported = true;\n this.exportedAt = new Date();\n };\n\n // Method: canBeDeleted\n schema.methods.canBeDeleted = function (): boolean {\n return this.exported && this.status === 'paid';\n };\n\n return schema;\n}\n\n\n// ============================================================================\n// Leave Schemas\n// ============================================================================\n\nexport {\n leaveBalanceSchema,\n leaveBalanceFields,\n leaveRequestSchema,\n leaveRequestIndexes,\n leaveRequestTTLIndex,\n applyLeaveRequestIndexes,\n getLeaveRequestFields,\n getLeaveRequestModel,\n} from './leave.js';\n\n// ============================================================================\n// Tax Withholding Schemas\n// ============================================================================\n\nexport {\n taxWithholdingSchema,\n taxWithholdingIndexes,\n applyTaxWithholdingIndexes,\n getTaxWithholdingFields,\n getTaxWithholdingModel,\n} from './tax-withholding.js';\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default {\n // Sub-schemas\n allowanceSchema,\n deductionSchema,\n compensationSchema,\n workScheduleSchema,\n bankDetailsSchema,\n employmentHistorySchema,\n payrollStatsSchema,\n payrollBreakdownSchema,\n periodSchema,\n // Field creators (configurable references)\n createEmploymentFields,\n createPayrollRecordFields,\n // Indexes\n employeeIndexes,\n payrollRecordIndexes,\n applyEmployeeIndexes,\n applyPayrollRecordIndexes,\n // Schema creators\n createEmployeeSchema,\n createPayrollRecordSchema,\n};\n\n"]}
1
+ {"version":3,"sources":["../../src/enums.ts","../../src/schemas/common.ts","../../src/utils/logger.ts","../../src/models/leave-request.model.ts","../../src/schemas/leave.ts","../../src/core/state-machine.ts","../../src/core/payroll-states.ts","../../src/models/tax-withholding.model.ts","../../src/schemas/tax-withholding.ts","../../src/schemas/index.ts"],"names":["Schema","mongoose"],"mappings":";;;;;AAwBO,IAAM,eAAA,GAAkB;AAAA,EAC7B,SAAA,EAAW,WAAA;AAAA,EACX,SAAA,EAAW,WAAA;AAAA,EACX,QAAA,EAAU,UAAA;AAAA,EACV,MAAA,EAAQ,QAAA;AAAA,EACR,UAAA,EAAY;AACd,CAAA;AAEO,IAAM,sBAAA,GAAyB,MAAA,CAAO,MAAA,CAAO,eAAe,CAAA;AAU5D,IAAM,eAAA,GAAkB;AAAA,EAC7B,MAAA,EAAQ,QAAA;AAAA,EACR,QAAA,EAAU,UAAA;AAAA,EACV,SAAA,EAAW,WAAA;AAAA,EACX,UAAA,EAAY;AACd,CAAA;AAEO,IAAM,sBAAA,GAAyB,MAAA,CAAO,MAAA,CAAO,eAAe,CAAA;AAsB5D,IAAM,UAAA,GAAa;AAAA,EACxB,UAAA,EAAY,YAAA;AAAA,EACZ,QAAA,EAAU,UAAA;AAAA,EACV,KAAA,EAAO,OAAA;AAAA,EACP,UAAA,EAAY,YAAA;AAAA,EACZ,OAAA,EAAS,SAAA;AAAA,EACT,EAAA,EAAI,IAAA;AAAA,EACJ,WAAA,EAAa,aAAA;AAAA,EACb,SAAA,EAAW,WAAA;AAAA,EACX,OAAA,EAAS,SAAA;AAAA,EACT,EAAA,EAAI;AACN,CAAA;AAEO,IAAM,iBAAA,GAAoB,MAAA,CAAO,MAAA,CAAO,UAAU,CAAA;AAUlD,IAAM,iBAAA,GAAoB;AAAA,EAC/B,OAAA,EAAS,SAAA;AAAA,EACT,SAAA,EAAW,WAAA;AAAA,EACX,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ,QAAA;AAAA,EACR,KAAA,EAAO;AACT,CAAA;AAEO,IAAM,wBAAA,GAA2B,MAAA,CAAO,MAAA,CAAO,iBAAiB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K,EAClB;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,aAAA,GAAgB,aAAA;AACrB,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB,CAAA;AAGA,EAAA,MAAA,CAAO,OAAA,CAAQ,iBAAiB,WAAY;AAC1C,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA;AAChB,IAAA,IAAA,CAAK,UAAA,uBAAiB,IAAA,EAAK;AAAA,EAC7B,CAAA;AAGA,EAAA,MAAA,CAAO,OAAA,CAAQ,eAAe,WAAqB;AACjD,IAAA,OAAO,IAAA,CAAK,QAAA,IAAY,IAAA,CAAK,MAAA,KAAW,MAAA;AAAA,EAC1C,CAAA;AAEA,EAAA,OAAO,MAAA;AACT;AAkCA,IAAO,eAAA,GAAQ;AAAA;AAAA,EAEb,eAAA;AAAA,EACA,eAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,uBAAA;AAAA,EACA,kBAAA;AAAA,EACA,sBAAA;AAAA,EACA,YAAA;AAAA;AAAA,EAEA,sBAAA;AAAA,EACA,yBAAA;AAAA;AAAA,EAEA,eAAA;AAAA,EACA,oBAAA;AAAA,EACA,oBAAA;AAAA,EACA,yBAAA;AAAA;AAAA,EAEA,oBAAA;AAAA,EACA;AACF","file":"index.js","sourcesContent":["/**\n * @classytic/payroll - Enums\n *\n * Type-safe enum definitions with const assertions\n * Single source of truth for all enum values\n */\n\nimport type {\n EmploymentType,\n EmployeeStatus,\n Department,\n PaymentFrequency,\n PaymentMethod,\n AllowanceType,\n DeductionType,\n PayrollStatus,\n TerminationReason,\n SalaryBand,\n} from './types.js';\n\n// ============================================================================\n// Employment Type\n// ============================================================================\n\nexport const EMPLOYMENT_TYPE = {\n FULL_TIME: 'full_time',\n PART_TIME: 'part_time',\n CONTRACT: 'contract',\n INTERN: 'intern',\n CONSULTANT: 'consultant',\n} as const satisfies Record<string, EmploymentType>;\n\nexport const EMPLOYMENT_TYPE_VALUES = Object.values(EMPLOYMENT_TYPE);\n\nexport function isValidEmploymentType(value: string): value is EmploymentType {\n return EMPLOYMENT_TYPE_VALUES.includes(value as EmploymentType);\n}\n\n// ============================================================================\n// Employee Status\n// ============================================================================\n\nexport const EMPLOYEE_STATUS = {\n ACTIVE: 'active',\n ON_LEAVE: 'on_leave',\n SUSPENDED: 'suspended',\n TERMINATED: 'terminated',\n} as const satisfies Record<string, EmployeeStatus>;\n\nexport const EMPLOYEE_STATUS_VALUES = Object.values(EMPLOYEE_STATUS);\n\nexport function isValidEmployeeStatus(value: string): value is EmployeeStatus {\n return EMPLOYEE_STATUS_VALUES.includes(value as EmployeeStatus);\n}\n\nexport function isActiveStatus(status: EmployeeStatus): boolean {\n return status === EMPLOYEE_STATUS.ACTIVE;\n}\n\nexport function isEmployedStatus(status: EmployeeStatus): boolean {\n return status !== EMPLOYEE_STATUS.TERMINATED;\n}\n\nexport function canReceiveSalaryStatus(status: EmployeeStatus): boolean {\n return status === EMPLOYEE_STATUS.ACTIVE || status === EMPLOYEE_STATUS.ON_LEAVE;\n}\n\n// ============================================================================\n// Department\n// ============================================================================\n\nexport const DEPARTMENT = {\n MANAGEMENT: 'management',\n TRAINING: 'training',\n SALES: 'sales',\n OPERATIONS: 'operations',\n SUPPORT: 'support',\n HR: 'hr',\n MAINTENANCE: 'maintenance',\n MARKETING: 'marketing',\n FINANCE: 'finance',\n IT: 'it',\n} as const satisfies Record<string, Department>;\n\nexport const DEPARTMENT_VALUES = Object.values(DEPARTMENT);\n\nexport function isValidDepartment(value: string): value is Department {\n return DEPARTMENT_VALUES.includes(value as Department);\n}\n\n// ============================================================================\n// Payment Frequency\n// ============================================================================\n\nexport const PAYMENT_FREQUENCY = {\n MONTHLY: 'monthly',\n BI_WEEKLY: 'bi_weekly',\n WEEKLY: 'weekly',\n HOURLY: 'hourly',\n DAILY: 'daily',\n} as const satisfies Record<string, PaymentFrequency>;\n\nexport const PAYMENT_FREQUENCY_VALUES = Object.values(PAYMENT_FREQUENCY);\n\nexport function isValidPaymentFrequency(value: string): value is PaymentFrequency {\n return PAYMENT_FREQUENCY_VALUES.includes(value as PaymentFrequency);\n}\n\n// ============================================================================\n// Payment Method\n// ============================================================================\n\nexport const PAYMENT_METHOD = {\n BANK: 'bank',\n CASH: 'cash',\n MOBILE: 'mobile',\n BKASH: 'bkash',\n NAGAD: 'nagad',\n ROCKET: 'rocket',\n CHECK: 'check',\n} as const satisfies Record<string, PaymentMethod>;\n\nexport const PAYMENT_METHOD_VALUES = Object.values(PAYMENT_METHOD);\n\nexport function isValidPaymentMethod(value: string): value is PaymentMethod {\n return PAYMENT_METHOD_VALUES.includes(value as PaymentMethod);\n}\n\n// ============================================================================\n// Allowance Type\n// ============================================================================\n\nexport const ALLOWANCE_TYPE = {\n HOUSING: 'housing',\n TRANSPORT: 'transport',\n MEAL: 'meal',\n MOBILE: 'mobile',\n MEDICAL: 'medical',\n EDUCATION: 'education',\n BONUS: 'bonus',\n OTHER: 'other',\n} as const satisfies Record<string, AllowanceType>;\n\nexport const ALLOWANCE_TYPE_VALUES = Object.values(ALLOWANCE_TYPE);\n\nexport function isValidAllowanceType(value: string): value is AllowanceType {\n return ALLOWANCE_TYPE_VALUES.includes(value as AllowanceType);\n}\n\n// ============================================================================\n// Deduction Type\n// ============================================================================\n\nexport const DEDUCTION_TYPE = {\n TAX: 'tax',\n LOAN: 'loan',\n ADVANCE: 'advance',\n PROVIDENT_FUND: 'provident_fund',\n INSURANCE: 'insurance',\n ABSENCE: 'absence',\n OTHER: 'other',\n} as const satisfies Record<string, DeductionType>;\n\nexport const DEDUCTION_TYPE_VALUES = Object.values(DEDUCTION_TYPE);\n\nexport function isValidDeductionType(value: string): value is DeductionType {\n return DEDUCTION_TYPE_VALUES.includes(value as DeductionType);\n}\n\n// ============================================================================\n// Payroll Status\n// ============================================================================\n\nexport const PAYROLL_STATUS = {\n PENDING: 'pending',\n PROCESSING: 'processing',\n PAID: 'paid',\n FAILED: 'failed',\n VOIDED: 'voided',\n REVERSED: 'reversed',\n} as const satisfies Record<string, PayrollStatus>;\n\nexport const PAYROLL_STATUS_VALUES = Object.values(PAYROLL_STATUS);\n\nexport function isValidPayrollStatus(value: string): value is PayrollStatus {\n return PAYROLL_STATUS_VALUES.includes(value as PayrollStatus);\n}\n\nexport function isCompletedPayrollStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.PAID;\n}\n\nexport function isPendingPayrollStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.PENDING || status === PAYROLL_STATUS.PROCESSING;\n}\n\n/** Check if payroll can be voided (not yet paid) */\nexport function isVoidablePayrollStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.PENDING ||\n status === PAYROLL_STATUS.PROCESSING ||\n status === PAYROLL_STATUS.FAILED;\n}\n\n/** Check if payroll requires reversal (already paid) */\nexport function requiresReversalPayrollStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.PAID;\n}\n\n/** Check if payroll is in a terminal void/reverse state */\nexport function isVoidedOrReversedStatus(status: PayrollStatus): boolean {\n return status === PAYROLL_STATUS.VOIDED || status === PAYROLL_STATUS.REVERSED;\n}\n\n// ============================================================================\n// Termination Reason\n// ============================================================================\n\nexport const TERMINATION_REASON = {\n RESIGNATION: 'resignation',\n RETIREMENT: 'retirement',\n TERMINATION: 'termination',\n CONTRACT_END: 'contract_end',\n MUTUAL_AGREEMENT: 'mutual_agreement',\n OTHER: 'other',\n} as const satisfies Record<string, TerminationReason>;\n\nexport const TERMINATION_REASON_VALUES = Object.values(TERMINATION_REASON);\n\nexport function isValidTerminationReason(value: string): value is TerminationReason {\n return TERMINATION_REASON_VALUES.includes(value as TerminationReason);\n}\n\n// ============================================================================\n// Salary Band\n// ============================================================================\n\nexport const SALARY_BAND = {\n INTERN: 'intern',\n JUNIOR: 'junior',\n MID: 'mid',\n SENIOR: 'senior',\n LEAD: 'lead',\n EXECUTIVE: 'executive',\n CUSTOM: 'custom',\n} as const satisfies Record<string, SalaryBand>;\n\nexport const SALARY_BAND_VALUES = Object.values(SALARY_BAND);\n\nexport function isValidSalaryBand(value: string): value is SalaryBand {\n return SALARY_BAND_VALUES.includes(value as SalaryBand);\n}\n\n// ============================================================================\n// Leave Type\n// ============================================================================\n\nimport type { LeaveType, LeaveRequestStatus } from './types.js';\n\nexport const LEAVE_TYPE = {\n ANNUAL: 'annual',\n SICK: 'sick',\n UNPAID: 'unpaid',\n MATERNITY: 'maternity',\n PATERNITY: 'paternity',\n BEREAVEMENT: 'bereavement',\n COMPENSATORY: 'compensatory',\n OTHER: 'other',\n} as const satisfies Record<string, LeaveType>;\n\nexport const LEAVE_TYPE_VALUES = Object.values(LEAVE_TYPE);\n\nexport function isValidLeaveType(value: string): value is LeaveType {\n return LEAVE_TYPE_VALUES.includes(value as LeaveType);\n}\n\nexport function isPaidLeaveType(type: LeaveType): boolean {\n return type !== LEAVE_TYPE.UNPAID;\n}\n\n// ============================================================================\n// Leave Request Status\n// ============================================================================\n\nexport const LEAVE_REQUEST_STATUS = {\n PENDING: 'pending',\n APPROVED: 'approved',\n REJECTED: 'rejected',\n CANCELLED: 'cancelled',\n} as const satisfies Record<string, LeaveRequestStatus>;\n\nexport const LEAVE_REQUEST_STATUS_VALUES = Object.values(LEAVE_REQUEST_STATUS);\n\nexport function isValidLeaveRequestStatus(value: string): value is LeaveRequestStatus {\n return LEAVE_REQUEST_STATUS_VALUES.includes(value as LeaveRequestStatus);\n}\n\nexport function isPendingLeaveStatus(status: LeaveRequestStatus): boolean {\n return status === LEAVE_REQUEST_STATUS.PENDING;\n}\n\nexport function isApprovedLeaveStatus(status: LeaveRequestStatus): boolean {\n return status === LEAVE_REQUEST_STATUS.APPROVED;\n}\n\n// ============================================================================\n// Tax Type\n// ============================================================================\n\nexport const TAX_TYPE = {\n INCOME_TAX: 'income_tax',\n SOCIAL_SECURITY: 'social_security',\n HEALTH_INSURANCE: 'health_insurance',\n PENSION: 'pension',\n EMPLOYMENT_INSURANCE: 'employment_insurance',\n LOCAL_TAX: 'local_tax',\n OTHER: 'other',\n} as const satisfies Record<string, import('./types.js').TaxType>;\n\nexport const TAX_TYPE_VALUES = Object.values(TAX_TYPE);\n\nexport function isValidTaxType(value: string): value is import('./types.js').TaxType {\n return TAX_TYPE_VALUES.includes(value as import('./types.js').TaxType);\n}\n\n// ============================================================================\n// Tax Status\n// ============================================================================\n\nexport const TAX_STATUS = {\n PENDING: 'pending',\n SUBMITTED: 'submitted',\n PAID: 'paid',\n CANCELLED: 'cancelled',\n} as const satisfies Record<string, import('./types.js').TaxStatus>;\n\nexport const TAX_STATUS_VALUES = Object.values(TAX_STATUS);\n\nexport function isValidTaxStatus(value: string): value is import('./types.js').TaxStatus {\n return TAX_STATUS_VALUES.includes(value as import('./types.js').TaxStatus);\n}\n\nexport function isPendingTaxStatus(status: import('./types.js').TaxStatus): boolean {\n return status === TAX_STATUS.PENDING;\n}\n\nexport function isPaidTaxStatus(status: import('./types.js').TaxStatus): boolean {\n return status === TAX_STATUS.PAID;\n}\n\nexport function isCancelledTaxStatus(status: import('./types.js').TaxStatus): boolean {\n return status === TAX_STATUS.CANCELLED;\n}\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default {\n EMPLOYMENT_TYPE,\n EMPLOYMENT_TYPE_VALUES,\n EMPLOYEE_STATUS,\n EMPLOYEE_STATUS_VALUES,\n DEPARTMENT,\n DEPARTMENT_VALUES,\n PAYMENT_FREQUENCY,\n PAYMENT_FREQUENCY_VALUES,\n PAYMENT_METHOD,\n PAYMENT_METHOD_VALUES,\n ALLOWANCE_TYPE,\n ALLOWANCE_TYPE_VALUES,\n DEDUCTION_TYPE,\n DEDUCTION_TYPE_VALUES,\n PAYROLL_STATUS,\n PAYROLL_STATUS_VALUES,\n TERMINATION_REASON,\n TERMINATION_REASON_VALUES,\n SALARY_BAND,\n SALARY_BAND_VALUES,\n LEAVE_TYPE,\n LEAVE_TYPE_VALUES,\n LEAVE_REQUEST_STATUS,\n LEAVE_REQUEST_STATUS_VALUES,\n TAX_TYPE,\n TAX_TYPE_VALUES,\n TAX_STATUS,\n TAX_STATUS_VALUES,\n};\n","/**\n * @classytic/payroll - Common Schema Definitions\n *\n * Shared sub-schemas used across multiple schema modules\n * Extracted to prevent circular dependencies\n */\n\nimport { Schema } from 'mongoose';\n\n// ============================================================================\n// Period Schema\n// ============================================================================\n\n/**\n * Payroll period schema\n * Shared across PayrollRecord and TaxWithholding schemas\n */\nexport const periodSchema = new Schema(\n {\n month: { type: Number, required: true, min: 1, max: 12 },\n year: { type: Number, required: true, min: 2020 },\n startDate: { type: Date, required: true },\n endDate: { type: Date, required: true },\n payDate: { type: Date, required: true },\n },\n { _id: false }\n);\n","/**\n * @classytic/payroll - Logger\n *\n * Pluggable logger abstraction\n * Defaults to console, can be replaced with pino, winston, etc.\n */\n\nimport type { Logger } from '../types.js';\n\n// ============================================================================\n// Default Logger Implementation\n// ============================================================================\n\nconst createConsoleLogger = (): Logger => ({\n info: (message: string, meta?: Record<string, unknown>) => {\n if (meta) {\n console.log(`[Payroll] INFO: ${message}`, meta);\n } else {\n console.log(`[Payroll] INFO: ${message}`);\n }\n },\n error: (message: string, meta?: Record<string, unknown>) => {\n if (meta) {\n console.error(`[Payroll] ERROR: ${message}`, meta);\n } else {\n console.error(`[Payroll] ERROR: ${message}`);\n }\n },\n warn: (message: string, meta?: Record<string, unknown>) => {\n if (meta) {\n console.warn(`[Payroll] WARN: ${message}`, meta);\n } else {\n console.warn(`[Payroll] WARN: ${message}`);\n }\n },\n debug: (message: string, meta?: Record<string, unknown>) => {\n if (process.env.NODE_ENV !== 'production') {\n if (meta) {\n console.log(`[Payroll] DEBUG: ${message}`, meta);\n } else {\n console.log(`[Payroll] DEBUG: ${message}`);\n }\n }\n },\n});\n\n// ============================================================================\n// Logger State\n// ============================================================================\n\nlet currentLogger: Logger = createConsoleLogger();\nlet loggingEnabled = true;\n\n// ============================================================================\n// Logger Functions\n// ============================================================================\n\n/**\n * Get the current logger instance (respects loggingEnabled flag)\n */\nexport function getLogger(): Logger {\n return {\n info: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.info(message, meta);\n },\n error: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.error(message, meta);\n },\n warn: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.warn(message, meta);\n },\n debug: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.debug(message, meta);\n },\n };\n}\n\n/**\n * Set a custom logger instance\n */\nexport function setLogger(logger: Logger): void {\n currentLogger = logger;\n}\n\n/**\n * Reset to default console logger\n */\nexport function resetLogger(): void {\n currentLogger = createConsoleLogger();\n}\n\n/**\n * Create a child logger with prefix (respects loggingEnabled flag)\n */\nexport function createChildLogger(prefix: string): Logger {\n const parent = currentLogger;\n return {\n info: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) parent.info(`[${prefix}] ${message}`, meta);\n },\n error: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) parent.error(`[${prefix}] ${message}`, meta);\n },\n warn: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) parent.warn(`[${prefix}] ${message}`, meta);\n },\n debug: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) parent.debug(`[${prefix}] ${message}`, meta);\n },\n };\n}\n\n/**\n * Create a silent logger (for testing)\n */\nexport function createSilentLogger(): Logger {\n return {\n info: () => {},\n error: () => {},\n warn: () => {},\n debug: () => {},\n };\n}\n\n/**\n * Enable logging globally\n */\nexport function enableLogging(): void {\n loggingEnabled = true;\n}\n\n/**\n * Disable logging globally (useful for production)\n */\nexport function disableLogging(): void {\n loggingEnabled = false;\n}\n\n/**\n * Check if logging is enabled\n */\nexport function isLoggingEnabled(): boolean {\n return loggingEnabled;\n}\n\n// ============================================================================\n// Logger Proxy Object\n// ============================================================================\n\n/**\n * Logger proxy that always delegates to currentLogger\n * Respects global logging enabled/disabled state\n */\nexport const logger: Logger = {\n info: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.info(message, meta);\n },\n error: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.error(message, meta);\n },\n warn: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.warn(message, meta);\n },\n debug: (message: string, meta?: Record<string, unknown>) => {\n if (loggingEnabled) currentLogger.debug(message, meta);\n },\n};\n\nexport default logger;\n\n","/**\n * @classytic/payroll - LeaveRequest Model\n *\n * Mongoose schema for leave requests with TTL support\n */\n\nimport mongoose, { Schema, Model } from 'mongoose';\nimport type {\n LeaveRequestDocument,\n LeaveType,\n LeaveRequestStatus,\n} from '../types.js';\nimport {\n LEAVE_REQUEST_STATUS,\n LEAVE_TYPE_VALUES,\n LEAVE_REQUEST_STATUS_VALUES,\n} from '../enums.js';\nimport { logger } from '../utils/logger.js';\n\n// ============================================================================\n// Schema Definition\n// ============================================================================\n\nconst leaveRequestSchema = new Schema(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n required: false, // Optional for single-tenant mode\n ref: 'Organization',\n },\n employeeId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'Employee',\n },\n userId: {\n type: Schema.Types.ObjectId,\n required: false, // Optional for guest employees\n ref: 'User',\n },\n type: {\n type: String,\n enum: LEAVE_TYPE_VALUES,\n required: true,\n },\n startDate: {\n type: Date,\n required: true,\n validate: {\n validator: function (this: { endDate?: Date }, value: Date) {\n return !this.endDate || value <= this.endDate;\n },\n message: 'Start date must be before or equal to end date',\n },\n },\n endDate: {\n type: Date,\n required: true,\n validate: {\n validator: function (this: { startDate?: Date }, value: Date) {\n return !this.startDate || value >= this.startDate;\n },\n message: 'End date must be after or equal to start date',\n },\n },\n days: {\n type: Number,\n required: true,\n min: [0.5, 'Days must be at least 0.5'],\n },\n halfDay: { type: Boolean, default: false },\n reason: String,\n status: {\n type: String,\n enum: LEAVE_REQUEST_STATUS_VALUES,\n default: 'pending',\n },\n reviewedBy: { type: Schema.Types.ObjectId, ref: 'User' },\n reviewedAt: Date,\n reviewNotes: String,\n attachments: [String],\n metadata: { type: Schema.Types.Mixed, default: {} },\n },\n { timestamps: true }\n);\n\n// ============================================================================\n// Indexes (opt-in via applyLeaveRequestIndexes)\n// ============================================================================\n\n// Note: Indexes are NOT applied automatically\n// Use applyLeaveRequestIndexes() from schemas/leave.ts if needed\n\n// ============================================================================\n// Virtuals\n// ============================================================================\n\nleaveRequestSchema.virtual('isPending').get(function () {\n return this.status === LEAVE_REQUEST_STATUS.PENDING;\n});\n\nleaveRequestSchema.virtual('isApproved').get(function () {\n return this.status === LEAVE_REQUEST_STATUS.APPROVED;\n});\n\nleaveRequestSchema.virtual('isRejected').get(function () {\n return this.status === LEAVE_REQUEST_STATUS.REJECTED;\n});\n\nleaveRequestSchema.virtual('isCancelled').get(function () {\n return this.status === LEAVE_REQUEST_STATUS.CANCELLED;\n});\n\n// ============================================================================\n// Methods\n// ============================================================================\n\nleaveRequestSchema.methods.approve = function (\n reviewerId: mongoose.Types.ObjectId,\n notes?: string\n) {\n if (this.status !== LEAVE_REQUEST_STATUS.PENDING) {\n throw new Error('Can only approve pending requests');\n }\n this.status = LEAVE_REQUEST_STATUS.APPROVED;\n this.reviewedBy = reviewerId;\n this.reviewedAt = new Date();\n if (notes) this.reviewNotes = notes;\n\n logger.info('Leave request approved', {\n requestId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n type: this.type,\n days: this.days,\n });\n};\n\nleaveRequestSchema.methods.reject = function (\n reviewerId: mongoose.Types.ObjectId,\n notes?: string\n) {\n if (this.status !== LEAVE_REQUEST_STATUS.PENDING) {\n throw new Error('Can only reject pending requests');\n }\n this.status = LEAVE_REQUEST_STATUS.REJECTED;\n this.reviewedBy = reviewerId;\n this.reviewedAt = new Date();\n if (notes) this.reviewNotes = notes;\n\n logger.info('Leave request rejected', {\n requestId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n type: this.type,\n days: this.days,\n });\n};\n\nleaveRequestSchema.methods.cancel = function () {\n if (this.status !== LEAVE_REQUEST_STATUS.PENDING) {\n throw new Error('Can only cancel pending requests');\n }\n this.status = LEAVE_REQUEST_STATUS.CANCELLED;\n\n logger.info('Leave request cancelled', {\n requestId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n type: this.type,\n days: this.days,\n });\n};\n\n// ============================================================================\n// Statics\n// ============================================================================\n\nleaveRequestSchema.statics.findByEmployee = function (\n employeeId: mongoose.Types.ObjectId,\n options: { status?: LeaveRequestStatus; year?: number; limit?: number } = {}\n) {\n const query: Record<string, unknown> = { employeeId };\n\n if (options.status) query.status = options.status;\n if (options.year) {\n query.startDate = {\n $gte: new Date(options.year, 0, 1),\n $lt: new Date(options.year + 1, 0, 1),\n };\n }\n\n return this.find(query)\n .sort({ startDate: -1 })\n .limit(options.limit || 50);\n};\n\nleaveRequestSchema.statics.findPendingByOrganization = function (\n organizationId?: mongoose.Types.ObjectId\n) {\n const query: Record<string, unknown> = {\n status: LEAVE_REQUEST_STATUS.PENDING,\n };\n\n if (organizationId) {\n query.organizationId = organizationId;\n }\n\n return this.find(query).sort({ createdAt: -1 });\n};\n\nleaveRequestSchema.statics.findByPeriod = function (\n organizationId: mongoose.Types.ObjectId | undefined,\n startDate: Date,\n endDate: Date,\n options: { status?: LeaveRequestStatus; type?: LeaveType } = {}\n) {\n const query: Record<string, unknown> = {\n $or: [\n { startDate: { $gte: startDate, $lte: endDate } },\n { endDate: { $gte: startDate, $lte: endDate } },\n {\n startDate: { $lte: startDate },\n endDate: { $gte: endDate },\n },\n ],\n };\n\n if (organizationId) {\n query.organizationId = organizationId;\n }\n\n if (options.status) query.status = options.status;\n if (options.type) query.type = options.type;\n\n return this.find(query).sort({ startDate: 1 });\n};\n\nleaveRequestSchema.statics.getLeaveStats = function (\n employeeId: mongoose.Types.ObjectId,\n year: number\n) {\n return this.aggregate([\n {\n $match: {\n employeeId,\n status: LEAVE_REQUEST_STATUS.APPROVED,\n startDate: {\n $gte: new Date(year, 0, 1),\n $lt: new Date(year + 1, 0, 1),\n },\n },\n },\n {\n $group: {\n _id: '$type',\n totalDays: { $sum: '$days' },\n count: { $sum: 1 },\n },\n },\n ]).then((results: unknown[]) =>\n results as Array<{ _id: LeaveType; totalDays: number; count: number }>\n );\n};\n\nleaveRequestSchema.statics.getOrganizationSummary = function (\n organizationId: mongoose.Types.ObjectId | undefined,\n year: number\n) {\n const matchStage: Record<string, unknown> = {\n startDate: {\n $gte: new Date(year, 0, 1),\n $lt: new Date(year + 1, 0, 1),\n },\n };\n\n if (organizationId) {\n matchStage.organizationId = organizationId;\n }\n\n return this.aggregate([\n {\n $match: matchStage,\n },\n {\n $group: {\n _id: { status: '$status', type: '$type' },\n totalDays: { $sum: '$days' },\n count: { $sum: 1 },\n },\n },\n ]);\n};\n\nleaveRequestSchema.statics.findOverlapping = function (\n employeeId: mongoose.Types.ObjectId,\n startDate: Date,\n endDate: Date,\n excludeRequestId?: mongoose.Types.ObjectId\n) {\n const query: Record<string, unknown> = {\n employeeId,\n status: { $in: [LEAVE_REQUEST_STATUS.PENDING, LEAVE_REQUEST_STATUS.APPROVED] },\n // Overlapping condition: new request overlaps with existing\n startDate: { $lte: endDate },\n endDate: { $gte: startDate },\n };\n\n if (excludeRequestId) {\n query._id = { $ne: excludeRequestId };\n }\n\n return this.find(query).sort({ startDate: 1 });\n};\n\nleaveRequestSchema.statics.hasOverlap = async function (\n employeeId: mongoose.Types.ObjectId,\n startDate: Date,\n endDate: Date,\n excludeRequestId?: mongoose.Types.ObjectId\n): Promise<boolean> {\n const query: Record<string, unknown> = {\n employeeId,\n status: { $in: [LEAVE_REQUEST_STATUS.PENDING, LEAVE_REQUEST_STATUS.APPROVED] },\n startDate: { $lte: endDate },\n endDate: { $gte: startDate },\n };\n\n if (excludeRequestId) {\n query._id = { $ne: excludeRequestId };\n }\n\n const count = await this.countDocuments(query);\n return count > 0;\n};\n\n// ============================================================================\n// Model Interface\n// ============================================================================\n\nexport interface LeaveRequestModel extends Model<LeaveRequestDocument> {\n findByEmployee(\n employeeId: mongoose.Types.ObjectId,\n options?: { status?: LeaveRequestStatus; year?: number; limit?: number }\n ): ReturnType<Model<LeaveRequestDocument>['find']>;\n\n findPendingByOrganization(\n organizationId?: mongoose.Types.ObjectId\n ): ReturnType<Model<LeaveRequestDocument>['find']>;\n\n findByPeriod(\n organizationId: mongoose.Types.ObjectId | undefined,\n startDate: Date,\n endDate: Date,\n options?: { status?: LeaveRequestStatus; type?: LeaveType }\n ): ReturnType<Model<LeaveRequestDocument>['find']>;\n\n getLeaveStats(\n employeeId: mongoose.Types.ObjectId,\n year: number\n ): Promise<Array<{ _id: LeaveType; totalDays: number; count: number }>>;\n\n getOrganizationSummary(\n organizationId: mongoose.Types.ObjectId | undefined,\n year: number\n ): Promise<\n Array<{\n _id: { status: LeaveRequestStatus; type: LeaveType };\n totalDays: number;\n count: number;\n }>\n >;\n\n findOverlapping(\n employeeId: mongoose.Types.ObjectId,\n startDate: Date,\n endDate: Date,\n excludeRequestId?: mongoose.Types.ObjectId\n ): ReturnType<Model<LeaveRequestDocument>['find']>;\n\n hasOverlap(\n employeeId: mongoose.Types.ObjectId,\n startDate: Date,\n endDate: Date,\n excludeRequestId?: mongoose.Types.ObjectId\n ): Promise<boolean>;\n}\n\n// ============================================================================\n// Model Factory\n// ============================================================================\n\n/**\n * Get or create LeaveRequest model\n *\n * @example\n * const LeaveRequest = getLeaveRequestModel();\n *\n * // With custom connection\n * const LeaveRequest = getLeaveRequestModel(customConnection);\n */\nexport function getLeaveRequestModel(\n connection: mongoose.Connection = mongoose.connection\n): LeaveRequestModel {\n const modelName = 'LeaveRequest';\n\n if (connection.models[modelName]) {\n return connection.models[modelName] as LeaveRequestModel;\n }\n\n return connection.model<LeaveRequestDocument, LeaveRequestModel>(\n modelName,\n leaveRequestSchema\n );\n}\n\nexport { leaveRequestSchema };\nexport default leaveRequestSchema;\n","/**\n * @classytic/payroll - Leave Schemas\n *\n * Leave balance sub-schema (for Employee embedding) and re-exports from\n * the authoritative LeaveRequest model definition.\n *\n * Single source of truth for LeaveRequest: models/leave-request.model.ts\n */\n\nimport { Schema, type SchemaDefinition, type IndexDefinition } from 'mongoose';\nimport { LEAVE_TYPE_VALUES, LEAVE_REQUEST_STATUS_VALUES } from '../enums.js';\nimport {\n leaveRequestSchema,\n getLeaveRequestModel,\n type LeaveRequestModel,\n} from '../models/leave-request.model.js';\n\n// Re-export the authoritative LeaveRequest schema and model\nexport { leaveRequestSchema, getLeaveRequestModel, type LeaveRequestModel };\n\n// ============================================================================\n// Leave Balance Sub-Schema (for Employee embedding)\n// ============================================================================\n\n/**\n * Leave balance schema (embedded in Employee documents)\n * This is NOT a standalone model - it's for embedding.\n */\nexport const leaveBalanceSchema = new Schema(\n {\n type: {\n type: String,\n enum: LEAVE_TYPE_VALUES,\n required: true,\n },\n allocated: { type: Number, default: 0, min: 0 },\n used: { type: Number, default: 0, min: 0 },\n pending: { type: Number, default: 0, min: 0 },\n carriedOver: { type: Number, default: 0, min: 0 },\n expiresAt: { type: Date },\n year: { type: Number, required: true },\n },\n { _id: false }\n);\n\n/**\n * Leave balance fields for embedding in Employee schema\n *\n * @example\n * const employeeSchema = new Schema({\n * ...createEmploymentFields({ organizationRef: 'Branch' }),\n * ...leaveBalanceFields,\n * });\n */\nexport const leaveBalanceFields: SchemaDefinition = {\n leaveBalances: [leaveBalanceSchema],\n};\n\n// ============================================================================\n// Index Definitions (for custom schema composition)\n// ============================================================================\n\n/**\n * Recommended indexes for LeaveRequest collection\n */\nexport const leaveRequestIndexes = [\n { fields: { organizationId: 1, employeeId: 1, startDate: -1 } },\n { fields: { organizationId: 1, status: 1, createdAt: -1 } },\n { fields: { employeeId: 1, status: 1 } },\n { fields: { organizationId: 1, type: 1, status: 1 } },\n];\n\n/**\n * TTL index config for auto-cleanup (opt-in)\n */\nexport const leaveRequestTTLIndex = {\n fields: { createdAt: 1 },\n options: {\n expireAfterSeconds: 63072000, // 2 years\n partialFilterExpression: {\n status: { $in: ['approved', 'rejected', 'cancelled'] },\n },\n },\n};\n\n/**\n * Apply indexes to a LeaveRequest schema\n */\nexport function applyLeaveRequestIndexes(\n schema: Schema,\n options: { createIndexes?: boolean; enableTTL?: boolean; ttlSeconds?: number } = {}\n): void {\n if (!options.createIndexes) return;\n\n for (const { fields } of leaveRequestIndexes) {\n schema.index(fields as unknown as IndexDefinition);\n }\n\n if (options.enableTTL) {\n schema.index(leaveRequestTTLIndex.fields as Record<string, 1>, {\n ...leaveRequestTTLIndex.options,\n expireAfterSeconds: options.ttlSeconds ?? leaveRequestTTLIndex.options.expireAfterSeconds,\n });\n }\n}\n\n// ============================================================================\n// Schema Field Extraction (for custom schema composition)\n// ============================================================================\n\n/**\n * Extract field definitions from the authoritative LeaveRequest schema.\n * Use this when composing custom schemas.\n *\n * @example\n * const customSchema = new Schema({\n * ...getLeaveRequestFields(),\n * myCustomField: String,\n * });\n */\nexport function getLeaveRequestFields(): SchemaDefinition {\n const paths = leaveRequestSchema.paths;\n const fields: SchemaDefinition = {};\n\n for (const [key, pathObj] of Object.entries(paths)) {\n if (key === '_id' || key === '__v' || key === 'createdAt' || key === 'updatedAt') {\n continue;\n }\n fields[key] = (pathObj as { options?: SchemaDefinition[string] }).options || {};\n }\n\n return fields;\n}\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default {\n leaveBalanceSchema,\n leaveBalanceFields,\n leaveRequestSchema,\n leaveRequestIndexes,\n leaveRequestTTLIndex,\n applyLeaveRequestIndexes,\n getLeaveRequestFields,\n getLeaveRequestModel,\n};\n","/**\r\n * @classytic/payroll - State Machine\r\n *\r\n * Minimal state machine implementation for status management.\r\n * Enforces valid transitions and provides clear error messages.\r\n */\r\n\r\n// ============================================================================\r\n// Types\r\n// ============================================================================\r\n\r\n/**\r\n * State transition definition\r\n */\r\nexport interface StateTransition<TState extends string> {\r\n from: TState | TState[];\r\n to: TState;\r\n}\r\n\r\n/**\r\n * State machine configuration\r\n */\r\nexport interface StateMachineConfig<TState extends string> {\r\n /** All valid states */\r\n states: readonly TState[];\r\n /** Initial state */\r\n initial: TState;\r\n /** Valid transitions */\r\n transitions: StateTransition<TState>[];\r\n /** Terminal states (no outgoing transitions) */\r\n terminal?: TState[];\r\n}\r\n\r\n/**\r\n * Transition result\r\n */\r\nexport type TransitionResult<TState extends string> =\r\n | { success: true; from: TState; to: TState }\r\n | { success: false; from: TState; to: TState; error: string };\r\n\r\n// ============================================================================\r\n// State Machine Class\r\n// ============================================================================\r\n\r\n/**\r\n * Minimal state machine for status management\r\n *\r\n * @example\r\n * const machine = new StateMachine({\r\n * states: ['pending', 'processing', 'paid', 'voided'] as const,\r\n * initial: 'pending',\r\n * transitions: [\r\n * { from: 'pending', to: 'processing' },\r\n * { from: 'pending', to: 'voided' },\r\n * { from: 'processing', to: 'paid' },\r\n * ],\r\n * terminal: ['paid', 'voided'],\r\n * });\r\n *\r\n * machine.canTransition('pending', 'processing'); // true\r\n * machine.canTransition('paid', 'pending'); // false\r\n */\r\nexport class StateMachine<TState extends string> {\r\n private readonly validTransitions: Map<TState, Set<TState>>;\r\n private readonly terminalStates: Set<TState>;\r\n\r\n constructor(private readonly config: StateMachineConfig<TState>) {\r\n // Build transition map for O(1) lookup\r\n this.validTransitions = new Map();\r\n for (const state of config.states) {\r\n this.validTransitions.set(state, new Set());\r\n }\r\n\r\n for (const transition of config.transitions) {\r\n const fromStates = Array.isArray(transition.from)\r\n ? transition.from\r\n : [transition.from];\r\n\r\n for (const from of fromStates) {\r\n this.validTransitions.get(from)?.add(transition.to);\r\n }\r\n }\r\n\r\n this.terminalStates = new Set(config.terminal || []);\r\n }\r\n\r\n /**\r\n * Get the initial state\r\n */\r\n get initial(): TState {\r\n return this.config.initial;\r\n }\r\n\r\n /**\r\n * Get all valid states\r\n */\r\n get states(): readonly TState[] {\r\n return this.config.states;\r\n }\r\n\r\n /**\r\n * Check if a state is valid\r\n */\r\n isValidState(state: string): state is TState {\r\n return this.config.states.includes(state as TState);\r\n }\r\n\r\n /**\r\n * Check if a state is terminal (no outgoing transitions)\r\n */\r\n isTerminal(state: TState): boolean {\r\n return this.terminalStates.has(state);\r\n }\r\n\r\n /**\r\n * Check if transition from one state to another is valid\r\n */\r\n canTransition(from: TState, to: TState): boolean {\r\n return this.validTransitions.get(from)?.has(to) ?? false;\r\n }\r\n\r\n /**\r\n * Get all valid next states from current state\r\n */\r\n getNextStates(from: TState): TState[] {\r\n return Array.from(this.validTransitions.get(from) || []);\r\n }\r\n\r\n /**\r\n * Validate a transition and return result\r\n */\r\n validateTransition(from: TState, to: TState): TransitionResult<TState> {\r\n if (!this.isValidState(from)) {\r\n return {\r\n success: false,\r\n from,\r\n to,\r\n error: `Invalid current state: '${from}'`,\r\n };\r\n }\r\n\r\n if (!this.isValidState(to)) {\r\n return {\r\n success: false,\r\n from,\r\n to,\r\n error: `Invalid target state: '${to}'`,\r\n };\r\n }\r\n\r\n if (this.isTerminal(from)) {\r\n return {\r\n success: false,\r\n from,\r\n to,\r\n error: `Cannot transition from terminal state '${from}'`,\r\n };\r\n }\r\n\r\n if (!this.canTransition(from, to)) {\r\n const validNext = this.getNextStates(from);\r\n return {\r\n success: false,\r\n from,\r\n to,\r\n error: `Invalid transition: '${from}' → '${to}'. Valid transitions from '${from}': [${validNext.join(', ')}]`,\r\n };\r\n }\r\n\r\n return { success: true, from, to };\r\n }\r\n\r\n /**\r\n * Assert a transition is valid, throw if not\r\n */\r\n assertTransition(from: TState, to: TState): void {\r\n const result = this.validateTransition(from, to);\r\n if (!result.success) {\r\n throw new Error(result.error);\r\n }\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Factory Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Create a state machine instance\r\n */\r\nexport function createStateMachine<TState extends string>(\r\n config: StateMachineConfig<TState>\r\n): StateMachine<TState> {\r\n return new StateMachine(config);\r\n}\r\n","/**\r\n * @classytic/payroll - Payroll State Machines\r\n *\r\n * Defines valid state transitions for all status types.\r\n * Single source of truth for status management.\r\n */\r\n\r\nimport { createStateMachine, type StateMachine } from './state-machine.js';\r\n\r\n// ============================================================================\r\n// Payroll Record Status\r\n// ============================================================================\r\n\r\n/**\r\n * PayrollStatus state machine\r\n *\r\n * State diagram:\r\n * ```\r\n * PENDING ──┬──> PROCESSING ──┬──> PAID ──> REVERSED\r\n * │ │ │\r\n * │ │ └──> FAILED ──┐\r\n * │ │ │\r\n * │ └──> VOIDED <──────────┘\r\n * │ ↑\r\n * └──────────────┘\r\n * ```\r\n *\r\n * - PENDING: Initial state, payroll created but not processed\r\n * - PROCESSING: Currently being processed (bulk operations)\r\n * - PAID: Payment completed successfully\r\n * - FAILED: Processing failed (can retry → pending, or void)\r\n * - VOIDED: Cancelled before payment (can restore → pending)\r\n * - REVERSED: Payment reversed after completion (terminal)\r\n */\r\nexport const PayrollStatusMachine = createStateMachine({\r\n states: ['pending', 'processing', 'paid', 'failed', 'voided', 'reversed'] as const,\r\n initial: 'pending',\r\n transitions: [\r\n // Normal flow\r\n { from: 'pending', to: 'processing' },\r\n { from: 'processing', to: 'paid' },\r\n\r\n // Direct payment (skip processing for single salary)\r\n { from: 'pending', to: 'paid' },\r\n\r\n // Failure handling\r\n { from: 'processing', to: 'failed' },\r\n { from: 'failed', to: 'pending' }, // Retry\r\n\r\n // Void (unpaid only - pending, processing, or failed)\r\n { from: ['pending', 'processing', 'failed'], to: 'voided' },\r\n\r\n // Reversal (paid only)\r\n { from: 'paid', to: 'reversed' },\r\n\r\n // Restore voided (back to pending for re-processing)\r\n { from: 'voided', to: 'pending' },\r\n ],\r\n terminal: ['reversed'], // Only reversed is truly terminal\r\n});\r\n\r\nexport type PayrollStatusState = typeof PayrollStatusMachine.states[number];\r\n\r\n// ============================================================================\r\n// Tax Withholding Status\r\n// ============================================================================\r\n\r\n/**\r\n * TaxStatus state machine\r\n *\r\n * State diagram:\r\n * ```\r\n * PENDING ──┬──> SUBMITTED ──> PAID\r\n * │\r\n * └──> CANCELLED\r\n * ```\r\n *\r\n * - PENDING: Tax withheld, not yet submitted to government\r\n * - SUBMITTED: Submitted to tax authority, awaiting confirmation\r\n * - PAID: Payment confirmed by tax authority\r\n * - CANCELLED: Invalidated (payroll voided/reversed)\r\n */\r\nexport const TaxStatusMachine = createStateMachine({\r\n states: ['pending', 'submitted', 'paid', 'cancelled'] as const,\r\n initial: 'pending',\r\n transitions: [\r\n { from: 'pending', to: 'submitted' },\r\n { from: 'submitted', to: 'paid' },\r\n\r\n // Direct payment (some jurisdictions)\r\n { from: 'pending', to: 'paid' },\r\n\r\n // Cancellation (from any non-terminal state)\r\n { from: ['pending', 'submitted'], to: 'cancelled' },\r\n ],\r\n terminal: ['paid', 'cancelled'],\r\n});\r\n\r\nexport type TaxStatusState = typeof TaxStatusMachine.states[number];\r\n\r\n// ============================================================================\r\n// Leave Request Status\r\n// ============================================================================\r\n\r\n/**\r\n * LeaveRequestStatus state machine\r\n *\r\n * State diagram:\r\n * ```\r\n * PENDING ──┬──> APPROVED\r\n * │\r\n * ├──> REJECTED\r\n * │\r\n * └──> CANCELLED\r\n * ```\r\n */\r\nexport const LeaveRequestStatusMachine = createStateMachine({\r\n states: ['pending', 'approved', 'rejected', 'cancelled'] as const,\r\n initial: 'pending',\r\n transitions: [\r\n { from: 'pending', to: 'approved' },\r\n { from: 'pending', to: 'rejected' },\r\n { from: 'pending', to: 'cancelled' },\r\n\r\n // Cancel approved leave (before it starts)\r\n { from: 'approved', to: 'cancelled' },\r\n ],\r\n terminal: ['rejected', 'cancelled'],\r\n});\r\n\r\nexport type LeaveRequestStatusState = typeof LeaveRequestStatusMachine.states[number];\r\n\r\n// ============================================================================\r\n// Employee Status\r\n// ============================================================================\r\n\r\n/**\r\n * EmployeeStatus state machine\r\n *\r\n * State diagram:\r\n * ```\r\n * ACTIVE ←──┬──→ ON_LEAVE\r\n * │\r\n * ├──→ SUSPENDED ──→ ACTIVE\r\n * │\r\n * └──→ TERMINATED\r\n * ```\r\n */\r\nexport const EmployeeStatusMachine = createStateMachine({\r\n states: ['active', 'on_leave', 'suspended', 'terminated'] as const,\r\n initial: 'active',\r\n transitions: [\r\n // Leave management\r\n { from: 'active', to: 'on_leave' },\r\n { from: 'on_leave', to: 'active' },\r\n\r\n // Suspension\r\n { from: ['active', 'on_leave'], to: 'suspended' },\r\n { from: 'suspended', to: 'active' },\r\n\r\n // Termination (from any state)\r\n { from: ['active', 'on_leave', 'suspended'], to: 'terminated' },\r\n\r\n // Re-hire (back to active)\r\n { from: 'terminated', to: 'active' },\r\n ],\r\n terminal: [], // No terminal states (re-hire possible)\r\n});\r\n\r\nexport type EmployeeStatusState = typeof EmployeeStatusMachine.states[number];\r\n\r\n// ============================================================================\r\n// Exports\r\n// ============================================================================\r\n\r\nexport {\r\n StateMachine,\r\n createStateMachine,\r\n type StateMachineConfig,\r\n type StateTransition,\r\n type TransitionResult,\r\n} from './state-machine.js';\r\n","/**\n * @classytic/payroll - TaxWithholding Model\n *\n * Mongoose schema for tax withholding tracking with aggregation support\n */\n\nimport mongoose, { Schema, Model } from 'mongoose';\nimport type {\n TaxWithholdingDocument,\n TaxType,\n TaxStatus,\n} from '../types.js';\nimport {\n TAX_STATUS,\n TAX_TYPE_VALUES,\n TAX_STATUS_VALUES,\n} from '../enums.js';\nimport { TaxStatusMachine } from '../core/payroll-states.js';\nimport { logger } from '../utils/logger.js';\nimport { periodSchema } from '../schemas/common.js';\n\n// ============================================================================\n// Schema Definition\n// ============================================================================\n\nconst taxWithholdingSchema = new Schema(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'Organization',\n },\n employeeId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'Employee',\n },\n userId: {\n type: Schema.Types.ObjectId,\n required: false,\n ref: 'User',\n },\n payrollRecordId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'PayrollRecord',\n },\n transactionId: {\n type: Schema.Types.ObjectId,\n required: true,\n ref: 'Transaction',\n },\n\n period: {\n type: periodSchema,\n required: true,\n },\n\n amount: {\n type: Number,\n required: true,\n min: 0,\n },\n currency: {\n type: String,\n default: 'USD',\n },\n\n taxType: {\n type: String,\n enum: TAX_TYPE_VALUES,\n required: true,\n },\n taxRate: {\n type: Number,\n required: true,\n min: 0,\n max: 1,\n },\n taxableAmount: {\n type: Number,\n required: true,\n min: 0,\n },\n\n status: {\n type: String,\n enum: TAX_STATUS_VALUES,\n default: 'pending',\n },\n\n submittedAt: Date,\n paidAt: Date,\n governmentTransactionId: {\n type: Schema.Types.ObjectId,\n ref: 'Transaction',\n },\n referenceNumber: String,\n\n // Void metadata (when payroll is voided/reversed)\n voidedAt: { type: Date },\n voidedBy: { type: Schema.Types.ObjectId, ref: 'User' },\n voidReason: { type: String },\n voidMetadata: { type: Schema.Types.Mixed },\n\n notes: String,\n metadata: { type: Schema.Types.Mixed, default: {} },\n },\n { timestamps: true }\n);\n\n// ============================================================================\n// Indexes\n// ============================================================================\n\ntaxWithholdingSchema.index({ organizationId: 1, status: 1, 'period.year': 1, 'period.month': 1 });\ntaxWithholdingSchema.index({ employeeId: 1, 'period.year': -1, 'period.month': -1 });\ntaxWithholdingSchema.index({ payrollRecordId: 1 });\ntaxWithholdingSchema.index({ transactionId: 1 });\ntaxWithholdingSchema.index({ organizationId: 1, taxType: 1, status: 1 });\ntaxWithholdingSchema.index({ governmentTransactionId: 1 }, { sparse: true });\n\n// ============================================================================\n// Virtuals\n// ============================================================================\n\ntaxWithholdingSchema.virtual('isPending').get(function () {\n return this.status === TAX_STATUS.PENDING;\n});\n\ntaxWithholdingSchema.virtual('isPaid').get(function () {\n return this.status === TAX_STATUS.PAID;\n});\n\ntaxWithholdingSchema.virtual('isSubmitted').get(function () {\n return this.status === TAX_STATUS.SUBMITTED;\n});\n\n// ============================================================================\n// Methods\n// ============================================================================\n\ntaxWithholdingSchema.methods.markAsSubmitted = function (submittedAt = new Date()) {\n // Validate state transition\n const transition = TaxStatusMachine.validateTransition(this.status, TAX_STATUS.SUBMITTED);\n if (!transition.success) {\n throw new Error(transition.error);\n }\n\n this.status = TAX_STATUS.SUBMITTED;\n this.submittedAt = submittedAt;\n\n logger.info('Tax withholding marked as submitted', {\n withholdingId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n taxType: this.taxType,\n amount: this.amount,\n });\n};\n\ntaxWithholdingSchema.methods.markAsPaid = function (\n transactionId: mongoose.Types.ObjectId,\n referenceNumber?: string,\n paidAt = new Date()\n) {\n // Validate state transition\n const transition = TaxStatusMachine.validateTransition(this.status, TAX_STATUS.PAID);\n if (!transition.success) {\n throw new Error(transition.error);\n }\n\n this.status = TAX_STATUS.PAID;\n this.governmentTransactionId = transactionId;\n this.referenceNumber = referenceNumber;\n this.paidAt = paidAt;\n\n logger.info('Tax withholding marked as paid', {\n withholdingId: this._id.toString(),\n employeeId: this.employeeId.toString(),\n taxType: this.taxType,\n amount: this.amount,\n referenceNumber,\n });\n};\n\n// ============================================================================\n// Statics\n// ============================================================================\n\ntaxWithholdingSchema.statics.findByPeriod = function (\n organizationId: mongoose.Types.ObjectId,\n month: number,\n year: number\n) {\n return this.find({\n organizationId,\n 'period.month': month,\n 'period.year': year,\n });\n};\n\ntaxWithholdingSchema.statics.findByEmployee = function (\n employeeId: mongoose.Types.ObjectId,\n options: { year?: number; taxType?: TaxType; status?: TaxStatus; limit?: number } = {}\n) {\n const query: Record<string, unknown> = { employeeId };\n\n if (options.year) {\n query['period.year'] = options.year;\n }\n if (options.taxType) {\n query.taxType = options.taxType;\n }\n if (options.status) {\n query.status = options.status;\n }\n\n return this.find(query)\n .sort({ 'period.year': -1, 'period.month': -1 })\n .limit(options.limit || 50);\n};\n\ntaxWithholdingSchema.statics.findPending = function (\n organizationId: mongoose.Types.ObjectId,\n options: {\n fromMonth?: number;\n fromYear?: number;\n toMonth?: number;\n toYear?: number;\n taxType?: TaxType;\n } = {}\n) {\n const query: Record<string, unknown> = {\n organizationId,\n status: TAX_STATUS.PENDING,\n };\n\n if (options.taxType) {\n query.taxType = options.taxType;\n }\n\n if (options.fromMonth && options.fromYear) {\n query.$or = query.$or || [];\n (query.$or as Array<Record<string, unknown>>).push({\n $and: [\n { 'period.year': { $gt: options.fromYear } },\n ],\n });\n (query.$or as Array<Record<string, unknown>>).push({\n $and: [\n { 'period.year': options.fromYear },\n { 'period.month': { $gte: options.fromMonth } },\n ],\n });\n }\n\n if (options.toMonth && options.toYear) {\n const existingOr = query.$or;\n delete query.$or;\n\n query.$and = query.$and || [];\n if (existingOr) {\n (query.$and as Array<Record<string, unknown>>).push({ $or: existingOr });\n }\n\n (query.$and as Array<Record<string, unknown>>).push({\n $or: [\n { 'period.year': { $lt: options.toYear } },\n {\n $and: [\n { 'period.year': options.toYear },\n { 'period.month': { $lte: options.toMonth } },\n ],\n },\n ],\n });\n }\n\n return this.find(query).sort({ 'period.year': 1, 'period.month': 1 });\n};\n\ntaxWithholdingSchema.statics.getSummaryByType = function (\n organizationId: mongoose.Types.ObjectId,\n fromPeriod: { month: number; year: number },\n toPeriod: { month: number; year: number }\n) {\n return this.aggregate([\n {\n $match: {\n organizationId,\n $or: [\n { 'period.year': { $gt: fromPeriod.year } },\n {\n $and: [\n { 'period.year': fromPeriod.year },\n { 'period.month': { $gte: fromPeriod.month } },\n ],\n },\n ],\n $and: [\n {\n $or: [\n { 'period.year': { $lt: toPeriod.year } },\n {\n $and: [\n { 'period.year': toPeriod.year },\n { 'period.month': { $lte: toPeriod.month } },\n ],\n },\n ],\n },\n ],\n },\n },\n {\n $group: {\n _id: '$taxType',\n totalAmount: { $sum: '$amount' },\n count: { $sum: 1 },\n withholdingIds: { $push: '$_id' },\n },\n },\n {\n $project: {\n _id: 0,\n taxType: '$_id',\n totalAmount: 1,\n count: 1,\n withholdingIds: 1,\n },\n },\n ]).then((results) =>\n results.map((r) => ({\n taxType: r.taxType,\n totalAmount: r.totalAmount,\n count: r.count,\n withholdingIds: r.withholdingIds,\n }))\n );\n};\n\ntaxWithholdingSchema.statics.getByPayrollRecord = function (\n payrollRecordId: mongoose.Types.ObjectId\n) {\n return this.find({ payrollRecordId });\n};\n\ntaxWithholdingSchema.statics.getTotalByOrganization = function (\n organizationId: mongoose.Types.ObjectId,\n options: { status?: TaxStatus; year?: number } = {}\n) {\n const match: Record<string, unknown> = { organizationId };\n\n if (options.status) {\n match.status = options.status;\n }\n if (options.year) {\n match['period.year'] = options.year;\n }\n\n return this.aggregate([\n { $match: match },\n {\n $group: {\n _id: null,\n totalAmount: { $sum: '$amount' },\n count: { $sum: 1 },\n },\n },\n ]).then((results) =>\n results[0] || { totalAmount: 0, count: 0 }\n );\n};\n\n// ============================================================================\n// TTL Index Management\n// ============================================================================\n\n/**\n * Add TTL index on any date field for automatic cleanup\n *\n * Creates a TTL index that automatically deletes documents after a specified time\n * from the date stored in the field. Useful for auto-cleanup of voided tax withholdings.\n *\n * @param fieldName - Name of the date field (e.g., 'voidedAt', 'paidAt')\n * @param ttlSeconds - Time in seconds after field date when document should be deleted\n * @param options - Optional configuration\n *\n * @example Auto-delete voided withholdings after 90 days\n * ```typescript\n * await TaxWithholding.addTTLIndex('voidedAt', 90 * 24 * 60 * 60);\n * ```\n *\n * @example Auto-delete paid withholdings after 7 years\n * ```typescript\n * const YEARS = 365.25 * 24 * 60 * 60;\n * await TaxWithholding.addTTLIndex('paidAt', 7 * YEARS);\n * ```\n */\ntaxWithholdingSchema.statics.addTTLIndex = async function (\n fieldName: string,\n ttlSeconds: number,\n options: { partialFilter?: Record<string, unknown> } = {}\n): Promise<void> {\n const collection = this.collection;\n const indexName = `${fieldName}_ttl_1`;\n\n try {\n // Drop existing TTL index if it exists\n const indexes = await collection.indexes();\n const hasTTLIndex = indexes.some((idx) => idx.name === indexName);\n\n if (hasTTLIndex) {\n await collection.dropIndex(indexName);\n logger.info('Dropped existing TTL index', { indexName, fieldName });\n }\n\n // Build index options\n const indexOptions: {\n name: string;\n expireAfterSeconds: number;\n partialFilterExpression?: Record<string, unknown>;\n } = {\n name: indexName,\n expireAfterSeconds: ttlSeconds,\n };\n\n // Add partial filter to only apply TTL to documents with this field set\n // Note: MongoDB partial filters don't support $ne operator\n indexOptions.partialFilterExpression = {\n [fieldName]: { $exists: true },\n ...options.partialFilter,\n };\n\n // Create TTL index\n await collection.createIndex(\n { [fieldName]: 1 },\n indexOptions\n );\n\n logger.info('Added TTL index for auto-cleanup', {\n fieldName,\n indexName,\n expireAfterSeconds: ttlSeconds,\n retentionDays: Math.round(ttlSeconds / (24 * 60 * 60)),\n partialFilter: indexOptions.partialFilterExpression,\n });\n } catch (error) {\n logger.error('Failed to add TTL index', {\n fieldName,\n error: (error as Error).message,\n });\n throw error;\n }\n};\n\n/**\n * Remove TTL index from a field\n *\n * @param fieldName - Name of the field to remove TTL index from\n *\n * @example\n * ```typescript\n * await TaxWithholding.removeTTLIndex('voidedAt');\n * ```\n */\ntaxWithholdingSchema.statics.removeTTLIndex = async function (\n fieldName: string\n): Promise<void> {\n const collection = this.collection;\n const indexName = `${fieldName}_ttl_1`;\n\n try {\n const indexes = await collection.indexes();\n const hasTTLIndex = indexes.some((idx) => idx.name === indexName);\n\n if (hasTTLIndex) {\n await collection.dropIndex(indexName);\n logger.info('Removed TTL index', { fieldName, indexName });\n } else {\n logger.warn('TTL index not found', { fieldName, indexName });\n }\n } catch (error) {\n logger.error('Failed to remove TTL index', {\n fieldName,\n error: (error as Error).message,\n });\n throw error;\n }\n};\n\n// ============================================================================\n// Model Interface\n// ============================================================================\n\nexport interface TaxWithholdingModel extends Model<TaxWithholdingDocument> {\n findByPeriod(\n organizationId: mongoose.Types.ObjectId,\n month: number,\n year: number\n ): ReturnType<Model<TaxWithholdingDocument>['find']>;\n\n findByEmployee(\n employeeId: mongoose.Types.ObjectId,\n options?: { year?: number; taxType?: TaxType; status?: TaxStatus; limit?: number }\n ): ReturnType<Model<TaxWithholdingDocument>['find']>;\n\n findPending(\n organizationId: mongoose.Types.ObjectId,\n options?: {\n fromMonth?: number;\n fromYear?: number;\n toMonth?: number;\n toYear?: number;\n taxType?: TaxType;\n }\n ): ReturnType<Model<TaxWithholdingDocument>['find']>;\n\n getSummaryByType(\n organizationId: mongoose.Types.ObjectId,\n fromPeriod: { month: number; year: number },\n toPeriod: { month: number; year: number }\n ): Promise<\n Array<{\n taxType: TaxType;\n totalAmount: number;\n count: number;\n withholdingIds: mongoose.Types.ObjectId[];\n }>\n >;\n\n getByPayrollRecord(\n payrollRecordId: mongoose.Types.ObjectId\n ): ReturnType<Model<TaxWithholdingDocument>['find']>;\n\n getTotalByOrganization(\n organizationId: mongoose.Types.ObjectId,\n options?: { status?: TaxStatus; year?: number }\n ): Promise<{ totalAmount: number; count: number }>;\n\n addTTLIndex(\n fieldName: string,\n ttlSeconds: number,\n options?: { partialFilter?: Record<string, unknown> }\n ): Promise<void>;\n removeTTLIndex(fieldName: string): Promise<void>;\n}\n\n// ============================================================================\n// Model Factory\n// ============================================================================\n\n/**\n * Get or create TaxWithholding model\n *\n * @example\n * const TaxWithholding = getTaxWithholdingModel();\n *\n * // With custom connection\n * const TaxWithholding = getTaxWithholdingModel(customConnection);\n */\nexport function getTaxWithholdingModel(\n connection: mongoose.Connection = mongoose.connection\n): TaxWithholdingModel {\n const modelName = 'TaxWithholding';\n\n if (connection.models[modelName]) {\n return connection.models[modelName] as TaxWithholdingModel;\n }\n\n return connection.model<TaxWithholdingDocument, TaxWithholdingModel>(\n modelName,\n taxWithholdingSchema\n );\n}\n\nexport { taxWithholdingSchema };\nexport default taxWithholdingSchema;\n","/**\n * @classytic/payroll - Tax Withholding Schema\n *\n * Re-exports from the authoritative model definition.\n * Use this for schema composition when building custom schemas.\n *\n * Single source of truth: models/tax-withholding.model.ts\n */\n\nimport {\n taxWithholdingSchema,\n getTaxWithholdingModel,\n type TaxWithholdingModel,\n} from '../models/tax-withholding.model.js';\nimport type { Schema, SchemaDefinition, IndexDefinition } from 'mongoose';\n\n// Re-export the authoritative schema\nexport { taxWithholdingSchema, getTaxWithholdingModel, type TaxWithholdingModel };\n\n// ============================================================================\n// Index Definitions (for custom schema composition)\n// ============================================================================\n\n/**\n * Recommended indexes for tax withholding collection\n */\nexport const taxWithholdingIndexes = [\n { fields: { organizationId: 1, status: 1, 'period.year': 1, 'period.month': 1 } },\n { fields: { employeeId: 1, 'period.year': -1, 'period.month': -1 } },\n { fields: { payrollRecordId: 1 } },\n { fields: { transactionId: 1 } },\n { fields: { organizationId: 1, taxType: 1, status: 1 } },\n { fields: { governmentTransactionId: 1 }, options: { sparse: true } },\n];\n\n/**\n * Apply recommended indexes to a custom tax withholding schema\n */\nexport function applyTaxWithholdingIndexes(schema: Schema): void {\n for (const { fields, options } of taxWithholdingIndexes) {\n schema.index(fields as unknown as IndexDefinition, options);\n }\n}\n\n// ============================================================================\n// Schema Field Extraction (for custom schema composition)\n// ============================================================================\n\n/**\n * Extract field definitions from the authoritative schema.\n * Use this when composing custom schemas that need tax withholding fields.\n *\n * @example\n * const customSchema = new Schema({\n * ...getTaxWithholdingFields(),\n * myCustomField: String,\n * });\n */\nexport function getTaxWithholdingFields(): SchemaDefinition {\n const paths = taxWithholdingSchema.paths;\n const fields: SchemaDefinition = {};\n\n for (const [key, pathObj] of Object.entries(paths)) {\n if (key === '_id' || key === '__v' || key === 'createdAt' || key === 'updatedAt') {\n continue;\n }\n fields[key] = (pathObj as { options?: SchemaDefinition[string] }).options || {};\n }\n\n return fields;\n}\n\nexport default taxWithholdingSchema;\n","/**\n * @classytic/payroll - Mongoose Schemas\n *\n * Reusable schema definitions for employee and payroll models\n * Can be spread into your own schemas\n */\n\nimport { Schema, type SchemaDefinition, type Types } from 'mongoose';\nimport {\n EMPLOYMENT_TYPE_VALUES,\n EMPLOYEE_STATUS_VALUES,\n DEPARTMENT_VALUES,\n PAYMENT_FREQUENCY_VALUES,\n ALLOWANCE_TYPE_VALUES,\n DEDUCTION_TYPE_VALUES,\n TERMINATION_REASON_VALUES,\n PAYROLL_STATUS_VALUES,\n PAYMENT_METHOD_VALUES,\n} from '../enums.js';\nimport { HRM_CONFIG } from '../config.js';\nimport { periodSchema } from './common.js';\n\n// ============================================================================\n// Schema Options (Multi-Tenant / Multi-Branch Flexibility)\n// ============================================================================\n\n/**\n * Options for configuring schema references.\n *\n * Use these to customize what collection `organizationId` references.\n * This supports multi-branch, multi-tenant, or any other hierarchy structure.\n *\n * @example\n * ```typescript\n * // Multi-branch setup (one company, multiple branches)\n * const employeeSchema = createEmployeeSchema({}, {\n * organizationRef: 'Branch',\n * });\n *\n * // Multi-tenant SaaS\n * const employeeSchema = createEmployeeSchema({}, {\n * organizationRef: 'Tenant',\n * });\n *\n * // Enterprise with workspaces\n * const employeeSchema = createEmployeeSchema({}, {\n * organizationRef: 'Workspace',\n * });\n * ```\n */\nexport interface PayrollSchemaOptions {\n /**\n * The collection name that `organizationId` references.\n *\n * This is used for Mongoose's `populate()` feature. The multi-tenant\n * plugin filters by the ObjectId value regardless of what collection\n * it references.\n *\n * @default 'Organization'\n *\n * @example 'Branch' | 'Company' | 'Tenant' | 'Workspace' | 'Team'\n */\n organizationRef?: string;\n\n /**\n * The collection name that `userId` references.\n *\n * @default 'User'\n */\n userRef?: string;\n}\n\n// ============================================================================\n// Sub-Schemas\n// ============================================================================\n\n/**\n * Allowance schema definition\n */\nexport const allowanceSchema = new Schema(\n {\n type: {\n type: String,\n enum: ALLOWANCE_TYPE_VALUES,\n required: true,\n },\n name: { type: String },\n amount: { type: Number, required: true, min: 0 },\n isPercentage: { type: Boolean, default: false },\n value: { type: Number },\n taxable: { type: Boolean, default: true },\n recurring: { type: Boolean, default: true },\n effectiveFrom: { type: Date, default: () => new Date() },\n effectiveTo: { type: Date },\n },\n { _id: false }\n);\n\n/**\n * Deduction schema definition\n */\nexport const deductionSchema = new Schema(\n {\n type: {\n type: String,\n enum: DEDUCTION_TYPE_VALUES,\n required: true,\n },\n name: { type: String },\n amount: { type: Number, required: true, min: 0 },\n isPercentage: { type: Boolean, default: false },\n value: { type: Number },\n auto: { type: Boolean, default: false },\n recurring: { type: Boolean, default: true },\n effectiveFrom: { type: Date, default: () => new Date() },\n effectiveTo: { type: Date },\n description: { type: String },\n },\n { _id: false }\n);\n\n/**\n * Compensation schema definition\n */\nexport const compensationSchema = new Schema(\n {\n baseAmount: { type: Number, required: true, min: 0 },\n frequency: {\n type: String,\n enum: PAYMENT_FREQUENCY_VALUES,\n default: 'monthly',\n },\n currency: { type: String }, // No default - use config or USD fallback in application logic\n allowances: [allowanceSchema],\n deductions: [deductionSchema],\n grossSalary: { type: Number, default: 0 },\n netSalary: { type: Number, default: 0 },\n effectiveFrom: { type: Date, default: () => new Date() },\n lastModified: { type: Date, default: () => new Date() },\n },\n { _id: false }\n);\n\n/**\n * Work schedule schema definition\n */\nexport const workScheduleSchema = new Schema(\n {\n hoursPerWeek: { type: Number, min: 0, max: 168 },\n hoursPerDay: { type: Number, min: 0, max: 24 },\n workingDays: [{ type: Number, min: 0, max: 6 }],\n shiftStart: { type: String },\n shiftEnd: { type: String },\n },\n { _id: false }\n);\n\n/**\n * Bank details schema definition\n */\nexport const bankDetailsSchema = new Schema(\n {\n accountName: { type: String },\n accountNumber: { type: String },\n bankName: { type: String },\n branchName: { type: String },\n routingNumber: { type: String },\n },\n { _id: false }\n);\n\n/**\n * Employment history entry schema\n */\nexport const employmentHistorySchema = new Schema(\n {\n hireDate: { type: Date, required: true },\n terminationDate: { type: Date, required: true },\n reason: { type: String, enum: TERMINATION_REASON_VALUES },\n finalSalary: { type: Number },\n position: { type: String },\n department: { type: String },\n notes: { type: String },\n },\n { timestamps: true }\n);\n\n/**\n * Payroll stats schema (pre-calculated)\n */\nexport const payrollStatsSchema = new Schema(\n {\n totalPaid: { type: Number, default: 0, min: 0 },\n lastPaymentDate: { type: Date },\n nextPaymentDate: { type: Date },\n paymentsThisYear: { type: Number, default: 0, min: 0 },\n averageMonthly: { type: Number, default: 0, min: 0 },\n updatedAt: { type: Date, default: () => new Date() },\n },\n { _id: false }\n);\n\n// ============================================================================\n// Employment Fields (Spread into Employee Schema)\n// ============================================================================\n\n/**\n * Employment fields to spread into your Employee schema.\n * Use `createEmploymentFields()` for configurable references.\n */\n/**\n * Create employment fields with configurable references.\n *\n * @param options - Schema options for configuring references\n * @returns SchemaDefinition for employment fields\n */\nexport function createEmploymentFields(options: PayrollSchemaOptions = {}): SchemaDefinition {\n const { organizationRef = 'Organization', userRef = 'User' } = options;\n\n return {\n userId: {\n type: Schema.Types.ObjectId,\n ref: userRef,\n required: false, // Allow guest employees (no user account)\n },\n email: {\n type: String,\n trim: true,\n lowercase: true,\n required: false, // For guest employees without user account\n },\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: organizationRef, // Configurable: 'Branch', 'Company', 'Tenant', etc.\n required: true,\n },\n employeeId: { type: String, required: true },\n employmentType: {\n type: String,\n enum: EMPLOYMENT_TYPE_VALUES,\n default: 'full_time',\n },\n status: {\n type: String,\n enum: EMPLOYEE_STATUS_VALUES,\n default: 'active',\n },\n department: { type: String, enum: DEPARTMENT_VALUES },\n position: { type: String, required: true },\n hireDate: { type: Date, required: true },\n terminationDate: { type: Date },\n probationEndDate: { type: Date },\n employmentHistory: [employmentHistorySchema],\n compensation: { type: compensationSchema, required: true },\n workSchedule: workScheduleSchema,\n bankDetails: bankDetailsSchema,\n payrollStats: { type: payrollStatsSchema, default: () => ({}) },\n };\n}\n\n\n// ============================================================================\n// Payroll Record Sub-Schemas\n// ============================================================================\n\n/**\n * Payroll breakdown schema\n */\nexport const payrollBreakdownSchema = new Schema(\n {\n baseAmount: { type: Number, required: true, min: 0 },\n allowances: [\n {\n type: { type: String, required: true },\n amount: { type: Number, required: true, min: 0 },\n taxable: { type: Boolean, default: true },\n },\n ],\n deductions: [\n {\n type: { type: String, required: true },\n amount: { type: Number, required: true, min: 0 },\n description: { type: String },\n },\n ],\n grossSalary: { type: Number, required: true, min: 0 },\n netSalary: { type: Number, required: true, min: 0 },\n taxableAmount: { type: Number, default: 0, min: 0 },\n taxAmount: { type: Number, default: 0, min: 0 },\n workingDays: { type: Number, min: 0 },\n actualDays: { type: Number, min: 0 },\n proRatedAmount: { type: Number, default: 0, min: 0 },\n attendanceDeduction: { type: Number, default: 0, min: 0 },\n overtimeAmount: { type: Number, default: 0, min: 0 },\n bonusAmount: { type: Number, default: 0, min: 0 },\n },\n { _id: false }\n);\n\n/**\n * Payroll period schema (imported from common to avoid circular dependencies)\n * Re-exported for external use\n */\nexport { periodSchema };\n\n/**\n * Create payroll record fields with configurable references.\n *\n * @param options - Schema options for configuring references\n * @returns SchemaDefinition for payroll record fields\n */\nexport function createPayrollRecordFields(options: PayrollSchemaOptions = {}): SchemaDefinition {\n const { organizationRef = 'Organization', userRef = 'User' } = options;\n\n return {\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: organizationRef, // Configurable: 'Branch', 'Company', 'Tenant', etc.\n required: true,\n },\n employeeId: {\n type: Schema.Types.ObjectId,\n required: true,\n },\n userId: {\n type: Schema.Types.ObjectId,\n ref: userRef,\n required: false, // Optional for guest employees\n },\n period: { type: periodSchema, required: true },\n breakdown: { type: payrollBreakdownSchema, required: true },\n transactionId: { type: Schema.Types.ObjectId },\n status: {\n type: String,\n enum: PAYROLL_STATUS_VALUES,\n default: 'pending',\n },\n paidAt: { type: Date },\n processedAt: { type: Date },\n paymentMethod: { type: String, enum: PAYMENT_METHOD_VALUES },\n metadata: { type: Schema.Types.Mixed },\n processedBy: { type: Schema.Types.ObjectId, ref: userRef },\n notes: { type: String },\n payslipUrl: { type: String },\n exported: { type: Boolean, default: false },\n exportedAt: { type: Date },\n // Void / Reversal fields (v2.4.0+)\n isVoided: { type: Boolean, default: false },\n voidedAt: { type: Date },\n voidedBy: { type: Schema.Types.ObjectId, ref: userRef },\n voidReason: { type: String },\n reversedAt: { type: Date },\n reversedBy: { type: Schema.Types.ObjectId, ref: userRef },\n reversalReason: { type: String },\n reversalTransactionId: { type: Schema.Types.ObjectId },\n originalPayrollId: { type: Schema.Types.ObjectId },\n // TTL expiration (per-document)\n expireAt: { type: Date },\n\n // Payroll run type (v2.8.0+)\n payrollRunType: {\n type: String,\n enum: ['regular', 'off-cycle', 'supplemental', 'retroactive'],\n default: 'regular',\n },\n\n // Payment frequency at time of processing (v2.9.0+)\n // Stored for proper idempotency key reconstruction in void/reverse operations\n paymentFrequency: {\n type: String,\n enum: PAYMENT_FREQUENCY_VALUES,\n default: 'monthly',\n },\n\n // Retroactive adjustment details (v2.8.0+)\n retroactiveAdjustment: {\n type: new Schema(\n {\n originalPeriod: {\n month: { type: Number, required: true, min: 1, max: 12 },\n year: { type: Number, required: true },\n },\n originalPayrollId: { type: Schema.Types.ObjectId },\n reason: { type: String, required: true },\n adjustmentAmount: { type: Number, required: true },\n approved: { type: Boolean },\n approvedBy: { type: Schema.Types.ObjectId },\n approvedAt: { type: Date },\n },\n { _id: false }\n ),\n required: false,\n },\n\n // Employer contributions (v2.8.0+)\n employerContributions: [\n {\n type: {\n type: String,\n enum: ['social_security', 'pension', 'unemployment', 'health_insurance', 'other'],\n required: true,\n },\n amount: { type: Number, required: true },\n description: { type: String },\n mandatory: { type: Boolean },\n referenceNumber: { type: String },\n },\n ],\n\n // Corrections history (v2.8.0+)\n corrections: [\n {\n previousAmount: { type: Number },\n newAmount: { type: Number },\n reason: { type: String },\n correctedBy: { type: Schema.Types.ObjectId, ref: userRef },\n correctedAt: { type: Date, default: Date.now },\n },\n ],\n };\n}\n\n\n// ============================================================================\n// Index Definitions\n// ============================================================================\n\n/**\n * Recommended indexes for Employee schema\n */\nexport const employeeIndexes = [\n { fields: { organizationId: 1, employeeId: 1 }, options: { unique: true } },\n // Partial unique index: Only includes docs with userId field (excludes guest employees)\n // Uses partialFilterExpression instead of sparse for compound indexes\n {\n fields: { userId: 1, organizationId: 1 },\n options: {\n unique: true,\n partialFilterExpression: { userId: { $exists: true } }\n }\n },\n // Partial unique index: Only includes non-terminated docs with email\n // This allows email reuse when employees are terminated and rehired\n {\n fields: { email: 1, organizationId: 1 },\n options: {\n unique: true,\n partialFilterExpression: {\n email: { $exists: true },\n status: { $in: ['active', 'on_leave', 'suspended'] }\n }\n }\n },\n { fields: { organizationId: 1, status: 1 } },\n { fields: { organizationId: 1, department: 1 } },\n { fields: { organizationId: 1, 'compensation.netSalary': -1 } },\n];\n\n/**\n * Recommended indexes for PayrollRecord schema\n *\n * Includes UNIQUE compound index on (org, employee, period, runType) with partial filter\n * to prevent race conditions while still allowing re-processing after void/reverse.\n */\nexport const payrollRecordIndexes = [\n /**\n * UNIQUE Compound Index (v2.9.0+) - PRIMARY duplicate protection\n *\n * Prevents duplicate payrolls at the database level for the same:\n * - Organization, Employee, Period (month + year + startDate), Payroll run type\n *\n * The period.startDate is critical for non-monthly frequencies (weekly, bi_weekly,\n * daily, hourly) where multiple payroll runs can occur within the same calendar month.\n *\n * Partial filter excludes voided records to allow re-processing.\n * Duplicate inserts fail with E11000 → converted to DuplicatePayrollError.\n */\n {\n fields: {\n organizationId: 1,\n employeeId: 1,\n 'period.month': 1,\n 'period.year': 1,\n 'period.startDate': 1,\n payrollRunType: 1,\n },\n options: {\n unique: true,\n name: 'unique_payroll_per_period_startdate_runtype',\n // Only enforce for non-voided records (uses $eq which is supported in partial indexes)\n // When a record is voided, isVoided is set to true, excluding it from unique constraint\n partialFilterExpression: {\n isVoided: { $eq: false },\n },\n },\n },\n // Composite index for common queries\n { fields: { organizationId: 1, employeeId: 1, 'period.month': 1, 'period.year': 1 } },\n { fields: { organizationId: 1, 'period.year': 1, 'period.month': 1 } },\n { fields: { employeeId: 1, 'period.year': -1, 'period.month': -1 } },\n { fields: { status: 1, createdAt: -1 } },\n { fields: { organizationId: 1, status: 1, 'period.payDate': 1 } },\n // Index for payroll run type queries (supplemental, retroactive, etc.)\n { fields: { organizationId: 1, payrollRunType: 1, 'period.year': 1, 'period.month': 1 } },\n // TTL index using expireAt field for per-document retention (jurisdiction-specific)\n {\n fields: { expireAt: 1 },\n options: {\n expireAfterSeconds: 0, // Delete immediately when expireAt is reached\n },\n },\n];\n\n/**\n * Apply indexes to schema\n */\nexport function applyEmployeeIndexes(schema: Schema): void {\n for (const { fields, options } of employeeIndexes) {\n schema.index(fields as unknown as Record<string, 1 | -1>, options);\n }\n}\n\n/**\n * Apply payroll record indexes to schema\n */\nexport function applyPayrollRecordIndexes(schema: Schema): void {\n for (const { fields, options } of payrollRecordIndexes) {\n schema.index(fields as unknown as Record<string, 1 | -1>, options);\n }\n}\n\n// ============================================================================\n// Complete Schema Creators\n// ============================================================================\n\n/**\n * Create a complete Employee schema with all HRM fields.\n *\n * @param additionalFields - Extra fields to add to the schema\n * @param options - Schema options (organizationRef, userRef)\n * @returns Mongoose Schema for Employee\n *\n * @example\n * ```typescript\n * // Default (references 'Organization')\n * const employeeSchema = createEmployeeSchema();\n *\n * // Multi-branch setup\n * const employeeSchema = createEmployeeSchema({}, {\n * organizationRef: 'Branch',\n * });\n *\n * // With additional fields\n * const employeeSchema = createEmployeeSchema({\n * customField: { type: String },\n * }, {\n * organizationRef: 'Company',\n * });\n * ```\n */\nexport function createEmployeeSchema(\n additionalFields: SchemaDefinition = {},\n options: PayrollSchemaOptions = {}\n): Schema {\n const schema = new Schema(\n {\n ...createEmploymentFields(options),\n ...additionalFields,\n },\n { timestamps: true }\n );\n\n // Note: Pre-save hooks are not needed for partial indexes since:\n // - Guest employees use insertOne() which bypasses Mongoose hooks\n // - User-linked employees use Model.create() which properly sets userId\n // - Partial indexes with partialFilterExpression handle inclusion/exclusion\n\n applyEmployeeIndexes(schema);\n return schema;\n}\n\n/**\n * Create a complete PayrollRecord schema.\n *\n * @param additionalFields - Extra fields to add to the schema\n * @param options - Schema options (organizationRef, userRef)\n * @returns Mongoose Schema for PayrollRecord\n *\n * @example\n * ```typescript\n * // Multi-branch setup\n * const payrollRecordSchema = createPayrollRecordSchema({}, {\n * organizationRef: 'Branch',\n * });\n * ```\n */\nexport function createPayrollRecordSchema(\n additionalFields: SchemaDefinition = {},\n options: PayrollSchemaOptions = {}\n): Schema {\n const schema = new Schema(\n {\n ...createPayrollRecordFields(options),\n ...additionalFields,\n },\n { timestamps: true }\n );\n\n applyPayrollRecordIndexes(schema);\n\n // Virtual: totalAmount\n schema.virtual('totalAmount').get(function () {\n return this.breakdown?.netSalary || 0;\n });\n\n // Virtual: isPaid\n schema.virtual('isPaid').get(function () {\n return this.status === 'paid';\n });\n\n // Virtual: periodLabel\n schema.virtual('periodLabel').get(function () {\n const months = [\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',\n ];\n return `${months[this.period.month - 1]} ${this.period.year}`;\n });\n\n // Method: markAsPaid\n schema.methods.markAsPaid = function (\n transactionId: Types.ObjectId,\n paidAt = new Date()\n ) {\n this.status = 'paid';\n this.transactionId = transactionId;\n this.paidAt = paidAt;\n };\n\n // Method: markAsExported\n schema.methods.markAsExported = function () {\n this.exported = true;\n this.exportedAt = new Date();\n };\n\n // Method: canBeDeleted\n schema.methods.canBeDeleted = function (): boolean {\n return this.exported && this.status === 'paid';\n };\n\n return schema;\n}\n\n\n// ============================================================================\n// Leave Schemas\n// ============================================================================\n\nexport {\n leaveBalanceSchema,\n leaveBalanceFields,\n leaveRequestSchema,\n leaveRequestIndexes,\n leaveRequestTTLIndex,\n applyLeaveRequestIndexes,\n getLeaveRequestFields,\n getLeaveRequestModel,\n} from './leave.js';\n\n// ============================================================================\n// Tax Withholding Schemas\n// ============================================================================\n\nexport {\n taxWithholdingSchema,\n taxWithholdingIndexes,\n applyTaxWithholdingIndexes,\n getTaxWithholdingFields,\n getTaxWithholdingModel,\n} from './tax-withholding.js';\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default {\n // Sub-schemas\n allowanceSchema,\n deductionSchema,\n compensationSchema,\n workScheduleSchema,\n bankDetailsSchema,\n employmentHistorySchema,\n payrollStatsSchema,\n payrollBreakdownSchema,\n periodSchema,\n // Field creators (configurable references)\n createEmploymentFields,\n createPayrollRecordFields,\n // Indexes\n employeeIndexes,\n payrollRecordIndexes,\n applyEmployeeIndexes,\n applyPayrollRecordIndexes,\n // Schema creators\n createEmployeeSchema,\n createPayrollRecordSchema,\n};\n\n"]}