@classytic/payroll 1.0.2 → 2.0.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.

Potentially problematic release.


This version of @classytic/payroll might be problematic. Click here for more details.

Files changed (68) hide show
  1. package/README.md +168 -489
  2. package/dist/core/index.d.ts +480 -0
  3. package/dist/core/index.js +971 -0
  4. package/dist/core/index.js.map +1 -0
  5. package/dist/index-CTjHlCzz.d.ts +721 -0
  6. package/dist/index.d.ts +967 -0
  7. package/dist/index.js +4352 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/payroll.d.ts +233 -0
  10. package/dist/payroll.js +2103 -0
  11. package/dist/payroll.js.map +1 -0
  12. package/dist/plugin-D9mOr3_d.d.ts +333 -0
  13. package/dist/schemas/index.d.ts +2869 -0
  14. package/dist/schemas/index.js +440 -0
  15. package/dist/schemas/index.js.map +1 -0
  16. package/dist/services/index.d.ts +3 -0
  17. package/dist/services/index.js +1696 -0
  18. package/dist/services/index.js.map +1 -0
  19. package/dist/types-BSYyX2KJ.d.ts +671 -0
  20. package/dist/utils/index.d.ts +873 -0
  21. package/dist/utils/index.js +1046 -0
  22. package/dist/utils/index.js.map +1 -0
  23. package/package.json +54 -37
  24. package/dist/types/config.d.ts +0 -162
  25. package/dist/types/core/compensation.manager.d.ts +0 -54
  26. package/dist/types/core/employment.manager.d.ts +0 -49
  27. package/dist/types/core/payroll.manager.d.ts +0 -60
  28. package/dist/types/enums.d.ts +0 -117
  29. package/dist/types/factories/compensation.factory.d.ts +0 -196
  30. package/dist/types/factories/employee.factory.d.ts +0 -149
  31. package/dist/types/factories/payroll.factory.d.ts +0 -319
  32. package/dist/types/hrm.orchestrator.d.ts +0 -47
  33. package/dist/types/index.d.ts +0 -20
  34. package/dist/types/init.d.ts +0 -30
  35. package/dist/types/models/payroll-record.model.d.ts +0 -3
  36. package/dist/types/plugins/employee.plugin.d.ts +0 -2
  37. package/dist/types/schemas/employment.schema.d.ts +0 -959
  38. package/dist/types/services/compensation.service.d.ts +0 -94
  39. package/dist/types/services/employee.service.d.ts +0 -28
  40. package/dist/types/services/payroll.service.d.ts +0 -30
  41. package/dist/types/utils/calculation.utils.d.ts +0 -26
  42. package/dist/types/utils/date.utils.d.ts +0 -35
  43. package/dist/types/utils/logger.d.ts +0 -12
  44. package/dist/types/utils/query-builders.d.ts +0 -83
  45. package/dist/types/utils/validation.utils.d.ts +0 -33
  46. package/payroll.d.ts +0 -241
  47. package/src/config.js +0 -177
  48. package/src/core/compensation.manager.js +0 -242
  49. package/src/core/employment.manager.js +0 -224
  50. package/src/core/payroll.manager.js +0 -499
  51. package/src/enums.js +0 -141
  52. package/src/factories/compensation.factory.js +0 -198
  53. package/src/factories/employee.factory.js +0 -173
  54. package/src/factories/payroll.factory.js +0 -413
  55. package/src/hrm.orchestrator.js +0 -139
  56. package/src/index.js +0 -172
  57. package/src/init.js +0 -62
  58. package/src/models/payroll-record.model.js +0 -126
  59. package/src/plugins/employee.plugin.js +0 -164
  60. package/src/schemas/employment.schema.js +0 -126
  61. package/src/services/compensation.service.js +0 -231
  62. package/src/services/employee.service.js +0 -162
  63. package/src/services/payroll.service.js +0 -213
  64. package/src/utils/calculation.utils.js +0 -91
  65. package/src/utils/date.utils.js +0 -120
  66. package/src/utils/logger.js +0 -36
  67. package/src/utils/query-builders.js +0 -185
  68. package/src/utils/validation.utils.js +0 -122
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/date.ts","../../src/config.ts","../../src/factories/employee.factory.ts","../../src/utils/query-builders.ts","../../src/utils/validation.ts","../../src/utils/logger.ts","../../src/services/employee.service.ts","../../src/utils/calculation.ts","../../src/factories/payroll.factory.ts","../../src/services/payroll.service.ts","../../src/factories/compensation.factory.ts","../../src/services/compensation.service.ts"],"names":["employee","payroll"],"mappings":";;;AAyBO,SAAS,SAAA,CAAU,MAAY,MAAA,EAAsB;AAC1D,EAAA,MAAM,MAAA,GAAS,IAAI,IAAA,CAAK,IAAI,CAAA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A,EAAY,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,WAAW,KAAK,CAAA;AAAA,MAC9C;AAAA,KACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,YAAA,CACZ,UAAA,EACA,OAAA,GAAuC,EAAC,EACb;AAC3B,IAAA,IAAI,QAAQ,IAAA,CAAK,aAAA,CAAc,QAAA,CAAS,UAAA,CAAW,UAAU,CAAC,CAAA;AAE9D,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,KAAA,GAAQ,KAAA,CAAM,OAAA,CAAQ,OAAA,CAAQ,OAAO,CAAA;AAAA,IACvC;AAEA,IAAA,MAAMA,SAAAA,GAAW,MAAM,KAAA,CAAM,IAAA,EAAK;AAClC,IAAA,IAAI,CAACA,SAAAA,EAAU;AACb,MAAA,MAAM,IAAI,MAAM,oBAAoB,CAAA;AAAA,IACtC;AACA,IAAA,OAAOA,SAAAA;AAAA,EACT;AACF;AASO,SAAS,0BACd,aAAA,EACqB;AACrB,EAAA,OAAO,IAAI,oBAAoB,aAAa,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\r\n * @classytic/payroll - Date Utilities\r\n *\r\n * Pure, composable, testable date operations\r\n * No side effects, no mutations\r\n */\r\n\r\nimport type { PayPeriodInfo, PaymentFrequency } from '../types.js';\r\n\r\n// ============================================================================\r\n// Date Arithmetic\r\n// ============================================================================\r\n\r\n/**\r\n * Add days to a date\r\n */\r\nexport function addDays(date: Date, days: number): Date {\r\n const result = new Date(date);\r\n result.setDate(result.getDate() + days);\r\n return result;\r\n}\r\n\r\n/**\r\n * Add months to a date\r\n */\r\nexport function addMonths(date: Date, months: number): Date {\r\n const result = new Date(date);\r\n result.setMonth(result.getMonth() + months);\r\n return result;\r\n}\r\n\r\n/**\r\n * Add years to a date\r\n */\r\nexport function addYears(date: Date, years: number): Date {\r\n const result = new Date(date);\r\n result.setFullYear(result.getFullYear() + years);\r\n return result;\r\n}\r\n\r\n/**\r\n * Subtract days from a date\r\n */\r\nexport function subDays(date: Date, days: number): Date {\r\n return addDays(date, -days);\r\n}\r\n\r\n/**\r\n * Subtract months from a date\r\n */\r\nexport function subMonths(date: Date, months: number): Date {\r\n return addMonths(date, -months);\r\n}\r\n\r\n// ============================================================================\r\n// Date Boundaries\r\n// ============================================================================\r\n\r\n/**\r\n * Get the start of a month\r\n */\r\nexport function startOfMonth(date: Date): Date {\r\n const result = new Date(date);\r\n result.setDate(1);\r\n result.setHours(0, 0, 0, 0);\r\n return result;\r\n}\r\n\r\n/**\r\n * Get the end of a month\r\n */\r\nexport function endOfMonth(date: Date): Date {\r\n const result = new Date(date);\r\n result.setMonth(result.getMonth() + 1, 0);\r\n result.setHours(23, 59, 59, 999);\r\n return result;\r\n}\r\n\r\n/**\r\n * Get the start of a year\r\n */\r\nexport function startOfYear(date: Date): Date {\r\n const result = new Date(date);\r\n result.setMonth(0, 1);\r\n result.setHours(0, 0, 0, 0);\r\n return result;\r\n}\r\n\r\n/**\r\n * Get the end of a year\r\n */\r\nexport function endOfYear(date: Date): Date {\r\n const result = new Date(date);\r\n result.setMonth(11, 31);\r\n result.setHours(23, 59, 59, 999);\r\n return result;\r\n}\r\n\r\n/**\r\n * Get the start of a day\r\n */\r\nexport function startOfDay(date: Date): Date {\r\n const result = new Date(date);\r\n result.setHours(0, 0, 0, 0);\r\n return result;\r\n}\r\n\r\n/**\r\n * Get the end of a day\r\n */\r\nexport function endOfDay(date: Date): Date {\r\n const result = new Date(date);\r\n result.setHours(23, 59, 59, 999);\r\n return result;\r\n}\r\n\r\n// ============================================================================\r\n// Date Differences\r\n// ============================================================================\r\n\r\n/**\r\n * Calculate difference in days between two dates\r\n */\r\nexport function diffInDays(start: Date, end: Date): number {\r\n return Math.ceil(\r\n (new Date(end).getTime() - new Date(start).getTime()) / (1000 * 60 * 60 * 24)\r\n );\r\n}\r\n\r\n/**\r\n * Calculate difference in months between two dates\r\n */\r\nexport function diffInMonths(start: Date, end: Date): number {\r\n const startDate = new Date(start);\r\n const endDate = new Date(end);\r\n return (\r\n (endDate.getFullYear() - startDate.getFullYear()) * 12 +\r\n (endDate.getMonth() - startDate.getMonth())\r\n );\r\n}\r\n\r\n/**\r\n * Calculate difference in years between two dates\r\n */\r\nexport function diffInYears(start: Date, end: Date): number {\r\n return Math.floor(diffInMonths(start, end) / 12);\r\n}\r\n\r\n// Aliases for backwards compatibility\r\nexport const daysBetween = diffInDays;\r\nexport const monthsBetween = diffInMonths;\r\n\r\n// ============================================================================\r\n// Day Type Checks\r\n// ============================================================================\r\n\r\n/**\r\n * Check if date is a weekday (Mon-Fri)\r\n */\r\nexport function isWeekday(date: Date): boolean {\r\n const day = new Date(date).getDay();\r\n return day >= 1 && day <= 5;\r\n}\r\n\r\n/**\r\n * Check if date is a weekend (Sat-Sun)\r\n */\r\nexport function isWeekend(date: Date): boolean {\r\n const day = new Date(date).getDay();\r\n return day === 0 || day === 6;\r\n}\r\n\r\n/**\r\n * Get day of week (0=Sunday, 6=Saturday)\r\n */\r\nexport function getDayOfWeek(date: Date): number {\r\n return new Date(date).getDay();\r\n}\r\n\r\n/**\r\n * Get day name\r\n */\r\nexport function getDayName(date: Date): string {\r\n const days = [\r\n 'Sunday',\r\n 'Monday',\r\n 'Tuesday',\r\n 'Wednesday',\r\n 'Thursday',\r\n 'Friday',\r\n 'Saturday',\r\n ];\r\n return days[getDayOfWeek(date)];\r\n}\r\n\r\n// ============================================================================\r\n// Pay Period Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Get pay period for a given month and year\r\n */\r\nexport function getPayPeriod(month: number, year: number): PayPeriodInfo {\r\n const startDate = new Date(year, month - 1, 1);\r\n return {\r\n month,\r\n year,\r\n startDate: startOfMonth(startDate),\r\n endDate: endOfMonth(startDate),\r\n };\r\n}\r\n\r\n/**\r\n * Get current pay period\r\n */\r\nexport function getCurrentPeriod(date = new Date()): { year: number; month: number } {\r\n const d = new Date(date);\r\n return {\r\n year: d.getFullYear(),\r\n month: d.getMonth() + 1,\r\n };\r\n}\r\n\r\n/**\r\n * Get working days in a month\r\n */\r\nexport function getWorkingDaysInMonth(year: number, month: number): number {\r\n const start = new Date(year, month - 1, 1);\r\n const end = endOfMonth(start);\r\n let count = 0;\r\n \r\n const current = new Date(start);\r\n while (current <= end) {\r\n if (isWeekday(current)) {\r\n count++;\r\n }\r\n current.setDate(current.getDate() + 1);\r\n }\r\n \r\n return count;\r\n}\r\n\r\n/**\r\n * Get total days in a month\r\n */\r\nexport function getDaysInMonth(year: number, month: number): number {\r\n return new Date(year, month, 0).getDate();\r\n}\r\n\r\n// ============================================================================\r\n// Employment Date Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Calculate probation end date\r\n */\r\nexport function calculateProbationEnd(\r\n hireDate: Date,\r\n probationMonths: number\r\n): Date | null {\r\n if (!probationMonths || probationMonths <= 0) return null;\r\n return addMonths(hireDate, probationMonths);\r\n}\r\n\r\n/**\r\n * Check if employee is on probation\r\n */\r\nexport function isOnProbation(\r\n probationEndDate: Date | null | undefined,\r\n now = new Date()\r\n): boolean {\r\n if (!probationEndDate) return false;\r\n return now < new Date(probationEndDate);\r\n}\r\n\r\n/**\r\n * Calculate years of service\r\n */\r\nexport function calculateYearsOfService(\r\n hireDate: Date,\r\n terminationDate?: Date | null\r\n): number {\r\n const end = terminationDate || new Date();\r\n const days = diffInDays(hireDate, end);\r\n return Math.max(0, Math.floor((days / 365.25) * 10) / 10);\r\n}\r\n\r\n// ============================================================================\r\n// Range Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Check if a date is within a range\r\n */\r\nexport function isDateInRange(date: Date, start: Date, end: Date): boolean {\r\n const checkDate = new Date(date);\r\n return checkDate >= new Date(start) && checkDate <= new Date(end);\r\n}\r\n\r\n/**\r\n * Get date range for a pay period\r\n */\r\nexport function getPayPeriodDateRange(\r\n month: number,\r\n year: number\r\n): { start: Date; end: Date } {\r\n const period = getPayPeriod(month, year);\r\n return { start: period.startDate, end: period.endDate };\r\n}\r\n\r\n// ============================================================================\r\n// Formatting Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Format date for database storage\r\n */\r\nexport function formatDateForDB(date: Date): string {\r\n if (!date) return '';\r\n return new Date(date).toISOString();\r\n}\r\n\r\n/**\r\n * Parse date from database\r\n */\r\nexport function parseDBDate(dateString: string): Date | null {\r\n if (!dateString) return null;\r\n return new Date(dateString);\r\n}\r\n\r\n/**\r\n * Format period as string (e.g., \"01/2025\")\r\n */\r\nexport function formatPeriod({ month, year }: { month: number; year: number }): string {\r\n return `${String(month).padStart(2, '0')}/${year}`;\r\n}\r\n\r\n/**\r\n * Parse period string back to object\r\n */\r\nexport function parsePeriod(periodString: string): { month: number; year: number } {\r\n const [month, year] = periodString.split('/').map(Number);\r\n return { month, year };\r\n}\r\n\r\n/**\r\n * Format month name\r\n */\r\nexport function getMonthName(month: number): string {\r\n const months = [\r\n 'January', 'February', 'March', 'April', 'May', 'June',\r\n 'July', 'August', 'September', 'October', 'November', 'December',\r\n ];\r\n return months[month - 1] || '';\r\n}\r\n\r\n/**\r\n * Format short month name\r\n */\r\nexport function getShortMonthName(month: number): string {\r\n const months = [\r\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\r\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',\r\n ];\r\n return months[month - 1] || '';\r\n}\r\n\r\n// ============================================================================\r\n// Default Export\r\n// ============================================================================\r\n\r\nexport default {\r\n addDays,\r\n addMonths,\r\n addYears,\r\n subDays,\r\n subMonths,\r\n startOfMonth,\r\n endOfMonth,\r\n startOfYear,\r\n endOfYear,\r\n startOfDay,\r\n endOfDay,\r\n diffInDays,\r\n diffInMonths,\r\n diffInYears,\r\n daysBetween,\r\n monthsBetween,\r\n isWeekday,\r\n isWeekend,\r\n getDayOfWeek,\r\n getDayName,\r\n getPayPeriod,\r\n getCurrentPeriod,\r\n getWorkingDaysInMonth,\r\n getDaysInMonth,\r\n calculateProbationEnd,\r\n isOnProbation,\r\n calculateYearsOfService,\r\n isDateInRange,\r\n getPayPeriodDateRange,\r\n formatDateForDB,\r\n parseDBDate,\r\n formatPeriod,\r\n parsePeriod,\r\n getMonthName,\r\n getShortMonthName,\r\n};\r\n\r\n","/**\r\n * @classytic/payroll - Configuration\r\n *\r\n * Centralized configuration with type safety\r\n * Configurable defaults for different use cases\r\n */\r\n\r\nimport type {\r\n HRMConfig,\r\n TaxBracket,\r\n SalaryBandRange,\r\n RoleMappingConfig,\r\n OrgRole,\r\n SalaryBand,\r\n Department,\r\n EmploymentType,\r\n PaymentFrequency,\r\n DeepPartial,\r\n} from './types.js';\r\n\r\n// ============================================================================\r\n// Default Configuration\r\n// ============================================================================\r\n\r\nexport const HRM_CONFIG: HRMConfig = {\r\n dataRetention: {\r\n payrollRecordsTTL: 63072000, // 2 years in seconds\r\n exportWarningDays: 30,\r\n archiveBeforeDeletion: true,\r\n },\r\n\r\n payroll: {\r\n defaultCurrency: 'BDT',\r\n allowProRating: true,\r\n attendanceIntegration: true,\r\n autoDeductions: true,\r\n overtimeEnabled: false,\r\n overtimeMultiplier: 1.5,\r\n },\r\n\r\n salary: {\r\n minimumWage: 0,\r\n maximumAllowances: 10,\r\n maximumDeductions: 10,\r\n defaultFrequency: 'monthly',\r\n },\r\n\r\n employment: {\r\n defaultProbationMonths: 3,\r\n maxProbationMonths: 6,\r\n allowReHiring: true,\r\n trackEmploymentHistory: true,\r\n },\r\n\r\n validation: {\r\n requireBankDetails: false,\r\n requireEmployeeId: true,\r\n uniqueEmployeeIdPerOrg: true,\r\n allowMultiTenantEmployees: true,\r\n },\r\n};\r\n\r\n// ============================================================================\r\n// Salary Bands Configuration\r\n// ============================================================================\r\n\r\nexport const SALARY_BANDS: Record<Exclude<SalaryBand, 'custom'>, SalaryBandRange> = {\r\n intern: { min: 10000, max: 20000 },\r\n junior: { min: 20000, max: 40000 },\r\n mid: { min: 40000, max: 70000 },\r\n senior: { min: 70000, max: 120000 },\r\n lead: { min: 100000, max: 200000 },\r\n executive: { min: 150000, max: 500000 },\r\n};\r\n\r\n// ============================================================================\r\n// Tax Brackets Configuration\r\n// ============================================================================\r\n\r\nexport const TAX_BRACKETS: Record<string, TaxBracket[]> = {\r\n BDT: [\r\n { min: 0, max: 300000, rate: 0 },\r\n { min: 300000, max: 400000, rate: 0.05 },\r\n { min: 400000, max: 500000, rate: 0.10 },\r\n { min: 500000, max: 600000, rate: 0.15 },\r\n { min: 600000, max: 3000000, rate: 0.20 },\r\n { min: 3000000, max: Infinity, rate: 0.25 },\r\n ],\r\n USD: [\r\n { min: 0, max: 10000, rate: 0.10 },\r\n { min: 10000, max: 40000, rate: 0.12 },\r\n { min: 40000, max: 85000, rate: 0.22 },\r\n { min: 85000, max: 165000, rate: 0.24 },\r\n { min: 165000, max: 215000, rate: 0.32 },\r\n { min: 215000, max: 540000, rate: 0.35 },\r\n { min: 540000, max: Infinity, rate: 0.37 },\r\n ],\r\n};\r\n\r\n// ============================================================================\r\n// Organization Roles Configuration\r\n// ============================================================================\r\n\r\nexport interface OrgRoleDefinition {\r\n key: OrgRole;\r\n label: string;\r\n description: string;\r\n}\r\n\r\nexport const ORG_ROLES: Record<Uppercase<OrgRole>, OrgRoleDefinition> = {\r\n OWNER: {\r\n key: 'owner',\r\n label: 'Owner',\r\n description: 'Full organization access (set by Organization model)',\r\n },\r\n MANAGER: {\r\n key: 'manager',\r\n label: 'Manager',\r\n description: 'Management and administrative features',\r\n },\r\n TRAINER: {\r\n key: 'trainer',\r\n label: 'Trainer',\r\n description: 'Training and coaching features',\r\n },\r\n STAFF: {\r\n key: 'staff',\r\n label: 'Staff',\r\n description: 'General staff access to basic features',\r\n },\r\n INTERN: {\r\n key: 'intern',\r\n label: 'Intern',\r\n description: 'Limited access for interns',\r\n },\r\n CONSULTANT: {\r\n key: 'consultant',\r\n label: 'Consultant',\r\n description: 'Project-based consultant access',\r\n },\r\n};\r\n\r\nexport const ORG_ROLE_KEYS = Object.values(ORG_ROLES).map((role) => role.key);\r\n\r\n// ============================================================================\r\n// Role Mapping Configuration\r\n// ============================================================================\r\n\r\nexport const ROLE_MAPPING: RoleMappingConfig = {\r\n byDepartment: {\r\n management: 'manager',\r\n training: 'trainer',\r\n sales: 'staff',\r\n operations: 'staff',\r\n finance: 'staff',\r\n hr: 'staff',\r\n marketing: 'staff',\r\n it: 'staff',\r\n support: 'staff',\r\n maintenance: 'staff',\r\n },\r\n\r\n byEmploymentType: {\r\n full_time: 'staff',\r\n part_time: 'staff',\r\n contract: 'consultant',\r\n intern: 'intern',\r\n consultant: 'consultant',\r\n },\r\n\r\n default: 'staff',\r\n};\r\n\r\n// ============================================================================\r\n// Configuration Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Calculate tax based on annual income\r\n */\r\nexport function calculateTax(annualIncome: number, currency = 'BDT'): number {\r\n const brackets = TAX_BRACKETS[currency];\r\n if (!brackets) return 0;\r\n\r\n let tax = 0;\r\n for (const bracket of brackets) {\r\n if (annualIncome > bracket.min) {\r\n const taxableAmount = Math.min(annualIncome, bracket.max) - bracket.min;\r\n tax += taxableAmount * bracket.rate;\r\n }\r\n }\r\n return Math.round(tax);\r\n}\r\n\r\n/**\r\n * Get salary band for a given amount\r\n */\r\nexport function getSalaryBand(amount: number): SalaryBand {\r\n for (const [band, range] of Object.entries(SALARY_BANDS)) {\r\n if (amount >= range.min && amount <= range.max) {\r\n return band as SalaryBand;\r\n }\r\n }\r\n return 'custom';\r\n}\r\n\r\n/**\r\n * Determine the appropriate organization role for an employee\r\n */\r\nexport function determineOrgRole(employmentData: {\r\n department?: Department | string;\r\n type?: EmploymentType | string;\r\n position?: string;\r\n}): OrgRole {\r\n const { department, type: employmentType } = employmentData;\r\n\r\n // Priority 1: Department-based mapping\r\n if (department && department in ROLE_MAPPING.byDepartment) {\r\n return ROLE_MAPPING.byDepartment[department as keyof typeof ROLE_MAPPING.byDepartment];\r\n }\r\n\r\n // Priority 2: Employment type mapping\r\n if (employmentType && employmentType in ROLE_MAPPING.byEmploymentType) {\r\n return ROLE_MAPPING.byEmploymentType[employmentType as keyof typeof ROLE_MAPPING.byEmploymentType];\r\n }\r\n\r\n // Priority 3: Default role\r\n return ROLE_MAPPING.default;\r\n}\r\n\r\n/**\r\n * Get pay periods per year based on frequency\r\n */\r\nexport function getPayPeriodsPerYear(frequency: PaymentFrequency): number {\r\n const periodsMap: Record<PaymentFrequency, number> = {\r\n monthly: 12,\r\n bi_weekly: 26,\r\n weekly: 52,\r\n daily: 365,\r\n hourly: 2080, // Assuming 40 hours/week * 52 weeks\r\n };\r\n return periodsMap[frequency];\r\n}\r\n\r\n/**\r\n * Calculate monthly equivalent from any frequency\r\n */\r\nexport function toMonthlyAmount(amount: number, frequency: PaymentFrequency): number {\r\n const periodsPerYear = getPayPeriodsPerYear(frequency);\r\n return Math.round((amount * periodsPerYear) / 12);\r\n}\r\n\r\n/**\r\n * Calculate annual equivalent from any frequency\r\n */\r\nexport function toAnnualAmount(amount: number, frequency: PaymentFrequency): number {\r\n const periodsPerYear = getPayPeriodsPerYear(frequency);\r\n return Math.round(amount * periodsPerYear);\r\n}\r\n\r\n/**\r\n * Merge configuration with defaults\r\n */\r\nexport function mergeConfig(\r\n customConfig: Partial<HRMConfig> | DeepPartial<HRMConfig> | undefined\r\n): HRMConfig {\r\n if (!customConfig) return HRM_CONFIG;\r\n\r\n return {\r\n dataRetention: { ...HRM_CONFIG.dataRetention, ...customConfig.dataRetention },\r\n payroll: { ...HRM_CONFIG.payroll, ...customConfig.payroll },\r\n salary: { ...HRM_CONFIG.salary, ...customConfig.salary },\r\n employment: { ...HRM_CONFIG.employment, ...customConfig.employment },\r\n validation: { ...HRM_CONFIG.validation, ...customConfig.validation },\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Default Export\r\n// ============================================================================\r\n\r\nexport default {\r\n HRM_CONFIG,\r\n SALARY_BANDS,\r\n TAX_BRACKETS,\r\n ORG_ROLES,\r\n ORG_ROLE_KEYS,\r\n ROLE_MAPPING,\r\n calculateTax,\r\n getSalaryBand,\r\n determineOrgRole,\r\n getPayPeriodsPerYear,\r\n toMonthlyAmount,\r\n toAnnualAmount,\r\n mergeConfig,\r\n};\r\n\r\n","/**\r\n * @classytic/payroll - Employee Factory\r\n *\r\n * Clean object creation for employee documents\r\n * Builder pattern for fluent API\r\n */\r\n\r\nimport type {\r\n ObjectIdLike,\r\n EmploymentType,\r\n Department,\r\n Compensation,\r\n BankDetails,\r\n WorkSchedule,\r\n Allowance,\r\n Deduction,\r\n PaymentFrequency,\r\n TerminationReason,\r\n} from '../types.js';\r\nimport { calculateProbationEnd } from '../utils/date.js';\r\nimport { HRM_CONFIG } from '../config.js';\r\n\r\n// ============================================================================\r\n// Employee Factory Types\r\n// ============================================================================\r\n\r\nexport interface CreateEmployeeParams {\r\n userId: ObjectIdLike;\r\n organizationId: ObjectIdLike;\r\n employment: {\r\n employeeId?: string;\r\n type?: EmploymentType;\r\n department?: Department | string;\r\n position: string;\r\n hireDate?: Date;\r\n probationMonths?: number;\r\n workSchedule?: WorkSchedule;\r\n };\r\n compensation: {\r\n baseAmount: number;\r\n frequency?: PaymentFrequency;\r\n currency?: string;\r\n allowances?: Array<Partial<Allowance>>;\r\n deductions?: Array<Partial<Deduction>>;\r\n };\r\n bankDetails?: BankDetails;\r\n}\r\n\r\nexport interface EmployeeData {\r\n userId: ObjectIdLike;\r\n organizationId: ObjectIdLike;\r\n employeeId: string;\r\n employmentType: EmploymentType;\r\n status: 'active';\r\n department?: Department;\r\n position: string;\r\n hireDate: Date;\r\n probationEndDate: Date | null;\r\n compensation: Compensation;\r\n workSchedule: WorkSchedule;\r\n bankDetails: BankDetails;\r\n payrollStats: {\r\n totalPaid: number;\r\n paymentsThisYear: number;\r\n averageMonthly: number;\r\n };\r\n}\r\n\r\nexport interface TerminationData {\r\n terminatedAt: Date;\r\n terminationReason: TerminationReason;\r\n terminationNotes?: string;\r\n terminatedBy: {\r\n userId?: ObjectIdLike;\r\n name?: string;\r\n role?: string;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Employee Factory\r\n// ============================================================================\r\n\r\nexport class EmployeeFactory {\r\n /**\r\n * Create employee data object\r\n */\r\n static create(params: CreateEmployeeParams): EmployeeData {\r\n const { userId, organizationId, employment, compensation, bankDetails } = params;\r\n const hireDate = employment.hireDate || new Date();\r\n\r\n return {\r\n userId,\r\n organizationId,\r\n employeeId: employment.employeeId || `EMP-${Date.now()}-${Math.random().toString(36).substr(2, 6).toUpperCase()}`,\r\n employmentType: employment.type || 'full_time',\r\n status: 'active',\r\n department: employment.department as Department | undefined,\r\n position: employment.position,\r\n hireDate,\r\n probationEndDate: calculateProbationEnd(\r\n hireDate,\r\n employment.probationMonths ?? HRM_CONFIG.employment.defaultProbationMonths\r\n ),\r\n compensation: this.createCompensation(compensation),\r\n workSchedule: employment.workSchedule || this.defaultWorkSchedule(),\r\n bankDetails: bankDetails || {},\r\n payrollStats: {\r\n totalPaid: 0,\r\n paymentsThisYear: 0,\r\n averageMonthly: 0,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Create compensation object\r\n */\r\n static createCompensation(params: {\r\n baseAmount: number;\r\n frequency?: PaymentFrequency;\r\n currency?: string;\r\n allowances?: Array<Partial<Allowance>>;\r\n deductions?: Array<Partial<Deduction>>;\r\n }): Compensation {\r\n return {\r\n baseAmount: params.baseAmount,\r\n frequency: params.frequency || 'monthly',\r\n currency: params.currency || HRM_CONFIG.payroll.defaultCurrency,\r\n allowances: (params.allowances || []).map((a) => ({\r\n type: a.type || 'other',\r\n name: a.name || a.type || 'other',\r\n amount: a.amount || 0,\r\n taxable: a.taxable,\r\n recurring: a.recurring,\r\n effectiveFrom: a.effectiveFrom,\r\n effectiveTo: a.effectiveTo,\r\n })),\r\n deductions: (params.deductions || []).map((d) => ({\r\n type: d.type || 'other',\r\n name: d.name || d.type || 'other',\r\n amount: d.amount || 0,\r\n auto: d.auto,\r\n recurring: d.recurring,\r\n description: d.description,\r\n effectiveFrom: d.effectiveFrom,\r\n effectiveTo: d.effectiveTo,\r\n })),\r\n grossSalary: 0,\r\n netSalary: 0,\r\n effectiveFrom: new Date(),\r\n lastModified: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Create allowance object\r\n */\r\n static createAllowance(params: {\r\n type: Allowance['type'];\r\n amount: number;\r\n name?: string;\r\n isPercentage?: boolean;\r\n taxable?: boolean;\r\n recurring?: boolean;\r\n }): Allowance {\r\n return {\r\n type: params.type,\r\n name: params.name || params.type,\r\n amount: params.amount,\r\n isPercentage: params.isPercentage ?? false,\r\n taxable: params.taxable ?? true,\r\n recurring: params.recurring ?? true,\r\n effectiveFrom: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Create deduction object\r\n */\r\n static createDeduction(params: {\r\n type: Deduction['type'];\r\n amount: number;\r\n name?: string;\r\n isPercentage?: boolean;\r\n auto?: boolean;\r\n recurring?: boolean;\r\n description?: string;\r\n }): Deduction {\r\n return {\r\n type: params.type,\r\n name: params.name || params.type,\r\n amount: params.amount,\r\n isPercentage: params.isPercentage ?? false,\r\n auto: params.auto ?? false,\r\n recurring: params.recurring ?? true,\r\n description: params.description,\r\n effectiveFrom: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Default work schedule\r\n */\r\n static defaultWorkSchedule(): WorkSchedule {\r\n return {\r\n hoursPerWeek: 40,\r\n hoursPerDay: 8,\r\n workingDays: [1, 2, 3, 4, 5], // Mon-Fri\r\n shiftStart: '09:00',\r\n shiftEnd: '17:00',\r\n };\r\n }\r\n\r\n /**\r\n * Create termination data\r\n */\r\n static createTermination(params: {\r\n reason: TerminationReason;\r\n date?: Date;\r\n notes?: string;\r\n context?: {\r\n userId?: ObjectIdLike;\r\n userName?: string;\r\n userRole?: string;\r\n };\r\n }): TerminationData {\r\n return {\r\n terminatedAt: params.date || new Date(),\r\n terminationReason: params.reason,\r\n terminationNotes: params.notes,\r\n terminatedBy: {\r\n userId: params.context?.userId,\r\n name: params.context?.userName,\r\n role: params.context?.userRole,\r\n },\r\n };\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Employee Builder\r\n// ============================================================================\r\n\r\nexport class EmployeeBuilder {\r\n private data: Partial<CreateEmployeeParams> = {\r\n employment: {} as CreateEmployeeParams['employment'],\r\n compensation: {} as CreateEmployeeParams['compensation'],\r\n bankDetails: {},\r\n };\r\n\r\n /**\r\n * Set user ID\r\n */\r\n forUser(userId: ObjectIdLike): this {\r\n this.data.userId = userId;\r\n return this;\r\n }\r\n\r\n /**\r\n * Set organization ID\r\n */\r\n inOrganization(organizationId: ObjectIdLike): this {\r\n this.data.organizationId = organizationId;\r\n return this;\r\n }\r\n\r\n /**\r\n * Set employee ID\r\n */\r\n withEmployeeId(employeeId: string): this {\r\n this.data.employment = { ...this.data.employment!, employeeId };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set department\r\n */\r\n inDepartment(department: Department): this {\r\n this.data.employment = { ...this.data.employment!, department };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set position\r\n */\r\n asPosition(position: string): this {\r\n this.data.employment = { ...this.data.employment!, position };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set employment type\r\n */\r\n withEmploymentType(type: EmploymentType): this {\r\n this.data.employment = { ...this.data.employment!, type };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set hire date\r\n */\r\n hiredOn(date: Date): this {\r\n this.data.employment = { ...this.data.employment!, hireDate: date };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set probation period\r\n */\r\n withProbation(months: number): this {\r\n this.data.employment = { ...this.data.employment!, probationMonths: months };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set work schedule\r\n */\r\n withSchedule(schedule: WorkSchedule): this {\r\n this.data.employment = { ...this.data.employment!, workSchedule: schedule };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set base salary\r\n */\r\n withBaseSalary(\r\n amount: number,\r\n frequency: PaymentFrequency = 'monthly',\r\n currency = 'BDT'\r\n ): this {\r\n this.data.compensation = {\r\n ...this.data.compensation!,\r\n baseAmount: amount,\r\n frequency,\r\n currency,\r\n };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add allowance\r\n */\r\n addAllowance(\r\n type: Allowance['type'],\r\n amount: number,\r\n options: { taxable?: boolean; recurring?: boolean } = {}\r\n ): this {\r\n const allowances = this.data.compensation?.allowances || [];\r\n this.data.compensation = {\r\n ...this.data.compensation!,\r\n allowances: [\r\n ...allowances,\r\n { type, amount, taxable: options.taxable, recurring: options.recurring },\r\n ],\r\n };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add deduction\r\n */\r\n addDeduction(\r\n type: Deduction['type'],\r\n amount: number,\r\n options: { auto?: boolean; recurring?: boolean; description?: string } = {}\r\n ): this {\r\n const deductions = this.data.compensation?.deductions || [];\r\n this.data.compensation = {\r\n ...this.data.compensation!,\r\n deductions: [\r\n ...deductions,\r\n {\r\n type,\r\n amount,\r\n auto: options.auto,\r\n recurring: options.recurring,\r\n description: options.description,\r\n },\r\n ],\r\n };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set bank details\r\n */\r\n withBankDetails(bankDetails: BankDetails): this {\r\n this.data.bankDetails = bankDetails;\r\n return this;\r\n }\r\n\r\n /**\r\n * Build employee data\r\n */\r\n build(): EmployeeData {\r\n if (!this.data.userId || !this.data.organizationId) {\r\n throw new Error('userId and organizationId are required');\r\n }\r\n if (!this.data.employment?.employeeId || !this.data.employment?.position) {\r\n throw new Error('employeeId and position are required');\r\n }\r\n if (!this.data.compensation?.baseAmount) {\r\n throw new Error('baseAmount is required');\r\n }\r\n\r\n return EmployeeFactory.create(this.data as CreateEmployeeParams);\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Factory Function\r\n// ============================================================================\r\n\r\n/**\r\n * Create new employee builder\r\n */\r\nexport function createEmployee(): EmployeeBuilder {\r\n return new EmployeeBuilder();\r\n}\r\n\r\n// ============================================================================\r\n// Default Export\r\n// ============================================================================\r\n\r\nexport default {\r\n EmployeeFactory,\r\n EmployeeBuilder,\r\n createEmployee,\r\n};\r\n\r\n","/**\r\n * @classytic/payroll - Query Builders\r\n *\r\n * Fluent API for building MongoDB queries\r\n * Type-safe, chainable, beautiful\r\n */\r\n\r\nimport mongoose, { Types } from 'mongoose';\r\nimport type {\r\n ObjectIdLike,\r\n EmployeeStatus,\r\n PayrollStatus,\r\n Department,\r\n EmploymentType,\r\n} from '../types.js';\r\n\r\n// ============================================================================\r\n// ObjectId Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Convert string or ObjectId to ObjectId\r\n */\r\nexport function toObjectId(id: ObjectIdLike): Types.ObjectId {\r\n if (id instanceof Types.ObjectId) return id;\r\n return new Types.ObjectId(id);\r\n}\r\n\r\n/**\r\n * Safely convert to ObjectId (returns null if invalid)\r\n */\r\nexport function safeToObjectId(id: unknown): Types.ObjectId | null {\r\n if (id instanceof Types.ObjectId) return id;\r\n if (typeof id === 'string' && Types.ObjectId.isValid(id)) {\r\n return new Types.ObjectId(id);\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * Check if value is valid ObjectId\r\n */\r\nexport function isValidObjectId(value: unknown): boolean {\r\n if (value instanceof Types.ObjectId) return true;\r\n if (typeof value === 'string') return Types.ObjectId.isValid(value);\r\n return false;\r\n}\r\n\r\n// ============================================================================\r\n// Base Query Builder\r\n// ============================================================================\r\n\r\nexport class QueryBuilder<T extends Record<string, unknown> = Record<string, unknown>> {\r\n protected query: T;\r\n\r\n constructor(initialQuery: T = {} as T) {\r\n this.query = { ...initialQuery };\r\n }\r\n\r\n /**\r\n * Add where condition\r\n */\r\n where<K extends string>(field: K, value: unknown): this {\r\n (this.query as Record<string, unknown>)[field] = value;\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $in condition\r\n */\r\n whereIn<K extends string>(field: K, values: unknown[]): this {\r\n (this.query as Record<string, unknown>)[field] = { $in: values };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $nin condition\r\n */\r\n whereNotIn<K extends string>(field: K, values: unknown[]): this {\r\n (this.query as Record<string, unknown>)[field] = { $nin: values };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $gte condition\r\n */\r\n whereGte<K extends string>(field: K, value: unknown): this {\r\n const existing = (this.query as Record<string, Record<string, unknown>>)[field] || {};\r\n (this.query as Record<string, unknown>)[field] = { ...existing, $gte: value };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $lte condition\r\n */\r\n whereLte<K extends string>(field: K, value: unknown): this {\r\n const existing = (this.query as Record<string, Record<string, unknown>>)[field] || {};\r\n (this.query as Record<string, unknown>)[field] = { ...existing, $lte: value };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $gt condition\r\n */\r\n whereGt<K extends string>(field: K, value: unknown): this {\r\n const existing = (this.query as Record<string, Record<string, unknown>>)[field] || {};\r\n (this.query as Record<string, unknown>)[field] = { ...existing, $gt: value };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $lt condition\r\n */\r\n whereLt<K extends string>(field: K, value: unknown): this {\r\n const existing = (this.query as Record<string, Record<string, unknown>>)[field] || {};\r\n (this.query as Record<string, unknown>)[field] = { ...existing, $lt: value };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add between condition\r\n */\r\n whereBetween<K extends string>(field: K, start: unknown, end: unknown): this {\r\n (this.query as Record<string, unknown>)[field] = { $gte: start, $lte: end };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $exists condition\r\n */\r\n whereExists<K extends string>(field: K): this {\r\n (this.query as Record<string, unknown>)[field] = { $exists: true };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $exists: false condition\r\n */\r\n whereNotExists<K extends string>(field: K): this {\r\n (this.query as Record<string, unknown>)[field] = { $exists: false };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add $ne condition\r\n */\r\n whereNot<K extends string>(field: K, value: unknown): this {\r\n (this.query as Record<string, unknown>)[field] = { $ne: value };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add regex condition\r\n */\r\n whereRegex<K extends string>(field: K, pattern: string, flags = 'i'): this {\r\n (this.query as Record<string, unknown>)[field] = { $regex: pattern, $options: flags };\r\n return this;\r\n }\r\n\r\n /**\r\n * Merge another query\r\n */\r\n merge(otherQuery: Record<string, unknown>): this {\r\n this.query = { ...this.query, ...otherQuery } as T;\r\n return this;\r\n }\r\n\r\n /**\r\n * Build and return the query\r\n */\r\n build(): T {\r\n return { ...this.query };\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Employee Query Builder\r\n// ============================================================================\r\n\r\nexport class EmployeeQueryBuilder extends QueryBuilder {\r\n /**\r\n * Filter by organization\r\n */\r\n forOrganization(organizationId: ObjectIdLike): this {\r\n return this.where('organizationId', toObjectId(organizationId));\r\n }\r\n\r\n /**\r\n * Filter by user\r\n */\r\n forUser(userId: ObjectIdLike): this {\r\n return this.where('userId', toObjectId(userId));\r\n }\r\n\r\n /**\r\n * Filter by status(es)\r\n */\r\n withStatus(...statuses: EmployeeStatus[]): this {\r\n if (statuses.length === 1) {\r\n return this.where('status', statuses[0]);\r\n }\r\n return this.whereIn('status', statuses);\r\n }\r\n\r\n /**\r\n * Filter active employees\r\n */\r\n active(): this {\r\n return this.withStatus('active');\r\n }\r\n\r\n /**\r\n * Filter employed employees (not terminated)\r\n */\r\n employed(): this {\r\n return this.whereIn('status', ['active', 'on_leave', 'suspended']);\r\n }\r\n\r\n /**\r\n * Filter terminated employees\r\n */\r\n terminated(): this {\r\n return this.withStatus('terminated');\r\n }\r\n\r\n /**\r\n * Filter by department\r\n */\r\n inDepartment(department: Department | string): this {\r\n return this.where('department', department);\r\n }\r\n\r\n /**\r\n * Filter by position\r\n */\r\n inPosition(position: string): this {\r\n return this.where('position', position);\r\n }\r\n\r\n /**\r\n * Filter by employment type\r\n */\r\n withEmploymentType(type: EmploymentType | string): this {\r\n return this.where('employmentType', type);\r\n }\r\n\r\n /**\r\n * Filter by hire date (after)\r\n */\r\n hiredAfter(date: Date): this {\r\n return this.whereGte('hireDate', date);\r\n }\r\n\r\n /**\r\n * Filter by hire date (before)\r\n */\r\n hiredBefore(date: Date): this {\r\n return this.whereLte('hireDate', date);\r\n }\r\n\r\n /**\r\n * Filter by minimum salary\r\n */\r\n withMinSalary(amount: number): this {\r\n return this.whereGte('compensation.netSalary', amount);\r\n }\r\n\r\n /**\r\n * Filter by maximum salary\r\n */\r\n withMaxSalary(amount: number): this {\r\n return this.whereLte('compensation.netSalary', amount);\r\n }\r\n\r\n /**\r\n * Filter by salary range\r\n */\r\n withSalaryRange(min: number, max: number): this {\r\n return this.whereBetween('compensation.netSalary', min, max);\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Payroll Query Builder\r\n// ============================================================================\r\n\r\nexport class PayrollQueryBuilder extends QueryBuilder {\r\n /**\r\n * Filter by organization\r\n */\r\n forOrganization(organizationId: ObjectIdLike): this {\r\n return this.where('organizationId', toObjectId(organizationId));\r\n }\r\n\r\n /**\r\n * Filter by employee\r\n */\r\n forEmployee(employeeId: ObjectIdLike): this {\r\n return this.where('employeeId', toObjectId(employeeId));\r\n }\r\n\r\n /**\r\n * Filter by period\r\n */\r\n forPeriod(month?: number, year?: number): this {\r\n if (month !== undefined) {\r\n this.where('period.month', month);\r\n }\r\n if (year !== undefined) {\r\n this.where('period.year', year);\r\n }\r\n return this;\r\n }\r\n\r\n /**\r\n * Filter by status(es)\r\n */\r\n withStatus(...statuses: PayrollStatus[]): this {\r\n if (statuses.length === 1) {\r\n return this.where('status', statuses[0]);\r\n }\r\n return this.whereIn('status', statuses);\r\n }\r\n\r\n /**\r\n * Filter paid records\r\n */\r\n paid(): this {\r\n return this.withStatus('paid');\r\n }\r\n\r\n /**\r\n * Filter pending records\r\n */\r\n pending(): this {\r\n return this.whereIn('status', ['pending', 'processing']);\r\n }\r\n\r\n /**\r\n * Filter by date range\r\n */\r\n inDateRange(start: Date, end: Date): this {\r\n return this.whereBetween('period.payDate', start, end);\r\n }\r\n\r\n /**\r\n * Filter exported records\r\n */\r\n exported(): this {\r\n return this.where('exported', true);\r\n }\r\n\r\n /**\r\n * Filter not exported records\r\n */\r\n notExported(): this {\r\n return this.where('exported', false);\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Factory Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Create employee query builder\r\n */\r\nexport function employee(): EmployeeQueryBuilder {\r\n return new EmployeeQueryBuilder();\r\n}\r\n\r\n/**\r\n * Create payroll query builder\r\n */\r\nexport function payroll(): PayrollQueryBuilder {\r\n return new PayrollQueryBuilder();\r\n}\r\n\r\n/**\r\n * Create generic query builder\r\n */\r\nexport function createQueryBuilder<T extends Record<string, unknown> = Record<string, unknown>>(\r\n initialQuery?: T\r\n): QueryBuilder<T> {\r\n return new QueryBuilder(initialQuery);\r\n}\r\n\r\n// ============================================================================\r\n// Convenience Query Builders\r\n// ============================================================================\r\n\r\n/**\r\n * Build employee query from options\r\n */\r\nexport function buildEmployeeQuery(options: {\r\n organizationId: ObjectIdLike;\r\n userId?: ObjectIdLike;\r\n statuses?: EmployeeStatus[];\r\n department?: Department | string;\r\n employmentType?: EmploymentType | string;\r\n}): Record<string, unknown> {\r\n const builder = employee().forOrganization(options.organizationId);\r\n\r\n if (options.userId) {\r\n builder.forUser(options.userId);\r\n }\r\n if (options.statuses) {\r\n builder.withStatus(...options.statuses);\r\n }\r\n if (options.department) {\r\n builder.inDepartment(options.department);\r\n }\r\n if (options.employmentType) {\r\n builder.withEmploymentType(options.employmentType);\r\n }\r\n\r\n return builder.build();\r\n}\r\n\r\n/**\r\n * Build payroll query from options\r\n */\r\nexport function buildPayrollQuery(options: {\r\n employeeId?: ObjectIdLike;\r\n organizationId?: ObjectIdLike;\r\n month?: number;\r\n year?: number;\r\n statuses?: PayrollStatus[];\r\n}): Record<string, unknown> {\r\n const builder = payroll();\r\n\r\n if (options.organizationId) {\r\n builder.forOrganization(options.organizationId);\r\n }\r\n if (options.employeeId) {\r\n builder.forEmployee(options.employeeId);\r\n }\r\n if (options.month || options.year) {\r\n builder.forPeriod(options.month, options.year);\r\n }\r\n if (options.statuses) {\r\n builder.withStatus(...options.statuses);\r\n }\r\n\r\n return builder.build();\r\n}\r\n\r\n// ============================================================================\r\n// Aggregation Pipeline Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Build aggregation pipeline from stages\r\n */\r\nexport function buildAggregationPipeline(\r\n ...stages: Array<Record<string, unknown> | undefined | null>\r\n): Record<string, unknown>[] {\r\n return stages.filter((stage): stage is Record<string, unknown> => !!stage);\r\n}\r\n\r\n/**\r\n * Match stage\r\n */\r\nexport function matchStage(query: Record<string, unknown>): Record<string, unknown> {\r\n return { $match: query };\r\n}\r\n\r\n/**\r\n * Group stage\r\n */\r\nexport function groupStage(\r\n groupBy: string | null,\r\n aggregations: Record<string, unknown>\r\n): Record<string, unknown> {\r\n return {\r\n $group: {\r\n _id: groupBy,\r\n ...aggregations,\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Sort stage\r\n */\r\nexport function sortStage(sortBy: Record<string, 1 | -1>): Record<string, unknown> {\r\n return { $sort: sortBy };\r\n}\r\n\r\n/**\r\n * Limit stage\r\n */\r\nexport function limitStage(limit: number): Record<string, unknown> {\r\n return { $limit: limit };\r\n}\r\n\r\n/**\r\n * Skip stage\r\n */\r\nexport function skipStage(skip: number): Record<string, unknown> {\r\n return { $skip: skip };\r\n}\r\n\r\n/**\r\n * Project stage\r\n */\r\nexport function projectStage(fields: Record<string, unknown>): Record<string, unknown> {\r\n return { $project: fields };\r\n}\r\n\r\n/**\r\n * Lookup stage\r\n */\r\nexport function lookupStage(options: {\r\n from: string;\r\n localField: string;\r\n foreignField: string;\r\n as: string;\r\n}): Record<string, unknown> {\r\n return { $lookup: options };\r\n}\r\n\r\n/**\r\n * Unwind stage\r\n */\r\nexport function unwindStage(\r\n path: string,\r\n options: { preserveNullAndEmptyArrays?: boolean } = {}\r\n): Record<string, unknown> {\r\n return { $unwind: { path, ...options } };\r\n}\r\n\r\n// ============================================================================\r\n// Default Export\r\n// ============================================================================\r\n\r\nexport default {\r\n toObjectId,\r\n safeToObjectId,\r\n isValidObjectId,\r\n QueryBuilder,\r\n EmployeeQueryBuilder,\r\n PayrollQueryBuilder,\r\n employee,\r\n payroll,\r\n createQueryBuilder,\r\n buildEmployeeQuery,\r\n buildPayrollQuery,\r\n buildAggregationPipeline,\r\n matchStage,\r\n groupStage,\r\n sortStage,\r\n limitStage,\r\n skipStage,\r\n projectStage,\r\n lookupStage,\r\n unwindStage,\r\n};\r\n\r\n","/**\r\n * @classytic/payroll - Validation Utilities\r\n *\r\n * Fluent, composable, type-safe validation\r\n * Clear semantics and helpful error messages\r\n */\r\n\r\nimport type {\r\n EmployeeStatus,\r\n EmploymentType,\r\n Compensation,\r\n BankDetails,\r\n EmployeeValidationResult,\r\n} from '../types.js';\r\nimport {\r\n EMPLOYEE_STATUS_VALUES,\r\n EMPLOYMENT_TYPE_VALUES,\r\n} from '../enums.js';\r\nimport { diffInMonths } from './date.js';\r\n\r\n// ============================================================================\r\n// Employee Status Validators\r\n// ============================================================================\r\n\r\n/**\r\n * Check if employee is active\r\n */\r\nexport function isActive(employee: { status?: EmployeeStatus }): boolean {\r\n return employee?.status === 'active';\r\n}\r\n\r\n/**\r\n * Check if employee is on leave\r\n */\r\nexport function isOnLeave(employee: { status?: EmployeeStatus }): boolean {\r\n return employee?.status === 'on_leave';\r\n}\r\n\r\n/**\r\n * Check if employee is suspended\r\n */\r\nexport function isSuspended(employee: { status?: EmployeeStatus }): boolean {\r\n return employee?.status === 'suspended';\r\n}\r\n\r\n/**\r\n * Check if employee is terminated\r\n */\r\nexport function isTerminated(employee: { status?: EmployeeStatus }): boolean {\r\n return employee?.status === 'terminated';\r\n}\r\n\r\n/**\r\n * Check if employee is employed (not terminated)\r\n */\r\nexport function isEmployed(employee: { status?: EmployeeStatus }): boolean {\r\n return (\r\n isActive(employee) || isOnLeave(employee) || isSuspended(employee)\r\n );\r\n}\r\n\r\n/**\r\n * Check if employee can receive salary\r\n */\r\nexport function canReceiveSalary(employee: {\r\n status?: EmployeeStatus;\r\n compensation?: { baseAmount?: number };\r\n}): boolean {\r\n return (\r\n (isActive(employee) || isOnLeave(employee)) &&\r\n (employee.compensation?.baseAmount ?? 0) > 0\r\n );\r\n}\r\n\r\n/**\r\n * Check if employment can be updated\r\n */\r\nexport function canUpdateEmployment(employee: { status?: EmployeeStatus }): boolean {\r\n return !isTerminated(employee);\r\n}\r\n\r\n// ============================================================================\r\n// Compensation Validators\r\n// ============================================================================\r\n\r\n/**\r\n * Check if employee has valid compensation\r\n */\r\nexport function hasCompensation(employee: {\r\n compensation?: { baseAmount?: number };\r\n}): boolean {\r\n return (employee.compensation?.baseAmount ?? 0) > 0;\r\n}\r\n\r\n/**\r\n * Check if compensation is valid\r\n */\r\nexport function isValidCompensation(compensation?: Compensation): boolean {\r\n return !!(\r\n compensation?.baseAmount &&\r\n compensation.baseAmount > 0 &&\r\n compensation.frequency &&\r\n compensation.currency\r\n );\r\n}\r\n\r\n/**\r\n * Check if bank details are valid\r\n */\r\nexport function isValidBankDetails(bankDetails?: BankDetails): boolean {\r\n return !!(\r\n bankDetails?.accountNumber &&\r\n bankDetails.bankName &&\r\n bankDetails.accountName\r\n );\r\n}\r\n\r\n// ============================================================================\r\n// Probation Validators\r\n// ============================================================================\r\n\r\n/**\r\n * Check if employee is in probation\r\n */\r\nexport function isInProbation(\r\n employee: { probationEndDate?: Date | null },\r\n now = new Date()\r\n): boolean {\r\n if (!employee?.probationEndDate) return false;\r\n return new Date(employee.probationEndDate) > now;\r\n}\r\n\r\n/**\r\n * Check if employee has completed probation\r\n */\r\nexport function hasCompletedProbation(\r\n employee: { probationEndDate?: Date | null },\r\n now = new Date()\r\n): boolean {\r\n if (!employee?.probationEndDate) return true;\r\n return new Date(employee.probationEndDate) <= now;\r\n}\r\n\r\n// ============================================================================\r\n// Eligibility Validators\r\n// ============================================================================\r\n\r\n/**\r\n * Check if employee is eligible for bonus\r\n */\r\nexport function isEligibleForBonus(\r\n employee: { status?: EmployeeStatus; hireDate?: Date },\r\n requiredMonths = 6\r\n): boolean {\r\n if (!isActive(employee) || !employee.hireDate) return false;\r\n const monthsEmployed = diffInMonths(employee.hireDate, new Date());\r\n return monthsEmployed >= requiredMonths;\r\n}\r\n\r\n/**\r\n * Check if employee is eligible for payroll\r\n */\r\nexport function isEligibleForPayroll(employee: {\r\n status?: EmployeeStatus;\r\n compensation?: { baseAmount?: number };\r\n bankDetails?: BankDetails;\r\n}): { eligible: boolean; reasons: string[] } {\r\n const reasons: string[] = [];\r\n\r\n if (!isActive(employee) && !isOnLeave(employee)) {\r\n reasons.push('Employee is not in active or on-leave status');\r\n }\r\n\r\n if (!hasCompensation(employee)) {\r\n reasons.push('Employee has no valid compensation');\r\n }\r\n\r\n return {\r\n eligible: reasons.length === 0,\r\n reasons,\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Field Validators\r\n// ============================================================================\r\n\r\n/**\r\n * Check if value is required\r\n */\r\nexport function required(fieldName: string): (value: unknown) => string | true {\r\n return (value: unknown) =>\r\n value !== undefined && value !== null && value !== ''\r\n ? true\r\n : `${fieldName} is required`;\r\n}\r\n\r\n/**\r\n * Check minimum value\r\n */\r\nexport function min(\r\n minValue: number,\r\n fieldName: string\r\n): (value: number) => string | true {\r\n return (value: number) =>\r\n value >= minValue ? true : `${fieldName} must be at least ${minValue}`;\r\n}\r\n\r\n/**\r\n * Check maximum value\r\n */\r\nexport function max(\r\n maxValue: number,\r\n fieldName: string\r\n): (value: number) => string | true {\r\n return (value: number) =>\r\n value <= maxValue ? true : `${fieldName} must not exceed ${maxValue}`;\r\n}\r\n\r\n/**\r\n * Check value is in range\r\n */\r\nexport function inRange(\r\n minValue: number,\r\n maxValue: number,\r\n fieldName: string\r\n): (value: number) => string | true {\r\n return (value: number) =>\r\n value >= minValue && value <= maxValue\r\n ? true\r\n : `${fieldName} must be between ${minValue} and ${maxValue}`;\r\n}\r\n\r\n/**\r\n * Check value is positive\r\n */\r\nexport function isPositive(fieldName: string): (value: number) => string | true {\r\n return (value: number) =>\r\n value > 0 ? true : `${fieldName} must be positive`;\r\n}\r\n\r\n/**\r\n * Check value is one of allowed values\r\n */\r\nexport function oneOf<T extends string>(\r\n allowedValues: readonly T[],\r\n fieldName: string\r\n): (value: T) => string | true {\r\n return (value: T) =>\r\n allowedValues.includes(value)\r\n ? true\r\n : `${fieldName} must be one of: ${allowedValues.join(', ')}`;\r\n}\r\n\r\n// ============================================================================\r\n// Enum Validators\r\n// ============================================================================\r\n\r\n/**\r\n * Check if status is valid\r\n */\r\nexport function isValidStatus(value: string): value is EmployeeStatus {\r\n return EMPLOYEE_STATUS_VALUES.includes(value as EmployeeStatus);\r\n}\r\n\r\n/**\r\n * Check if employment type is valid\r\n */\r\nexport function isValidEmploymentType(value: string): value is EmploymentType {\r\n return EMPLOYMENT_TYPE_VALUES.includes(value as EmploymentType);\r\n}\r\n\r\n// ============================================================================\r\n// Composite Validators\r\n// ============================================================================\r\n\r\n/**\r\n * Compose multiple validators\r\n */\r\nexport function composeValidators<T>(\r\n ...validators: Array<(value: T, data?: unknown) => string | true>\r\n): (value: T, data?: unknown) => string | true {\r\n return (value: T, data?: unknown) => {\r\n for (const validator of validators) {\r\n const result = validator(value, data);\r\n if (result !== true) return result;\r\n }\r\n return true;\r\n };\r\n}\r\n\r\n/**\r\n * Create a validator from validation functions\r\n */\r\nexport function createValidator<T extends Record<string, unknown>>(\r\n validationFns: Record<string, (value: unknown, data: T) => string | true>\r\n): (data: T) => EmployeeValidationResult {\r\n return (data: T) => {\r\n const errors: string[] = [];\r\n\r\n for (const [field, validator] of Object.entries(validationFns)) {\r\n const result = validator((data as Record<string, unknown>)[field], data);\r\n if (result !== true) {\r\n errors.push(result);\r\n }\r\n }\r\n\r\n return {\r\n valid: errors.length === 0,\r\n errors,\r\n };\r\n };\r\n}\r\n\r\n/**\r\n * Validate required fields exist\r\n */\r\nexport function hasRequiredFields(\r\n obj: Record<string, unknown>,\r\n fields: string[]\r\n): { valid: boolean; missing: string[] } {\r\n const missing = fields.filter(\r\n (field) => obj[field] === undefined || obj[field] === null\r\n );\r\n return {\r\n valid: missing.length === 0,\r\n missing,\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Aliases for backwards compatibility\r\n// ============================================================================\r\n\r\nexport const minValue = min;\r\nexport const maxValue = max;\r\nexport const isInRange = inRange;\r\n\r\n// ============================================================================\r\n// Default Export\r\n// ============================================================================\r\n\r\nexport default {\r\n // Status validators\r\n isActive,\r\n isOnLeave,\r\n isSuspended,\r\n isTerminated,\r\n isEmployed,\r\n canReceiveSalary,\r\n canUpdateEmployment,\r\n // Compensation validators\r\n hasCompensation,\r\n isValidCompensation,\r\n isValidBankDetails,\r\n // Probation validators\r\n isInProbation,\r\n hasCompletedProbation,\r\n // Eligibility validators\r\n isEligibleForBonus,\r\n isEligibleForPayroll,\r\n // Field validators\r\n required,\r\n min,\r\n max,\r\n inRange,\r\n isPositive,\r\n oneOf,\r\n // Enum validators\r\n isValidStatus,\r\n isValidEmploymentType,\r\n // Composite validators\r\n composeValidators,\r\n createValidator,\r\n hasRequiredFields,\r\n};\r\n\r\n","/**\r\n * @classytic/payroll - Logger\r\n *\r\n * Pluggable logger abstraction\r\n * Defaults to console, can be replaced with pino, winston, etc.\r\n */\r\n\r\nimport type { Logger } from '../types.js';\r\n\r\n// ============================================================================\r\n// Default Logger Implementation\r\n// ============================================================================\r\n\r\nconst createConsoleLogger = (): Logger => ({\r\n info: (message: string, meta?: Record<string, unknown>) => {\r\n if (meta) {\r\n console.log(`[Payroll] INFO: ${message}`, meta);\r\n } else {\r\n console.log(`[Payroll] INFO: ${message}`);\r\n }\r\n },\r\n error: (message: string, meta?: Record<string, unknown>) => {\r\n if (meta) {\r\n console.error(`[Payroll] ERROR: ${message}`, meta);\r\n } else {\r\n console.error(`[Payroll] ERROR: ${message}`);\r\n }\r\n },\r\n warn: (message: string, meta?: Record<string, unknown>) => {\r\n if (meta) {\r\n console.warn(`[Payroll] WARN: ${message}`, meta);\r\n } else {\r\n console.warn(`[Payroll] WARN: ${message}`);\r\n }\r\n },\r\n debug: (message: string, meta?: Record<string, unknown>) => {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (meta) {\r\n console.log(`[Payroll] DEBUG: ${message}`, meta);\r\n } else {\r\n console.log(`[Payroll] DEBUG: ${message}`);\r\n }\r\n }\r\n },\r\n});\r\n\r\n// ============================================================================\r\n// Logger State\r\n// ============================================================================\r\n\r\nlet currentLogger: Logger = createConsoleLogger();\r\nlet loggingEnabled = true;\r\n\r\n// ============================================================================\r\n// Logger Functions\r\n// ============================================================================\r\n\r\n/**\r\n * Get the current logger instance\r\n */\r\nexport function getLogger(): Logger {\r\n return currentLogger;\r\n}\r\n\r\n/**\r\n * Set a custom logger instance\r\n */\r\nexport function setLogger(logger: Logger): void {\r\n currentLogger = logger;\r\n}\r\n\r\n/**\r\n * Reset to default console logger\r\n */\r\nexport function resetLogger(): void {\r\n currentLogger = createConsoleLogger();\r\n}\r\n\r\n/**\r\n * Create a child logger with prefix\r\n */\r\nexport function createChildLogger(prefix: string): Logger {\r\n const parent = currentLogger;\r\n return {\r\n info: (message: string, meta?: Record<string, unknown>) =>\r\n parent.info(`[${prefix}] ${message}`, meta),\r\n error: (message: string, meta?: Record<string, unknown>) =>\r\n parent.error(`[${prefix}] ${message}`, meta),\r\n warn: (message: string, meta?: Record<string, unknown>) =>\r\n parent.warn(`[${prefix}] ${message}`, meta),\r\n debug: (message: string, meta?: Record<string, unknown>) =>\r\n parent.debug(`[${prefix}] ${message}`, meta),\r\n };\r\n}\r\n\r\n/**\r\n * Create a silent logger (for testing)\r\n */\r\nexport function createSilentLogger(): Logger {\r\n return {\r\n info: () => {},\r\n error: () => {},\r\n warn: () => {},\r\n debug: () => {},\r\n };\r\n}\r\n\r\n/**\r\n * Enable logging globally\r\n */\r\nexport function enableLogging(): void {\r\n loggingEnabled = true;\r\n}\r\n\r\n/**\r\n * Disable logging globally (useful for production)\r\n */\r\nexport function disableLogging(): void {\r\n loggingEnabled = false;\r\n}\r\n\r\n/**\r\n * Check if logging is enabled\r\n */\r\nexport function isLoggingEnabled(): boolean {\r\n return loggingEnabled;\r\n}\r\n\r\n// ============================================================================\r\n// Logger Proxy Object\r\n// ============================================================================\r\n\r\n/**\r\n * Logger proxy that always delegates to currentLogger\r\n * Respects global logging enabled/disabled state\r\n */\r\nexport const logger: Logger = {\r\n info: (message: string, meta?: Record<string, unknown>) => {\r\n if (loggingEnabled) currentLogger.info(message, meta);\r\n },\r\n error: (message: string, meta?: Record<string, unknown>) => {\r\n if (loggingEnabled) currentLogger.error(message, meta);\r\n },\r\n warn: (message: string, meta?: Record<string, unknown>) => {\r\n if (loggingEnabled) currentLogger.warn(message, meta);\r\n },\r\n debug: (message: string, meta?: Record<string, unknown>) => {\r\n if (loggingEnabled) currentLogger.debug(message, meta);\r\n },\r\n};\r\n\r\nexport default logger;\r\n\r\n","/**\r\n * @classytic/payroll - Employee Service\r\n *\r\n * High-level employee operations with dependency injection\r\n */\r\n\r\nimport type { Model, ClientSession } from 'mongoose';\r\nimport type {\r\n ObjectIdLike,\r\n EmployeeDocument,\r\n EmployeeStatus,\r\n Department,\r\n EmploymentType,\r\n Compensation,\r\n OperationContext,\r\n} from '../types.js';\r\nimport { EmployeeFactory, type CreateEmployeeParams } from '../factories/employee.factory.js';\r\nimport { employee as employeeQuery, toObjectId } from '../utils/query-builders.js';\r\nimport { isActive, isEmployed, canReceiveSalary } from '../utils/validation.js';\r\nimport { logger } from '../utils/logger.js';\r\n\r\n// ============================================================================\r\n// Employee Service\r\n// ============================================================================\r\n\r\nexport class EmployeeService {\r\n constructor(private readonly EmployeeModel: Model<EmployeeDocument>) {}\r\n\r\n /**\r\n * Find employee by ID\r\n */\r\n async findById(\r\n employeeId: ObjectIdLike,\r\n options: { session?: ClientSession; populate?: boolean } = {}\r\n ): Promise<EmployeeDocument | null> {\r\n let query = this.EmployeeModel.findById(toObjectId(employeeId));\r\n \r\n if (options.session) {\r\n query = query.session(options.session);\r\n }\r\n \r\n if (options.populate) {\r\n query = query.populate('userId', 'name email phone');\r\n }\r\n \r\n return query.exec();\r\n }\r\n\r\n /**\r\n * Find employee by user and organization\r\n */\r\n async findByUserId(\r\n userId: ObjectIdLike,\r\n organizationId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<EmployeeDocument | null> {\r\n const query = employeeQuery()\r\n .forUser(userId)\r\n .forOrganization(organizationId)\r\n .build();\r\n\r\n let mongooseQuery = this.EmployeeModel.findOne(query);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n return mongooseQuery.exec();\r\n }\r\n\r\n /**\r\n * Find active employees in organization\r\n */\r\n async findActive(\r\n organizationId: ObjectIdLike,\r\n options: { session?: ClientSession; projection?: Record<string, number> } = {}\r\n ): Promise<EmployeeDocument[]> {\r\n const query = employeeQuery()\r\n .forOrganization(organizationId)\r\n .active()\r\n .build();\r\n\r\n let mongooseQuery = this.EmployeeModel.find(query, options.projection);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n return mongooseQuery.exec();\r\n }\r\n\r\n /**\r\n * Find employed employees (not terminated)\r\n */\r\n async findEmployed(\r\n organizationId: ObjectIdLike,\r\n options: { session?: ClientSession; projection?: Record<string, number> } = {}\r\n ): Promise<EmployeeDocument[]> {\r\n const query = employeeQuery()\r\n .forOrganization(organizationId)\r\n .employed()\r\n .build();\r\n\r\n let mongooseQuery = this.EmployeeModel.find(query, options.projection);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n return mongooseQuery.exec();\r\n }\r\n\r\n /**\r\n * Find employees by department\r\n */\r\n async findByDepartment(\r\n organizationId: ObjectIdLike,\r\n department: Department,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<EmployeeDocument[]> {\r\n const query = employeeQuery()\r\n .forOrganization(organizationId)\r\n .inDepartment(department)\r\n .active()\r\n .build();\r\n\r\n let mongooseQuery = this.EmployeeModel.find(query);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n return mongooseQuery.exec();\r\n }\r\n\r\n /**\r\n * Find employees eligible for payroll\r\n */\r\n async findEligibleForPayroll(\r\n organizationId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<EmployeeDocument[]> {\r\n const query = employeeQuery()\r\n .forOrganization(organizationId)\r\n .employed()\r\n .build();\r\n\r\n let mongooseQuery = this.EmployeeModel.find(query);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n const employees = await mongooseQuery.exec();\r\n return employees.filter((emp) => canReceiveSalary(emp));\r\n }\r\n\r\n /**\r\n * Create new employee\r\n */\r\n async create(\r\n params: CreateEmployeeParams,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<EmployeeDocument> {\r\n const employeeData = EmployeeFactory.create(params);\r\n \r\n const [employee] = await this.EmployeeModel.create([employeeData], {\r\n session: options.session,\r\n });\r\n\r\n logger.info('Employee created', {\r\n employeeId: employee.employeeId,\r\n organizationId: employee.organizationId.toString(),\r\n });\r\n\r\n return employee;\r\n }\r\n\r\n /**\r\n * Update employee status\r\n */\r\n async updateStatus(\r\n employeeId: ObjectIdLike,\r\n status: EmployeeStatus,\r\n context: OperationContext = {},\r\n options: { session?: ClientSession } = {}\r\n ): Promise<EmployeeDocument> {\r\n const employee = await this.findById(employeeId, options);\r\n if (!employee) {\r\n throw new Error('Employee not found');\r\n }\r\n\r\n employee.status = status;\r\n await employee.save({ session: options.session });\r\n\r\n logger.info('Employee status updated', {\r\n employeeId: employee.employeeId,\r\n newStatus: status,\r\n });\r\n\r\n return employee;\r\n }\r\n\r\n /**\r\n * Update employee compensation\r\n * \r\n * NOTE: This merges the compensation fields rather than replacing the entire object.\r\n * To update allowances/deductions, use addAllowance/removeAllowance methods.\r\n */\r\n async updateCompensation(\r\n employeeId: ObjectIdLike,\r\n compensation: Partial<Compensation>,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<EmployeeDocument> {\r\n // First fetch the employee to get current compensation\r\n const currentEmployee = await this.EmployeeModel.findById(toObjectId(employeeId)).session(options.session || null);\r\n if (!currentEmployee) {\r\n throw new Error('Employee not found');\r\n }\r\n\r\n // Build update object that only sets provided fields\r\n const updateFields: Record<string, unknown> = {\r\n 'compensation.lastModified': new Date(),\r\n };\r\n\r\n // Only update specific fields if provided (preserve allowances/deductions)\r\n if (compensation.baseAmount !== undefined) {\r\n updateFields['compensation.baseAmount'] = compensation.baseAmount;\r\n }\r\n if (compensation.currency !== undefined) {\r\n updateFields['compensation.currency'] = compensation.currency;\r\n }\r\n if (compensation.frequency !== undefined) {\r\n updateFields['compensation.frequency'] = compensation.frequency;\r\n }\r\n if (compensation.effectiveFrom !== undefined) {\r\n updateFields['compensation.effectiveFrom'] = compensation.effectiveFrom;\r\n }\r\n // Note: allowances and deductions should NOT be updated here\r\n // Use addAllowance/removeAllowance methods instead\r\n\r\n const employee = await this.EmployeeModel.findByIdAndUpdate(\r\n toObjectId(employeeId),\r\n { $set: updateFields },\r\n { new: true, runValidators: true, session: options.session }\r\n );\r\n\r\n if (!employee) {\r\n throw new Error('Employee not found');\r\n }\r\n\r\n return employee;\r\n }\r\n\r\n /**\r\n * Get employee statistics for organization\r\n */\r\n async getEmployeeStats(\r\n organizationId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<{\r\n total: number;\r\n active: number;\r\n employed: number;\r\n canReceiveSalary: number;\r\n byStatus: Record<string, number>;\r\n byDepartment: Record<string, number>;\r\n }> {\r\n const query = employeeQuery().forOrganization(organizationId).build();\r\n \r\n let mongooseQuery = this.EmployeeModel.find(query);\r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n const employees = await mongooseQuery.exec();\r\n\r\n return {\r\n total: employees.length,\r\n active: employees.filter(isActive).length,\r\n employed: employees.filter(isEmployed).length,\r\n canReceiveSalary: employees.filter(canReceiveSalary).length,\r\n byStatus: this.groupByStatus(employees),\r\n byDepartment: this.groupByDepartment(employees),\r\n };\r\n }\r\n\r\n /**\r\n * Group employees by status\r\n */\r\n private groupByStatus(employees: EmployeeDocument[]): Record<string, number> {\r\n return employees.reduce(\r\n (acc, emp) => {\r\n acc[emp.status] = (acc[emp.status] || 0) + 1;\r\n return acc;\r\n },\r\n {} as Record<string, number>\r\n );\r\n }\r\n\r\n /**\r\n * Group employees by department\r\n */\r\n private groupByDepartment(employees: EmployeeDocument[]): Record<string, number> {\r\n return employees.reduce(\r\n (acc, emp) => {\r\n const dept = emp.department || 'unassigned';\r\n acc[dept] = (acc[dept] || 0) + 1;\r\n return acc;\r\n },\r\n {} as Record<string, number>\r\n );\r\n }\r\n\r\n /**\r\n * Check if employee is active\r\n */\r\n isActive(employee: EmployeeDocument): boolean {\r\n return isActive(employee);\r\n }\r\n\r\n /**\r\n * Check if employee is employed\r\n */\r\n isEmployed(employee: EmployeeDocument): boolean {\r\n return isEmployed(employee);\r\n }\r\n\r\n /**\r\n * Check if employee can receive salary\r\n */\r\n canReceiveSalary(employee: EmployeeDocument): boolean {\r\n return canReceiveSalary(employee);\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Factory Function\r\n// ============================================================================\r\n\r\n/**\r\n * Create employee service instance\r\n */\r\nexport function createEmployeeService(\r\n EmployeeModel: Model<EmployeeDocument>\r\n): EmployeeService {\r\n return new EmployeeService(EmployeeModel);\r\n}\r\n\r\n","/**\r\n * @classytic/payroll - Calculation Utilities\r\n *\r\n * Pure, functional, composable financial calculations\r\n * No side effects, highly testable\r\n */\r\n\r\nimport type {\r\n Allowance,\r\n Deduction,\r\n Compensation,\r\n TaxCalculationResult,\r\n CompensationBreakdownResult,\r\n ProRatingResult,\r\n PayPeriodInfo,\r\n} from '../types.js';\r\nimport { diffInDays } from './date.js';\r\n\r\n// ============================================================================\r\n// Basic Math Operations\r\n// ============================================================================\r\n\r\n/**\r\n * Sum array of numbers\r\n */\r\nexport function sum(numbers: number[]): number {\r\n return numbers.reduce((total, n) => total + n, 0);\r\n}\r\n\r\n/**\r\n * Sum by property\r\n */\r\nexport function sumBy<T>(items: T[], getter: (item: T) => number): number {\r\n return items.reduce((total, item) => total + getter(item), 0);\r\n}\r\n\r\n/**\r\n * Sum allowances\r\n */\r\nexport function sumAllowances(allowances: Array<{ amount: number }>): number {\r\n return sumBy(allowances, (a) => a.amount);\r\n}\r\n\r\n/**\r\n * Sum deductions\r\n */\r\nexport function sumDeductions(deductions: Array<{ amount: number }>): number {\r\n return sumBy(deductions, (d) => d.amount);\r\n}\r\n\r\n/**\r\n * Apply percentage to amount\r\n */\r\nexport function applyPercentage(amount: number, percentage: number): number {\r\n return Math.round(amount * (percentage / 100));\r\n}\r\n\r\n/**\r\n * Calculate percentage of total\r\n */\r\nexport function calculatePercentage(part: number, total: number): number {\r\n return total > 0 ? Math.round((part / total) * 100) : 0;\r\n}\r\n\r\n/**\r\n * Round to decimal places\r\n */\r\nexport function roundTo(value: number, decimals = 2): number {\r\n const factor = Math.pow(10, decimals);\r\n return Math.round(value * factor) / factor;\r\n}\r\n\r\n// ============================================================================\r\n// Salary Calculations\r\n// ============================================================================\r\n\r\n/**\r\n * Calculate gross salary from base and allowances\r\n */\r\nexport function calculateGross(\r\n baseAmount: number,\r\n allowances: Array<{ amount: number }>\r\n): number {\r\n return baseAmount + sumAllowances(allowances);\r\n}\r\n\r\n/**\r\n * Calculate net salary from gross and deductions\r\n */\r\nexport function calculateNet(\r\n gross: number,\r\n deductions: Array<{ amount: number }>\r\n): number {\r\n return Math.max(0, gross - sumDeductions(deductions));\r\n}\r\n\r\n/**\r\n * Calculate total compensation\r\n */\r\nexport function calculateTotalCompensation(\r\n baseAmount: number,\r\n allowances: Array<{ amount: number }>,\r\n deductions: Array<{ amount: number }>\r\n): { gross: number; net: number; deductions: number } {\r\n const gross = calculateGross(baseAmount, allowances);\r\n const totalDeductions = sumDeductions(deductions);\r\n const net = calculateNet(gross, deductions);\r\n return { gross, net, deductions: totalDeductions };\r\n}\r\n\r\n// ============================================================================\r\n// Allowance & Deduction Calculation\r\n// ============================================================================\r\n\r\n/**\r\n * Calculate allowance amount (handles percentage-based)\r\n */\r\nexport function calculateAllowanceAmount(\r\n allowance: Pick<Allowance, 'amount' | 'isPercentage' | 'value'>,\r\n baseAmount: number\r\n): number {\r\n if (allowance.isPercentage && allowance.value !== undefined) {\r\n return applyPercentage(baseAmount, allowance.value);\r\n }\r\n return allowance.amount;\r\n}\r\n\r\n/**\r\n * Calculate deduction amount (handles percentage-based)\r\n */\r\nexport function calculateDeductionAmount(\r\n deduction: Pick<Deduction, 'amount' | 'isPercentage' | 'value'>,\r\n baseAmount: number\r\n): number {\r\n if (deduction.isPercentage && deduction.value !== undefined) {\r\n return applyPercentage(baseAmount, deduction.value);\r\n }\r\n return deduction.amount;\r\n}\r\n\r\n/**\r\n * Calculate all allowances with their actual amounts\r\n */\r\nexport function calculateAllowances(\r\n allowances: Allowance[],\r\n baseAmount: number\r\n): Array<Allowance & { calculatedAmount: number }> {\r\n return allowances.map((allowance) => ({\r\n ...allowance,\r\n calculatedAmount: calculateAllowanceAmount(allowance, baseAmount),\r\n }));\r\n}\r\n\r\n/**\r\n * Calculate all deductions with their actual amounts\r\n */\r\nexport function calculateDeductions(\r\n deductions: Deduction[],\r\n baseAmount: number\r\n): Array<Deduction & { calculatedAmount: number }> {\r\n return deductions.map((deduction) => ({\r\n ...deduction,\r\n calculatedAmount: calculateDeductionAmount(deduction, baseAmount),\r\n }));\r\n}\r\n\r\n// ============================================================================\r\n// Compensation Breakdown\r\n// ============================================================================\r\n\r\n/**\r\n * Calculate full compensation breakdown\r\n */\r\nexport function calculateCompensationBreakdown(\r\n compensation: Pick<Compensation, 'baseAmount' | 'allowances' | 'deductions'>\r\n): CompensationBreakdownResult {\r\n const { baseAmount, allowances = [], deductions = [] } = compensation;\r\n\r\n const calculatedAllowances = calculateAllowances(allowances, baseAmount);\r\n const calculatedDeductions = calculateDeductions(deductions, baseAmount);\r\n\r\n const grossAmount =\r\n baseAmount + sumBy(calculatedAllowances, (a) => a.calculatedAmount);\r\n const netAmount =\r\n grossAmount - sumBy(calculatedDeductions, (d) => d.calculatedAmount);\r\n\r\n return {\r\n baseAmount,\r\n allowances: calculatedAllowances,\r\n deductions: calculatedDeductions,\r\n grossAmount,\r\n netAmount: Math.max(0, netAmount),\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Pro-Rating Calculations\r\n// ============================================================================\r\n\r\n/**\r\n * Calculate pro-rating for mid-month hires\r\n */\r\nexport function calculateProRating(\r\n hireDate: Date,\r\n periodStart: Date,\r\n periodEnd: Date\r\n): ProRatingResult {\r\n const totalDays = diffInDays(periodStart, periodEnd) + 1;\r\n\r\n // Hired before period start - no pro-rating\r\n if (hireDate <= periodStart) {\r\n return {\r\n isProRated: false,\r\n totalDays,\r\n actualDays: totalDays,\r\n ratio: 1,\r\n };\r\n }\r\n\r\n // Hired during the period - pro-rate\r\n if (hireDate > periodStart && hireDate <= periodEnd) {\r\n const actualDays = diffInDays(hireDate, periodEnd) + 1;\r\n const ratio = actualDays / totalDays;\r\n\r\n return {\r\n isProRated: true,\r\n totalDays,\r\n actualDays,\r\n ratio,\r\n };\r\n }\r\n\r\n // Hired after period - no work days\r\n return {\r\n isProRated: false,\r\n totalDays,\r\n actualDays: 0,\r\n ratio: 0,\r\n };\r\n}\r\n\r\n/**\r\n * Apply pro-rating to an amount\r\n */\r\nexport function applyProRating(\r\n amount: number,\r\n proRating: ProRatingResult\r\n): number {\r\n return Math.round(amount * proRating.ratio);\r\n}\r\n\r\n/**\r\n * Calculate pro-rated salary\r\n */\r\nexport function calculateProRatedSalary(\r\n baseAmount: number,\r\n hireDate: Date,\r\n period: PayPeriodInfo\r\n): { amount: number; proRating: ProRatingResult } {\r\n const proRating = calculateProRating(hireDate, period.startDate, period.endDate);\r\n const amount = applyProRating(baseAmount, proRating);\r\n return { amount, proRating };\r\n}\r\n\r\n// ============================================================================\r\n// Tax Calculations\r\n// ============================================================================\r\n\r\n/**\r\n * Apply tax brackets to calculate tax\r\n */\r\nexport function applyTaxBrackets(\r\n amount: number,\r\n brackets: Array<{ min: number; max: number; rate: number }>\r\n): number {\r\n let tax = 0;\r\n\r\n for (const bracket of brackets) {\r\n if (amount > bracket.min) {\r\n const taxableAmount = Math.min(amount, bracket.max) - bracket.min;\r\n tax += taxableAmount * bracket.rate;\r\n }\r\n }\r\n\r\n return Math.round(tax);\r\n}\r\n\r\n/**\r\n * Calculate tax with result\r\n */\r\nexport function calculateTax(\r\n amount: number,\r\n brackets: Array<{ min: number; max: number; rate: number }>\r\n): TaxCalculationResult {\r\n const tax = applyTaxBrackets(amount, brackets);\r\n return {\r\n gross: amount,\r\n tax,\r\n net: amount - tax,\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Functional Composition\r\n// ============================================================================\r\n\r\n/**\r\n * Pipe functions left-to-right\r\n * pipe(f, g, h)(x) === h(g(f(x)))\r\n */\r\nexport function pipe<T>(...fns: Array<(value: T) => T>): (value: T) => T {\r\n return (value: T) => fns.reduce((acc, fn) => fn(acc), value);\r\n}\r\n\r\n/**\r\n * Compose functions right-to-left\r\n * compose(f, g, h)(x) === f(g(h(x)))\r\n */\r\nexport function compose<T>(...fns: Array<(value: T) => T>): (value: T) => T {\r\n return (value: T) => fns.reduceRight((acc, fn) => fn(acc), value);\r\n}\r\n\r\n/**\r\n * Create an allowance calculator factory\r\n */\r\nexport function createAllowanceCalculator(\r\n allowances: Allowance[]\r\n): (baseSalary: number) => Array<Allowance & { calculatedAmount: number }> {\r\n return (baseSalary: number) => calculateAllowances(allowances, baseSalary);\r\n}\r\n\r\n/**\r\n * Create a deduction calculator factory\r\n */\r\nexport function createDeductionCalculator(\r\n deductions: Deduction[]\r\n): (baseSalary: number) => Array<Deduction & { calculatedAmount: number }> {\r\n return (baseSalary: number) => calculateDeductions(deductions, baseSalary);\r\n}\r\n\r\n// ============================================================================\r\n// Overtime Calculations\r\n// ============================================================================\r\n\r\n/**\r\n * Calculate overtime pay\r\n */\r\nexport function calculateOvertime(\r\n hourlyRate: number,\r\n overtimeHours: number,\r\n multiplier = 1.5\r\n): number {\r\n return Math.round(hourlyRate * overtimeHours * multiplier);\r\n}\r\n\r\n/**\r\n * Calculate hourly rate from monthly salary\r\n */\r\nexport function calculateHourlyRate(\r\n monthlySalary: number,\r\n hoursPerMonth = 176 // 44 hours/week * 4 weeks\r\n): number {\r\n return Math.round(monthlySalary / hoursPerMonth);\r\n}\r\n\r\n/**\r\n * Calculate daily rate from monthly salary\r\n */\r\nexport function calculateDailyRate(\r\n monthlySalary: number,\r\n daysPerMonth = 22\r\n): number {\r\n return Math.round(monthlySalary / daysPerMonth);\r\n}\r\n\r\n// ============================================================================\r\n// Default Export\r\n// ============================================================================\r\n\r\nexport default {\r\n sum,\r\n sumBy,\r\n sumAllowances,\r\n sumDeductions,\r\n applyPercentage,\r\n calculatePercentage,\r\n roundTo,\r\n calculateGross,\r\n calculateNet,\r\n calculateTotalCompensation,\r\n calculateAllowanceAmount,\r\n calculateDeductionAmount,\r\n calculateAllowances,\r\n calculateDeductions,\r\n calculateCompensationBreakdown,\r\n calculateProRating,\r\n applyProRating,\r\n calculateProRatedSalary,\r\n applyTaxBrackets,\r\n calculateTax,\r\n pipe,\r\n compose,\r\n createAllowanceCalculator,\r\n createDeductionCalculator,\r\n calculateOvertime,\r\n calculateHourlyRate,\r\n calculateDailyRate,\r\n};\r\n\r\n","/**\r\n * @classytic/payroll - Payroll Factory\r\n *\r\n * Clean object creation for payroll records\r\n * Immutable operations and builder pattern\r\n */\r\n\r\nimport type {\r\n ObjectIdLike,\r\n PayrollBreakdown,\r\n PayrollPeriod,\r\n PaymentMethod,\r\n Allowance,\r\n Deduction,\r\n Compensation,\r\n} from '../types.js';\r\nimport { getPayPeriod } from '../utils/date.js';\r\nimport { calculateGross, calculateNet, sumAllowances, sumDeductions } from '../utils/calculation.js';\r\nimport { HRM_CONFIG } from '../config.js';\r\n\r\n// ============================================================================\r\n// Payroll Factory Types\r\n// ============================================================================\r\n\r\nexport interface CreatePayrollParams {\r\n employeeId: ObjectIdLike;\r\n organizationId: ObjectIdLike;\r\n baseAmount: number;\r\n allowances?: Array<{ type: string; amount: number; taxable?: boolean }>;\r\n deductions?: Array<{ type: string; amount: number; description?: string }>;\r\n period?: { month?: number; year?: number };\r\n metadata?: {\r\n currency?: string;\r\n paymentMethod?: PaymentMethod;\r\n notes?: string;\r\n };\r\n}\r\n\r\nexport interface PayrollData {\r\n employeeId: ObjectIdLike;\r\n organizationId: ObjectIdLike;\r\n period: PayrollPeriod;\r\n breakdown: PayrollBreakdown;\r\n status: 'pending';\r\n processedAt: null;\r\n paidAt: null;\r\n metadata: {\r\n currency: string;\r\n paymentMethod?: PaymentMethod;\r\n notes?: string;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Payroll Factory\r\n// ============================================================================\r\n\r\nexport class PayrollFactory {\r\n /**\r\n * Create payroll data object\r\n */\r\n static create(params: CreatePayrollParams): PayrollData {\r\n const {\r\n employeeId,\r\n organizationId,\r\n baseAmount,\r\n allowances = [],\r\n deductions = [],\r\n period = {},\r\n metadata = {},\r\n } = params;\r\n\r\n const calculatedAllowances = this.calculateAllowances(baseAmount, allowances);\r\n const calculatedDeductions = this.calculateDeductions(baseAmount, deductions);\r\n\r\n const gross = calculateGross(baseAmount, calculatedAllowances);\r\n const net = calculateNet(gross, calculatedDeductions);\r\n\r\n return {\r\n employeeId,\r\n organizationId,\r\n period: this.createPeriod(period),\r\n breakdown: {\r\n baseAmount,\r\n allowances: calculatedAllowances,\r\n deductions: calculatedDeductions,\r\n grossSalary: gross,\r\n netSalary: net,\r\n },\r\n status: 'pending',\r\n processedAt: null,\r\n paidAt: null,\r\n metadata: {\r\n currency: metadata.currency || HRM_CONFIG.payroll.defaultCurrency,\r\n paymentMethod: metadata.paymentMethod,\r\n notes: metadata.notes,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Create pay period\r\n */\r\n static createPeriod(params: { month?: number; year?: number; payDate?: Date }): PayrollPeriod {\r\n const now = new Date();\r\n const month = params.month || now.getMonth() + 1;\r\n const year = params.year || now.getFullYear();\r\n const period = getPayPeriod(month, year);\r\n\r\n return {\r\n ...period,\r\n payDate: params.payDate || new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Calculate allowances from base amount\r\n */\r\n static calculateAllowances(\r\n baseAmount: number,\r\n allowances: Array<{ type: string; amount: number; taxable?: boolean; isPercentage?: boolean; value?: number }>\r\n ): Array<{ type: string; amount: number; taxable: boolean }> {\r\n return allowances.map((allowance) => {\r\n const amount =\r\n allowance.isPercentage && allowance.value !== undefined\r\n ? Math.round((baseAmount * allowance.value) / 100)\r\n : allowance.amount;\r\n\r\n return {\r\n type: allowance.type,\r\n amount,\r\n taxable: allowance.taxable ?? true,\r\n };\r\n });\r\n }\r\n\r\n /**\r\n * Calculate deductions from base amount\r\n */\r\n static calculateDeductions(\r\n baseAmount: number,\r\n deductions: Array<{ type: string; amount: number; description?: string; isPercentage?: boolean; value?: number }>\r\n ): Array<{ type: string; amount: number; description?: string }> {\r\n return deductions.map((deduction) => {\r\n const amount =\r\n deduction.isPercentage && deduction.value !== undefined\r\n ? Math.round((baseAmount * deduction.value) / 100)\r\n : deduction.amount;\r\n\r\n return {\r\n type: deduction.type,\r\n amount,\r\n description: deduction.description,\r\n };\r\n });\r\n }\r\n\r\n /**\r\n * Create bonus object\r\n */\r\n static createBonus(params: {\r\n type: string;\r\n amount: number;\r\n reason: string;\r\n approvedBy?: ObjectIdLike;\r\n }): { type: string; amount: number; reason: string; approvedBy?: ObjectIdLike; approvedAt: Date } {\r\n return {\r\n type: params.type,\r\n amount: params.amount,\r\n reason: params.reason,\r\n approvedBy: params.approvedBy,\r\n approvedAt: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Mark payroll as paid (immutable)\r\n * Sets both top-level transactionId and metadata for compatibility\r\n */\r\n static markAsPaid<T extends { status: string; paidAt?: Date | null; processedAt?: Date | null; transactionId?: unknown; metadata?: Record<string, unknown> }>(\r\n payroll: T,\r\n params: { paidAt?: Date; transactionId?: ObjectIdLike; paymentMethod?: PaymentMethod } = {}\r\n ): T & { status: 'paid' } {\r\n return {\r\n ...payroll,\r\n status: 'paid' as const,\r\n paidAt: params.paidAt || new Date(),\r\n processedAt: payroll.processedAt || params.paidAt || new Date(),\r\n transactionId: params.transactionId || payroll.transactionId,\r\n metadata: {\r\n ...payroll.metadata,\r\n transactionId: params.transactionId,\r\n paymentMethod: params.paymentMethod || payroll.metadata?.paymentMethod,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Mark payroll as processed (immutable)\r\n */\r\n static markAsProcessed<T extends { status: string; processedAt: Date | null }>(\r\n payroll: T,\r\n params: { processedAt?: Date } = {}\r\n ): T & { status: 'processing' } {\r\n return {\r\n ...payroll,\r\n status: 'processing' as const,\r\n processedAt: params.processedAt || new Date(),\r\n };\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Payroll Builder\r\n// ============================================================================\r\n\r\nexport class PayrollBuilder {\r\n private data: Partial<CreatePayrollParams> = {\r\n allowances: [],\r\n deductions: [],\r\n period: {},\r\n metadata: {},\r\n };\r\n\r\n /**\r\n * Set employee ID\r\n */\r\n forEmployee(employeeId: ObjectIdLike): this {\r\n this.data.employeeId = employeeId;\r\n return this;\r\n }\r\n\r\n /**\r\n * Set organization ID\r\n */\r\n inOrganization(organizationId: ObjectIdLike): this {\r\n this.data.organizationId = organizationId;\r\n return this;\r\n }\r\n\r\n /**\r\n * Set base amount\r\n */\r\n withBaseAmount(amount: number): this {\r\n this.data.baseAmount = amount;\r\n return this;\r\n }\r\n\r\n /**\r\n * Set pay period\r\n */\r\n forPeriod(month: number, year: number): this {\r\n this.data.period = { month, year };\r\n return this;\r\n }\r\n\r\n /**\r\n * Add allowance\r\n */\r\n addAllowance(\r\n type: string,\r\n value: number,\r\n isPercentage = false,\r\n name?: string\r\n ): this {\r\n this.data.allowances = [\r\n ...(this.data.allowances || []),\r\n {\r\n type,\r\n amount: isPercentage ? 0 : value,\r\n isPercentage,\r\n value: isPercentage ? value : undefined,\r\n } as { type: string; amount: number },\r\n ];\r\n return this;\r\n }\r\n\r\n /**\r\n * Add deduction\r\n */\r\n addDeduction(\r\n type: string,\r\n value: number,\r\n isPercentage = false,\r\n description?: string\r\n ): this {\r\n this.data.deductions = [\r\n ...(this.data.deductions || []),\r\n {\r\n type,\r\n amount: isPercentage ? 0 : value,\r\n isPercentage,\r\n value: isPercentage ? value : undefined,\r\n description,\r\n } as { type: string; amount: number; description?: string },\r\n ];\r\n return this;\r\n }\r\n\r\n /**\r\n * Add bonus\r\n */\r\n addBonus(amount: number, reason: string): this {\r\n return this.addAllowance('bonus', amount, false, reason);\r\n }\r\n\r\n /**\r\n * Set currency\r\n */\r\n withCurrency(currency: string): this {\r\n this.data.metadata = { ...this.data.metadata, currency };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set payment method\r\n */\r\n withPaymentMethod(method: PaymentMethod): this {\r\n this.data.metadata = { ...this.data.metadata, paymentMethod: method };\r\n return this;\r\n }\r\n\r\n /**\r\n * Set notes\r\n */\r\n withNotes(notes: string): this {\r\n this.data.metadata = { ...this.data.metadata, notes };\r\n return this;\r\n }\r\n\r\n /**\r\n * Build payroll data\r\n */\r\n build(): PayrollData {\r\n if (!this.data.employeeId || !this.data.organizationId) {\r\n throw new Error('employeeId and organizationId are required');\r\n }\r\n if (!this.data.baseAmount) {\r\n throw new Error('baseAmount is required');\r\n }\r\n\r\n return PayrollFactory.create(this.data as CreatePayrollParams);\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Batch Payroll Factory\r\n// ============================================================================\r\n\r\nexport class BatchPayrollFactory {\r\n /**\r\n * Create payroll records for multiple employees\r\n */\r\n static createBatch(\r\n employees: Array<{\r\n _id: ObjectIdLike;\r\n organizationId: ObjectIdLike;\r\n compensation: Compensation;\r\n }>,\r\n params: { month: number; year: number; organizationId?: ObjectIdLike }\r\n ): PayrollData[] {\r\n return employees.map((employee) =>\r\n PayrollFactory.create({\r\n employeeId: employee._id,\r\n organizationId: params.organizationId || employee.organizationId,\r\n baseAmount: employee.compensation.baseAmount,\r\n allowances: employee.compensation.allowances || [],\r\n deductions: employee.compensation.deductions || [],\r\n period: { month: params.month, year: params.year },\r\n metadata: { currency: employee.compensation.currency },\r\n })\r\n );\r\n }\r\n\r\n /**\r\n * Calculate total payroll amounts\r\n */\r\n static calculateTotalPayroll(payrolls: Array<{ breakdown: PayrollBreakdown }>): {\r\n count: number;\r\n totalGross: number;\r\n totalNet: number;\r\n totalAllowances: number;\r\n totalDeductions: number;\r\n } {\r\n return payrolls.reduce(\r\n (totals, payroll) => ({\r\n count: totals.count + 1,\r\n totalGross: totals.totalGross + payroll.breakdown.grossSalary,\r\n totalNet: totals.totalNet + payroll.breakdown.netSalary,\r\n totalAllowances: totals.totalAllowances + sumAllowances(payroll.breakdown.allowances),\r\n totalDeductions: totals.totalDeductions + sumDeductions(payroll.breakdown.deductions),\r\n }),\r\n { count: 0, totalGross: 0, totalNet: 0, totalAllowances: 0, totalDeductions: 0 }\r\n );\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Factory Function\r\n// ============================================================================\r\n\r\n/**\r\n * Create new payroll builder\r\n */\r\nexport function createPayroll(): PayrollBuilder {\r\n return new PayrollBuilder();\r\n}\r\n\r\n// ============================================================================\r\n// Default Export\r\n// ============================================================================\r\n\r\nexport default {\r\n PayrollFactory,\r\n PayrollBuilder,\r\n BatchPayrollFactory,\r\n createPayroll,\r\n};\r\n\r\n","/**\r\n * @classytic/payroll - Payroll Service\r\n *\r\n * High-level payroll operations with dependency injection\r\n */\r\n\r\nimport type { Model, ClientSession } from 'mongoose';\r\nimport type {\r\n ObjectIdLike,\r\n PayrollRecordDocument,\r\n EmployeeDocument,\r\n PayrollStatus,\r\n PaymentMethod,\r\n} from '../types.js';\r\nimport {\r\n PayrollFactory,\r\n BatchPayrollFactory,\r\n type PayrollData,\r\n} from '../factories/payroll.factory.js';\r\nimport { payroll as payrollQuery, toObjectId } from '../utils/query-builders.js';\r\nimport { getCurrentPeriod } from '../utils/date.js';\r\nimport { canReceiveSalary } from '../utils/validation.js';\r\nimport { logger } from '../utils/logger.js';\r\nimport type { EmployeeService } from './employee.service.js';\r\n\r\n// ============================================================================\r\n// Payroll Service\r\n// ============================================================================\r\n\r\nexport class PayrollService {\r\n constructor(\r\n private readonly PayrollModel: Model<PayrollRecordDocument>,\r\n private readonly employeeService: EmployeeService\r\n ) {}\r\n\r\n /**\r\n * Find payroll by ID\r\n */\r\n async findById(\r\n payrollId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument | null> {\r\n let query = this.PayrollModel.findById(toObjectId(payrollId));\r\n \r\n if (options.session) {\r\n query = query.session(options.session);\r\n }\r\n \r\n return query.exec();\r\n }\r\n\r\n /**\r\n * Find payrolls by employee\r\n */\r\n async findByEmployee(\r\n employeeId: ObjectIdLike,\r\n organizationId: ObjectIdLike,\r\n options: { session?: ClientSession; limit?: number } = {}\r\n ): Promise<PayrollRecordDocument[]> {\r\n const query = payrollQuery()\r\n .forEmployee(employeeId)\r\n .forOrganization(organizationId)\r\n .build();\r\n\r\n let mongooseQuery = this.PayrollModel.find(query)\r\n .sort({ 'period.year': -1, 'period.month': -1 })\r\n .limit(options.limit || 12);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n return mongooseQuery.exec();\r\n }\r\n\r\n /**\r\n * Find payrolls for a period\r\n */\r\n async findForPeriod(\r\n organizationId: ObjectIdLike,\r\n month: number,\r\n year: number,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument[]> {\r\n const query = payrollQuery()\r\n .forOrganization(organizationId)\r\n .forPeriod(month, year)\r\n .build();\r\n\r\n let mongooseQuery = this.PayrollModel.find(query);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n return mongooseQuery.exec();\r\n }\r\n\r\n /**\r\n * Find pending payrolls\r\n */\r\n async findPending(\r\n organizationId: ObjectIdLike,\r\n month: number,\r\n year: number,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument[]> {\r\n const query = payrollQuery()\r\n .forOrganization(organizationId)\r\n .forPeriod(month, year)\r\n .pending()\r\n .build();\r\n\r\n let mongooseQuery = this.PayrollModel.find(query);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n return mongooseQuery.exec();\r\n }\r\n\r\n /**\r\n * Find payroll by employee and period\r\n */\r\n async findByEmployeeAndPeriod(\r\n employeeId: ObjectIdLike,\r\n organizationId: ObjectIdLike,\r\n month: number,\r\n year: number,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument | null> {\r\n const query = payrollQuery()\r\n .forEmployee(employeeId)\r\n .forOrganization(organizationId)\r\n .forPeriod(month, year)\r\n .build();\r\n\r\n let mongooseQuery = this.PayrollModel.findOne(query);\r\n \r\n if (options.session) {\r\n mongooseQuery = mongooseQuery.session(options.session);\r\n }\r\n \r\n return mongooseQuery.exec();\r\n }\r\n\r\n /**\r\n * Create payroll record\r\n */\r\n async create(\r\n data: PayrollData,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument> {\r\n const [payroll] = await this.PayrollModel.create([data], {\r\n session: options.session,\r\n });\r\n\r\n logger.info('Payroll record created', {\r\n payrollId: payroll._id.toString(),\r\n employeeId: payroll.employeeId.toString(),\r\n });\r\n\r\n return payroll;\r\n }\r\n\r\n /**\r\n * Generate payroll for employee\r\n */\r\n async generateForEmployee(\r\n employeeId: ObjectIdLike,\r\n organizationId: ObjectIdLike,\r\n month: number,\r\n year: number,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument> {\r\n const employee = await this.employeeService.findById(employeeId, options);\r\n if (!employee) {\r\n throw new Error('Employee not found');\r\n }\r\n\r\n if (!canReceiveSalary(employee)) {\r\n throw new Error('Employee not eligible for payroll');\r\n }\r\n\r\n // Check if payroll already exists\r\n const existing = await this.findByEmployeeAndPeriod(\r\n employeeId,\r\n organizationId,\r\n month,\r\n year,\r\n options\r\n );\r\n if (existing) {\r\n throw new Error('Payroll already exists for this period');\r\n }\r\n\r\n const payrollData = PayrollFactory.create({\r\n employeeId,\r\n organizationId,\r\n baseAmount: employee.compensation.baseAmount,\r\n allowances: employee.compensation.allowances || [],\r\n deductions: employee.compensation.deductions || [],\r\n period: { month, year },\r\n metadata: { currency: employee.compensation.currency },\r\n });\r\n\r\n return this.create(payrollData, options);\r\n }\r\n\r\n /**\r\n * Generate batch payroll\r\n */\r\n async generateBatch(\r\n organizationId: ObjectIdLike,\r\n month: number,\r\n year: number,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<{\r\n success: boolean;\r\n generated: number;\r\n skipped: number;\r\n payrolls: PayrollRecordDocument[];\r\n message: string;\r\n }> {\r\n const employees = await this.employeeService.findEligibleForPayroll(\r\n organizationId,\r\n options\r\n );\r\n\r\n if (employees.length === 0) {\r\n return {\r\n success: true,\r\n generated: 0,\r\n skipped: 0,\r\n payrolls: [],\r\n message: 'No eligible employees',\r\n };\r\n }\r\n\r\n // Get existing payrolls\r\n const existingPayrolls = await this.findForPeriod(\r\n organizationId,\r\n month,\r\n year,\r\n options\r\n );\r\n const existingEmployeeIds = new Set(\r\n existingPayrolls.map((p) => p.employeeId.toString())\r\n );\r\n\r\n // Filter out employees who already have payroll\r\n const eligibleEmployees = employees.filter(\r\n (emp) => !existingEmployeeIds.has(emp._id.toString())\r\n );\r\n\r\n if (eligibleEmployees.length === 0) {\r\n return {\r\n success: true,\r\n generated: 0,\r\n skipped: employees.length,\r\n payrolls: [],\r\n message: 'Payrolls already exist for all employees',\r\n };\r\n }\r\n\r\n const payrollsData = BatchPayrollFactory.createBatch(eligibleEmployees, {\r\n month,\r\n year,\r\n organizationId,\r\n });\r\n\r\n const created = await this.PayrollModel.insertMany(payrollsData, {\r\n session: options.session,\r\n });\r\n\r\n logger.info('Batch payroll generated', {\r\n organizationId: organizationId.toString(),\r\n month,\r\n year,\r\n count: created.length,\r\n });\r\n\r\n return {\r\n success: true,\r\n generated: created.length,\r\n skipped: existingEmployeeIds.size,\r\n payrolls: created as PayrollRecordDocument[],\r\n message: `Generated ${created.length} payrolls`,\r\n };\r\n }\r\n\r\n /**\r\n * Mark payroll as paid\r\n */\r\n async markAsPaid(\r\n payrollId: ObjectIdLike,\r\n paymentDetails: {\r\n paidAt?: Date;\r\n transactionId?: ObjectIdLike;\r\n paymentMethod?: PaymentMethod;\r\n } = {},\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument> {\r\n const payroll = await this.findById(payrollId, options);\r\n if (!payroll) {\r\n throw new Error('Payroll not found');\r\n }\r\n\r\n if (payroll.status === 'paid') {\r\n throw new Error('Payroll already paid');\r\n }\r\n\r\n const payrollObj = payroll.toObject() as {\r\n status: string;\r\n paidAt: Date | null;\r\n processedAt: Date | null;\r\n metadata: Record<string, unknown>;\r\n };\r\n const updatedData = PayrollFactory.markAsPaid(payrollObj, paymentDetails);\r\n\r\n const updated = await this.PayrollModel.findByIdAndUpdate(\r\n payrollId,\r\n updatedData,\r\n { new: true, runValidators: true, session: options.session }\r\n );\r\n\r\n if (!updated) {\r\n throw new Error('Failed to update payroll');\r\n }\r\n\r\n logger.info('Payroll marked as paid', {\r\n payrollId: payrollId.toString(),\r\n });\r\n\r\n return updated;\r\n }\r\n\r\n /**\r\n * Mark payroll as processed\r\n */\r\n async markAsProcessed(\r\n payrollId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument> {\r\n const payroll = await this.findById(payrollId, options);\r\n if (!payroll) {\r\n throw new Error('Payroll not found');\r\n }\r\n\r\n const payrollObj = payroll.toObject() as { status: string; processedAt: Date | null };\r\n const updatedData = PayrollFactory.markAsProcessed(payrollObj);\r\n\r\n const updated = await this.PayrollModel.findByIdAndUpdate(\r\n payrollId,\r\n updatedData,\r\n { new: true, runValidators: true, session: options.session }\r\n );\r\n\r\n if (!updated) {\r\n throw new Error('Failed to update payroll');\r\n }\r\n\r\n return updated;\r\n }\r\n\r\n /**\r\n * Calculate period summary\r\n */\r\n async calculatePeriodSummary(\r\n organizationId: ObjectIdLike,\r\n month: number,\r\n year: number,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<{\r\n period: { month: number; year: number };\r\n count: number;\r\n totalGross: number;\r\n totalNet: number;\r\n totalAllowances: number;\r\n totalDeductions: number;\r\n byStatus: Record<string, number>;\r\n }> {\r\n const payrolls = await this.findForPeriod(organizationId, month, year, options);\r\n const summary = BatchPayrollFactory.calculateTotalPayroll(payrolls);\r\n\r\n return {\r\n period: { month, year },\r\n ...summary,\r\n byStatus: this.groupByStatus(payrolls),\r\n };\r\n }\r\n\r\n /**\r\n * Get employee payroll history\r\n */\r\n async getEmployeePayrollHistory(\r\n employeeId: ObjectIdLike,\r\n organizationId: ObjectIdLike,\r\n limit = 12,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<PayrollRecordDocument[]> {\r\n return this.findByEmployee(employeeId, organizationId, { ...options, limit });\r\n }\r\n\r\n /**\r\n * Get overview stats\r\n */\r\n async getOverviewStats(\r\n organizationId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<{\r\n currentPeriod: { month: number; year: number };\r\n count: number;\r\n totalGross: number;\r\n totalNet: number;\r\n totalAllowances: number;\r\n totalDeductions: number;\r\n byStatus: Record<string, number>;\r\n }> {\r\n const { month, year } = getCurrentPeriod();\r\n const result = await this.calculatePeriodSummary(organizationId, month, year, options);\r\n return {\r\n currentPeriod: result.period,\r\n count: result.count,\r\n totalGross: result.totalGross,\r\n totalNet: result.totalNet,\r\n totalAllowances: result.totalAllowances,\r\n totalDeductions: result.totalDeductions,\r\n byStatus: result.byStatus,\r\n };\r\n }\r\n\r\n /**\r\n * Group payrolls by status\r\n */\r\n private groupByStatus(payrolls: PayrollRecordDocument[]): Record<string, number> {\r\n return payrolls.reduce(\r\n (acc, payroll) => {\r\n acc[payroll.status] = (acc[payroll.status] || 0) + 1;\r\n return acc;\r\n },\r\n {} as Record<string, number>\r\n );\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Factory Function\r\n// ============================================================================\r\n\r\n/**\r\n * Create payroll service instance\r\n */\r\nexport function createPayrollService(\r\n PayrollModel: Model<PayrollRecordDocument>,\r\n employeeService: EmployeeService\r\n): PayrollService {\r\n return new PayrollService(PayrollModel, employeeService);\r\n}\r\n\r\n","/**\r\n * @classytic/payroll - Compensation Factory\r\n *\r\n * Clean compensation structure creation\r\n * Presets for common compensation packages\r\n */\r\n\r\nimport type {\r\n Compensation,\r\n Allowance,\r\n Deduction,\r\n PaymentFrequency,\r\n CompensationBreakdownResult,\r\n} from '../types.js';\r\nimport { calculateGross, calculateNet, applyPercentage } from '../utils/calculation.js';\r\nimport { HRM_CONFIG } from '../config.js';\r\n\r\n// ============================================================================\r\n// Compensation Factory Types\r\n// ============================================================================\r\n\r\nexport interface CreateCompensationParams {\r\n baseAmount: number;\r\n frequency?: PaymentFrequency;\r\n currency?: string;\r\n allowances?: Array<{\r\n type: Allowance['type'];\r\n value: number;\r\n isPercentage?: boolean;\r\n name?: string;\r\n taxable?: boolean;\r\n }>;\r\n deductions?: Array<{\r\n type: Deduction['type'];\r\n value: number;\r\n isPercentage?: boolean;\r\n name?: string;\r\n auto?: boolean;\r\n }>;\r\n effectiveFrom?: Date;\r\n}\r\n\r\n// ============================================================================\r\n// Compensation Factory\r\n// ============================================================================\r\n\r\nexport class CompensationFactory {\r\n /**\r\n * Create compensation object\r\n */\r\n static create(params: CreateCompensationParams): Compensation {\r\n const {\r\n baseAmount,\r\n frequency = 'monthly',\r\n currency = HRM_CONFIG.payroll.defaultCurrency,\r\n allowances = [],\r\n deductions = [],\r\n effectiveFrom = new Date(),\r\n } = params;\r\n\r\n return {\r\n baseAmount,\r\n frequency,\r\n currency,\r\n allowances: allowances.map((a) => this.createAllowance(a, baseAmount)),\r\n deductions: deductions.map((d) => this.createDeduction(d, baseAmount)),\r\n effectiveFrom,\r\n lastModified: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Create allowance\r\n */\r\n static createAllowance(\r\n params: {\r\n type: Allowance['type'];\r\n value: number;\r\n isPercentage?: boolean;\r\n name?: string;\r\n taxable?: boolean;\r\n },\r\n baseAmount?: number\r\n ): Allowance {\r\n const amount = params.isPercentage && baseAmount\r\n ? applyPercentage(baseAmount, params.value)\r\n : params.value;\r\n\r\n return {\r\n type: params.type,\r\n name: params.name || params.type,\r\n amount,\r\n isPercentage: params.isPercentage ?? false,\r\n value: params.isPercentage ? params.value : undefined,\r\n taxable: params.taxable ?? true,\r\n recurring: true,\r\n effectiveFrom: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Create deduction\r\n */\r\n static createDeduction(\r\n params: {\r\n type: Deduction['type'];\r\n value: number;\r\n isPercentage?: boolean;\r\n name?: string;\r\n auto?: boolean;\r\n },\r\n baseAmount?: number\r\n ): Deduction {\r\n const amount = params.isPercentage && baseAmount\r\n ? applyPercentage(baseAmount, params.value)\r\n : params.value;\r\n\r\n return {\r\n type: params.type,\r\n name: params.name || params.type,\r\n amount,\r\n isPercentage: params.isPercentage ?? false,\r\n value: params.isPercentage ? params.value : undefined,\r\n auto: params.auto ?? false,\r\n recurring: true,\r\n effectiveFrom: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Update base amount (immutable)\r\n */\r\n static updateBaseAmount(\r\n compensation: Compensation,\r\n newAmount: number,\r\n effectiveFrom = new Date()\r\n ): Compensation {\r\n return {\r\n ...compensation,\r\n baseAmount: newAmount,\r\n lastModified: effectiveFrom,\r\n };\r\n }\r\n\r\n /**\r\n * Add allowance (immutable)\r\n */\r\n static addAllowance(\r\n compensation: Compensation,\r\n allowance: Parameters<typeof this.createAllowance>[0]\r\n ): Compensation {\r\n return {\r\n ...compensation,\r\n allowances: [\r\n ...compensation.allowances,\r\n this.createAllowance(allowance, compensation.baseAmount),\r\n ],\r\n lastModified: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Remove allowance (immutable)\r\n */\r\n static removeAllowance(\r\n compensation: Compensation,\r\n allowanceType: Allowance['type']\r\n ): Compensation {\r\n return {\r\n ...compensation,\r\n allowances: compensation.allowances.filter((a) => a.type !== allowanceType),\r\n lastModified: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Add deduction (immutable)\r\n */\r\n static addDeduction(\r\n compensation: Compensation,\r\n deduction: Parameters<typeof this.createDeduction>[0]\r\n ): Compensation {\r\n return {\r\n ...compensation,\r\n deductions: [\r\n ...compensation.deductions,\r\n this.createDeduction(deduction, compensation.baseAmount),\r\n ],\r\n lastModified: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Remove deduction (immutable)\r\n */\r\n static removeDeduction(\r\n compensation: Compensation,\r\n deductionType: Deduction['type']\r\n ): Compensation {\r\n return {\r\n ...compensation,\r\n deductions: compensation.deductions.filter((d) => d.type !== deductionType),\r\n lastModified: new Date(),\r\n };\r\n }\r\n\r\n /**\r\n * Calculate compensation breakdown\r\n */\r\n static calculateBreakdown(compensation: Compensation): CompensationBreakdownResult {\r\n const { baseAmount, allowances, deductions } = compensation;\r\n\r\n // Calculate actual amounts for percentage-based items\r\n const calculatedAllowances = allowances.map((a) => ({\r\n ...a,\r\n calculatedAmount: a.isPercentage && a.value !== undefined\r\n ? applyPercentage(baseAmount, a.value)\r\n : a.amount,\r\n }));\r\n\r\n const calculatedDeductions = deductions.map((d) => ({\r\n ...d,\r\n calculatedAmount: d.isPercentage && d.value !== undefined\r\n ? applyPercentage(baseAmount, d.value)\r\n : d.amount,\r\n }));\r\n\r\n const grossAmount = calculateGross(\r\n baseAmount,\r\n calculatedAllowances.map((a) => ({ amount: a.calculatedAmount }))\r\n );\r\n const netAmount = calculateNet(\r\n grossAmount,\r\n calculatedDeductions.map((d) => ({ amount: d.calculatedAmount }))\r\n );\r\n\r\n return {\r\n baseAmount,\r\n allowances: calculatedAllowances,\r\n deductions: calculatedDeductions,\r\n grossAmount,\r\n netAmount: Math.max(0, netAmount),\r\n };\r\n }\r\n\r\n /**\r\n * Apply salary increment (immutable)\r\n */\r\n static applyIncrement(\r\n compensation: Compensation,\r\n params: { percentage?: number; amount?: number; effectiveFrom?: Date }\r\n ): Compensation {\r\n const newBaseAmount = params.amount\r\n ? compensation.baseAmount + params.amount\r\n : compensation.baseAmount * (1 + (params.percentage || 0) / 100);\r\n\r\n return this.updateBaseAmount(\r\n compensation,\r\n Math.round(newBaseAmount),\r\n params.effectiveFrom\r\n );\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Compensation Builder\r\n// ============================================================================\r\n\r\nexport class CompensationBuilder {\r\n private data: CreateCompensationParams = {\r\n baseAmount: 0,\r\n frequency: 'monthly',\r\n currency: HRM_CONFIG.payroll.defaultCurrency,\r\n allowances: [],\r\n deductions: [],\r\n };\r\n\r\n /**\r\n * Set base amount\r\n */\r\n withBase(\r\n amount: number,\r\n frequency: PaymentFrequency = 'monthly',\r\n currency = HRM_CONFIG.payroll.defaultCurrency\r\n ): this {\r\n this.data.baseAmount = amount;\r\n this.data.frequency = frequency;\r\n this.data.currency = currency;\r\n return this;\r\n }\r\n\r\n /**\r\n * Add allowance\r\n */\r\n addAllowance(\r\n type: Allowance['type'],\r\n value: number,\r\n isPercentage = false,\r\n name?: string\r\n ): this {\r\n this.data.allowances = [\r\n ...(this.data.allowances || []),\r\n { type, value, isPercentage, name },\r\n ];\r\n return this;\r\n }\r\n\r\n /**\r\n * Add deduction\r\n */\r\n addDeduction(\r\n type: Deduction['type'],\r\n value: number,\r\n isPercentage = false,\r\n name?: string\r\n ): this {\r\n this.data.deductions = [\r\n ...(this.data.deductions || []),\r\n { type, value, isPercentage, name },\r\n ];\r\n return this;\r\n }\r\n\r\n /**\r\n * Set effective date\r\n */\r\n effectiveFrom(date: Date): this {\r\n this.data.effectiveFrom = date;\r\n return this;\r\n }\r\n\r\n /**\r\n * Build compensation\r\n */\r\n build(): Compensation {\r\n if (!this.data.baseAmount) {\r\n throw new Error('baseAmount is required');\r\n }\r\n return CompensationFactory.create(this.data);\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Compensation Presets\r\n// ============================================================================\r\n\r\nexport const CompensationPresets = {\r\n /**\r\n * Basic compensation (base only)\r\n */\r\n basic(baseAmount: number): Compensation {\r\n return new CompensationBuilder()\r\n .withBase(baseAmount)\r\n .build();\r\n },\r\n\r\n /**\r\n * With house rent allowance\r\n */\r\n withHouseRent(baseAmount: number, rentPercentage = 50): Compensation {\r\n return new CompensationBuilder()\r\n .withBase(baseAmount)\r\n .addAllowance('housing', rentPercentage, true, 'House Rent')\r\n .build();\r\n },\r\n\r\n /**\r\n * With medical allowance\r\n */\r\n withMedical(baseAmount: number, medicalPercentage = 10): Compensation {\r\n return new CompensationBuilder()\r\n .withBase(baseAmount)\r\n .addAllowance('medical', medicalPercentage, true, 'Medical Allowance')\r\n .build();\r\n },\r\n\r\n /**\r\n * Standard package (house rent + medical + transport)\r\n */\r\n standard(baseAmount: number): Compensation {\r\n return new CompensationBuilder()\r\n .withBase(baseAmount)\r\n .addAllowance('housing', 50, true, 'House Rent')\r\n .addAllowance('medical', 10, true, 'Medical Allowance')\r\n .addAllowance('transport', 5, true, 'Transport Allowance')\r\n .build();\r\n },\r\n\r\n /**\r\n * With provident fund\r\n */\r\n withProvidentFund(baseAmount: number, pfPercentage = 10): Compensation {\r\n return new CompensationBuilder()\r\n .withBase(baseAmount)\r\n .addAllowance('housing', 50, true, 'House Rent')\r\n .addAllowance('medical', 10, true, 'Medical Allowance')\r\n .addDeduction('provident_fund', pfPercentage, true, 'Provident Fund')\r\n .build();\r\n },\r\n\r\n /**\r\n * Executive package\r\n */\r\n executive(baseAmount: number): Compensation {\r\n return new CompensationBuilder()\r\n .withBase(baseAmount)\r\n .addAllowance('housing', 60, true, 'House Rent')\r\n .addAllowance('medical', 15, true, 'Medical Allowance')\r\n .addAllowance('transport', 10, true, 'Transport Allowance')\r\n .addAllowance('mobile', 5, true, 'Mobile Allowance')\r\n .addDeduction('provident_fund', 10, true, 'Provident Fund')\r\n .build();\r\n },\r\n};\r\n\r\n// ============================================================================\r\n// Factory Function\r\n// ============================================================================\r\n\r\n/**\r\n * Create new compensation builder\r\n */\r\nexport function createCompensation(): CompensationBuilder {\r\n return new CompensationBuilder();\r\n}\r\n\r\n// ============================================================================\r\n// Default Export\r\n// ============================================================================\r\n\r\nexport default {\r\n CompensationFactory,\r\n CompensationBuilder,\r\n CompensationPresets,\r\n createCompensation,\r\n};\r\n\r\n","/**\r\n * @classytic/payroll - Compensation Service\r\n *\r\n * High-level compensation operations with dependency injection\r\n */\r\n\r\nimport type { Model, ClientSession } from 'mongoose';\r\nimport type {\r\n ObjectIdLike,\r\n EmployeeDocument,\r\n Compensation,\r\n Allowance,\r\n Deduction,\r\n Department,\r\n CompensationBreakdownResult,\r\n} from '../types.js';\r\nimport {\r\n CompensationFactory,\r\n CompensationPresets,\r\n} from '../factories/compensation.factory.js';\r\nimport { toObjectId } from '../utils/query-builders.js';\r\nimport { logger } from '../utils/logger.js';\r\n\r\n// ============================================================================\r\n// Compensation Service\r\n// ============================================================================\r\n\r\nexport class CompensationService {\r\n constructor(private readonly EmployeeModel: Model<EmployeeDocument>) {}\r\n\r\n /**\r\n * Get employee compensation\r\n */\r\n async getEmployeeCompensation(\r\n employeeId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<Compensation> {\r\n let query = this.EmployeeModel.findById(toObjectId(employeeId));\r\n \r\n if (options.session) {\r\n query = query.session(options.session);\r\n }\r\n \r\n const employee = await query.exec();\r\n if (!employee) {\r\n throw new Error('Employee not found');\r\n }\r\n\r\n return employee.compensation;\r\n }\r\n\r\n /**\r\n * Calculate compensation breakdown\r\n */\r\n async calculateBreakdown(\r\n employeeId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<CompensationBreakdownResult> {\r\n const compensation = await this.getEmployeeCompensation(employeeId, options);\r\n return CompensationFactory.calculateBreakdown(compensation);\r\n }\r\n\r\n /**\r\n * Update base amount\r\n */\r\n async updateBaseAmount(\r\n employeeId: ObjectIdLike,\r\n newAmount: number,\r\n effectiveFrom = new Date(),\r\n options: { session?: ClientSession } = {}\r\n ): Promise<CompensationBreakdownResult> {\r\n const employee = await this.findEmployee(employeeId, options);\r\n\r\n const updatedCompensation = CompensationFactory.updateBaseAmount(\r\n employee.compensation,\r\n newAmount,\r\n effectiveFrom\r\n );\r\n\r\n employee.compensation = updatedCompensation;\r\n await employee.save({ session: options.session });\r\n\r\n logger.info('Compensation base amount updated', {\r\n employeeId: employee.employeeId,\r\n newAmount,\r\n });\r\n\r\n return this.calculateBreakdown(employeeId, options);\r\n }\r\n\r\n /**\r\n * Apply salary increment\r\n */\r\n async applyIncrement(\r\n employeeId: ObjectIdLike,\r\n params: { percentage?: number; amount?: number; effectiveFrom?: Date },\r\n options: { session?: ClientSession } = {}\r\n ): Promise<CompensationBreakdownResult> {\r\n const employee = await this.findEmployee(employeeId, options);\r\n const previousAmount = employee.compensation.baseAmount;\r\n\r\n const updatedCompensation = CompensationFactory.applyIncrement(\r\n employee.compensation,\r\n params\r\n );\r\n\r\n employee.compensation = updatedCompensation;\r\n await employee.save({ session: options.session });\r\n\r\n logger.info('Salary increment applied', {\r\n employeeId: employee.employeeId,\r\n previousAmount,\r\n newAmount: updatedCompensation.baseAmount,\r\n percentage: params.percentage,\r\n });\r\n\r\n return this.calculateBreakdown(employeeId, options);\r\n }\r\n\r\n /**\r\n * Add allowance\r\n */\r\n async addAllowance(\r\n employeeId: ObjectIdLike,\r\n allowance: {\r\n type: Allowance['type'];\r\n value: number;\r\n isPercentage?: boolean;\r\n name?: string;\r\n taxable?: boolean;\r\n },\r\n options: { session?: ClientSession } = {}\r\n ): Promise<CompensationBreakdownResult> {\r\n const employee = await this.findEmployee(employeeId, options);\r\n\r\n const updatedCompensation = CompensationFactory.addAllowance(\r\n employee.compensation,\r\n allowance\r\n );\r\n\r\n employee.compensation = updatedCompensation;\r\n await employee.save({ session: options.session });\r\n\r\n logger.info('Allowance added', {\r\n employeeId: employee.employeeId,\r\n type: allowance.type,\r\n value: allowance.value,\r\n });\r\n\r\n return this.calculateBreakdown(employeeId, options);\r\n }\r\n\r\n /**\r\n * Remove allowance\r\n */\r\n async removeAllowance(\r\n employeeId: ObjectIdLike,\r\n allowanceType: Allowance['type'],\r\n options: { session?: ClientSession } = {}\r\n ): Promise<CompensationBreakdownResult> {\r\n const employee = await this.findEmployee(employeeId, options);\r\n\r\n const updatedCompensation = CompensationFactory.removeAllowance(\r\n employee.compensation,\r\n allowanceType\r\n );\r\n\r\n employee.compensation = updatedCompensation;\r\n await employee.save({ session: options.session });\r\n\r\n logger.info('Allowance removed', {\r\n employeeId: employee.employeeId,\r\n type: allowanceType,\r\n });\r\n\r\n return this.calculateBreakdown(employeeId, options);\r\n }\r\n\r\n /**\r\n * Add deduction\r\n */\r\n async addDeduction(\r\n employeeId: ObjectIdLike,\r\n deduction: {\r\n type: Deduction['type'];\r\n value: number;\r\n isPercentage?: boolean;\r\n name?: string;\r\n auto?: boolean;\r\n },\r\n options: { session?: ClientSession } = {}\r\n ): Promise<CompensationBreakdownResult> {\r\n const employee = await this.findEmployee(employeeId, options);\r\n\r\n const updatedCompensation = CompensationFactory.addDeduction(\r\n employee.compensation,\r\n deduction\r\n );\r\n\r\n employee.compensation = updatedCompensation;\r\n await employee.save({ session: options.session });\r\n\r\n logger.info('Deduction added', {\r\n employeeId: employee.employeeId,\r\n type: deduction.type,\r\n value: deduction.value,\r\n });\r\n\r\n return this.calculateBreakdown(employeeId, options);\r\n }\r\n\r\n /**\r\n * Remove deduction\r\n */\r\n async removeDeduction(\r\n employeeId: ObjectIdLike,\r\n deductionType: Deduction['type'],\r\n options: { session?: ClientSession } = {}\r\n ): Promise<CompensationBreakdownResult> {\r\n const employee = await this.findEmployee(employeeId, options);\r\n\r\n const updatedCompensation = CompensationFactory.removeDeduction(\r\n employee.compensation,\r\n deductionType\r\n );\r\n\r\n employee.compensation = updatedCompensation;\r\n await employee.save({ session: options.session });\r\n\r\n logger.info('Deduction removed', {\r\n employeeId: employee.employeeId,\r\n type: deductionType,\r\n });\r\n\r\n return this.calculateBreakdown(employeeId, options);\r\n }\r\n\r\n /**\r\n * Set standard compensation\r\n */\r\n async setStandardCompensation(\r\n employeeId: ObjectIdLike,\r\n baseAmount: number,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<CompensationBreakdownResult> {\r\n const employee = await this.findEmployee(employeeId, options);\r\n\r\n employee.compensation = CompensationPresets.standard(baseAmount);\r\n await employee.save({ session: options.session });\r\n\r\n logger.info('Standard compensation set', {\r\n employeeId: employee.employeeId,\r\n baseAmount,\r\n });\r\n\r\n return this.calculateBreakdown(employeeId, options);\r\n }\r\n\r\n /**\r\n * Compare compensation between two employees\r\n */\r\n async compareCompensation(\r\n employeeId1: ObjectIdLike,\r\n employeeId2: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<{\r\n employee1: CompensationBreakdownResult;\r\n employee2: CompensationBreakdownResult;\r\n difference: { base: number; gross: number; net: number };\r\n ratio: { base: number; gross: number; net: number };\r\n }> {\r\n const breakdown1 = await this.calculateBreakdown(employeeId1, options);\r\n const breakdown2 = await this.calculateBreakdown(employeeId2, options);\r\n\r\n return {\r\n employee1: breakdown1,\r\n employee2: breakdown2,\r\n difference: {\r\n base: breakdown2.baseAmount - breakdown1.baseAmount,\r\n gross: breakdown2.grossAmount - breakdown1.grossAmount,\r\n net: breakdown2.netAmount - breakdown1.netAmount,\r\n },\r\n ratio: {\r\n base: breakdown1.baseAmount > 0 ? breakdown2.baseAmount / breakdown1.baseAmount : 0,\r\n gross: breakdown1.grossAmount > 0 ? breakdown2.grossAmount / breakdown1.grossAmount : 0,\r\n net: breakdown1.netAmount > 0 ? breakdown2.netAmount / breakdown1.netAmount : 0,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Get department compensation stats\r\n */\r\n async getDepartmentCompensationStats(\r\n organizationId: ObjectIdLike,\r\n department: Department,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<{\r\n department: string;\r\n employeeCount: number;\r\n totalBase: number;\r\n totalGross: number;\r\n totalNet: number;\r\n averageBase: number;\r\n averageGross: number;\r\n averageNet: number;\r\n }> {\r\n let query = this.EmployeeModel.find({\r\n organizationId: toObjectId(organizationId),\r\n department,\r\n status: { $in: ['active', 'on_leave'] },\r\n });\r\n\r\n if (options.session) {\r\n query = query.session(options.session);\r\n }\r\n\r\n const employees = await query.exec();\r\n\r\n const breakdowns = employees.map((emp) =>\r\n CompensationFactory.calculateBreakdown(emp.compensation)\r\n );\r\n\r\n const totals = breakdowns.reduce(\r\n (acc, breakdown) => ({\r\n totalBase: acc.totalBase + breakdown.baseAmount,\r\n totalGross: acc.totalGross + breakdown.grossAmount,\r\n totalNet: acc.totalNet + breakdown.netAmount,\r\n }),\r\n { totalBase: 0, totalGross: 0, totalNet: 0 }\r\n );\r\n\r\n const count = employees.length || 1;\r\n\r\n return {\r\n department,\r\n employeeCount: employees.length,\r\n ...totals,\r\n averageBase: Math.round(totals.totalBase / count),\r\n averageGross: Math.round(totals.totalGross / count),\r\n averageNet: Math.round(totals.totalNet / count),\r\n };\r\n }\r\n\r\n /**\r\n * Get organization compensation stats\r\n */\r\n async getOrganizationCompensationStats(\r\n organizationId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<{\r\n employeeCount: number;\r\n totalBase: number;\r\n totalGross: number;\r\n totalNet: number;\r\n averageBase: number;\r\n averageGross: number;\r\n averageNet: number;\r\n byDepartment: Record<string, { count: number; totalNet: number }>;\r\n }> {\r\n let query = this.EmployeeModel.find({\r\n organizationId: toObjectId(organizationId),\r\n status: { $in: ['active', 'on_leave'] },\r\n });\r\n\r\n if (options.session) {\r\n query = query.session(options.session);\r\n }\r\n\r\n const employees = await query.exec();\r\n\r\n const breakdowns = employees.map((emp) =>\r\n CompensationFactory.calculateBreakdown(emp.compensation)\r\n );\r\n\r\n const totals = breakdowns.reduce(\r\n (acc, breakdown) => ({\r\n totalBase: acc.totalBase + breakdown.baseAmount,\r\n totalGross: acc.totalGross + breakdown.grossAmount,\r\n totalNet: acc.totalNet + breakdown.netAmount,\r\n }),\r\n { totalBase: 0, totalGross: 0, totalNet: 0 }\r\n );\r\n\r\n const byDepartment: Record<string, { count: number; totalNet: number }> = {};\r\n employees.forEach((emp, i) => {\r\n const dept = emp.department || 'unassigned';\r\n if (!byDepartment[dept]) {\r\n byDepartment[dept] = { count: 0, totalNet: 0 };\r\n }\r\n byDepartment[dept].count++;\r\n byDepartment[dept].totalNet += breakdowns[i].netAmount;\r\n });\r\n\r\n const count = employees.length || 1;\r\n\r\n return {\r\n employeeCount: employees.length,\r\n ...totals,\r\n averageBase: Math.round(totals.totalBase / count),\r\n averageGross: Math.round(totals.totalGross / count),\r\n averageNet: Math.round(totals.totalNet / count),\r\n byDepartment,\r\n };\r\n }\r\n\r\n /**\r\n * Find employee helper\r\n */\r\n private async findEmployee(\r\n employeeId: ObjectIdLike,\r\n options: { session?: ClientSession } = {}\r\n ): Promise<EmployeeDocument> {\r\n let query = this.EmployeeModel.findById(toObjectId(employeeId));\r\n \r\n if (options.session) {\r\n query = query.session(options.session);\r\n }\r\n \r\n const employee = await query.exec();\r\n if (!employee) {\r\n throw new Error('Employee not found');\r\n }\r\n return employee;\r\n }\r\n}\r\n\r\n// ============================================================================\r\n// Factory Function\r\n// ============================================================================\r\n\r\n/**\r\n * Create compensation service instance\r\n */\r\nexport function createCompensationService(\r\n EmployeeModel: Model<EmployeeDocument>\r\n): CompensationService {\r\n return new CompensationService(EmployeeModel);\r\n}\r\n\r\n"]}