All files / src/domains/hr/payroll/services payroll.service.ts

0% Statements 0/404
0% Branches 0/420
0% Functions 0/115
0% Lines 0/345

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
// ================================================================
// PAYROLL SERVICES — Configuration, Components, Structures,
// Compensation, Calendars, Inputs, Runs, Loans, Advances,
// Reimbursements, Benefits, Payslips, Payments, Accounting,
// Off-Cycle, F&F, Import/Export, Dashboard
// ================================================================
import {
  Injectable,
  BadRequestException,
  NotFoundException,
  ForbiddenException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import {
  PayrollConfiguration,
  PayrollConfigurationVersion,
  PayrollCountryConfiguration,
  SalaryComponent,
  SalaryComponentVersion,
  SalaryComponentDependency,
  SalaryComponentSlab,
  SalaryComponentFormula,
  PayrollFormulaDefinition,
  PayrollFormulaTestCase,
  SalaryStructure,
  SalaryStructureVersion,
  SalaryStructureComponent,
  SalaryStructureAssignmentRule,
  EmployeeCompensation,
  EmployeeCompensationVersion,
  EmployeeSalaryComponent,
  CompensationRevision,
  CompensationHistory,
  CompensationApproval,
  PayrollCalendar,
  PayrollPeriod,
  PayrollGroup,
  PayrollGroupAssignment,
  PayrollCutoffConfiguration,
  PayrollInput,
  PayrollInputBatch,
  PayrollInputValidation,
  PayrollAttendanceInput,
  PayrollLeaveInput,
  PayrollOvertimeInput,
  PayrollRun,
  PayrollRunEmployee,
  PayrollRunStage,
  PayrollRunApproval,
  PayrollRunHistory,
  PayrollCalculationResult,
  PayrollCalculationComponent,
  PayrollRunValidation,
  PayrollRunException,
  BonusPlan,
  BonusAward,
  IncentivePlan,
  IncentiveEarning,
  LoanType,
  EmployeeLoan,
  LoanApproval,
  LoanRepaymentSchedule,
  LoanRepayment,
  LoanAdjustment,
  LoanForeclosure,
  SalaryAdvancePolicy,
  SalaryAdvanceRequest,
  SalaryAdvanceApproval,
  SalaryAdvanceRecoverySchedule,
  ReimbursementType,
  ReimbursementPolicy,
  ReimbursementClaim,
  ReimbursementItem,
  ReimbursementApproval,
  ReimbursementSettlement,
  BenefitPlan,
  EmployeeBenefitEnrollment,
  FlexibleBenefitPlan,
  FlexibleBenefitAllocation,
  FlexibleBenefitClaim,
  PayrollLock,
  PayrollReopenRequest,
  PayrollCorrectionBatch,
  Payslip,
  PayslipTemplate,
  PayslipDeliveryLog,
  PayrollPaymentBatch,
  PayrollPaymentInstruction,
  PayrollBankFile,
  PayrollPaymentReconciliation,
  PayrollAccountingMapping,
  PayrollJournalExport,
  PayrollCostAllocation,
  OffCyclePayrollRun,
  FullAndFinalSettlement,
  SettlementComponent,
  SettlementRecovery,
  SettlementApproval,
  PayrollImportJob,
  PayrollImportRow,
  PayrollExportJob,
} from '../schemas';
import { PayrollFormulaEngine } from '../engines/payroll-formula.engine';
import { PayrollCalculationEngine } from '../engines/payroll-calculation.engine';
 
// ── 1. Configuration Service ──
@Injectable()
export class PayrollConfigurationService {
  constructor(
    @InjectModel(PayrollConfiguration.name)
    private readonly model: Model<PayrollConfiguration>,
    @InjectModel(PayrollConfigurationVersion.name)
    private readonly versionModel: Model<PayrollConfigurationVersion>,
    @InjectModel(PayrollCountryConfiguration.name)
    private readonly countryModel: Model<PayrollCountryConfiguration>,
  ) {}
 
  async get(tenantId: string) {
    return this.model.findOne({ tenantId }).lean();
  }
 
  async upsert(tenantId: string, data: Partial<PayrollConfiguration>) {
    const existing = await this.model.findOne({ tenantId });
    if (existing) {
      if (existing.status === 'published')
        throw new BadRequestException(
          'Published configuration is immutable. Create a new version.',
        );
      return this.model
        .findOneAndUpdate({ tenantId }, { $set: data }, { new: true })
        .lean();
    }
    return this.model.create({ ...data, tenantId });
  }
 
  async publish(tenantId: string, userId: string) {
    const config = await this.model.findOne({ tenantId });
    if (!config) throw new NotFoundException('Configuration not found');
    const version = config.version + 1;
    await this.versionModel.create({
      tenantId,
      version,
      snapshot: config.toObject(),
      publishedBy: new Types.ObjectId(userId),
    });
    return this.model
      .findOneAndUpdate(
        { tenantId },
        { $set: { status: 'published', version } },
        { new: true },
      )
      .lean();
  }
 
  async getVersions(tenantId: string) {
    return this.versionModel.find({ tenantId }).sort({ version: -1 }).lean();
  }
 
  async getCountryConfigs() {
    return this.countryModel.find({ isActive: true }).lean();
  }
}
 
// ── 2. Salary Component Service ──
@Injectable()
export class SalaryComponentService {
  constructor(
    @InjectModel(SalaryComponent.name)
    private readonly model: Model<SalaryComponent>,
    @InjectModel(SalaryComponentVersion.name)
    private readonly versionModel: Model<SalaryComponentVersion>,
    @InjectModel(SalaryComponentDependency.name)
    private readonly depModel: Model<SalaryComponentDependency>,
    @InjectModel(SalaryComponentSlab.name)
    private readonly slabModel: Model<SalaryComponentSlab>,
    @InjectModel(SalaryComponentFormula.name)
    private readonly formulaModel: Model<SalaryComponentFormula>,
    private readonly formulaEngine: PayrollFormulaEngine,
  ) {}
 
  async list(tenantId: string, filters: Record<string, unknown> = {}) {
    return this.model
      .find({ tenantId, ...filters })
      .sort({ priority: 1 })
      .lean();
  }
 
  async getById(tenantId: string, id: string) {
    const comp = await this.model.findOne({ _id: id, tenantId }).lean();
    if (!comp) throw new NotFoundException('Component not found');
    return comp;
  }
 
  async create(tenantId: string, data: Partial<SalaryComponent>) {
    const exists = await this.model.findOne({
      tenantId,
      componentCode: data.componentCode,
    });
    if (exists)
      throw new BadRequestException(
        `Component code ${data.componentCode} already exists`,
      );
    if (data.formula) {
      const validation = this.formulaEngine.validate(data.formula);
      if (!validation.valid)
        throw new BadRequestException(
          `Formula errors: ${validation.errors.join(', ')}`,
        );
    }
    return this.model.create({ ...data, tenantId });
  }
 
  async update(tenantId: string, id: string, data: Partial<SalaryComponent>) {
    const comp = await this.model.findOne({ _id: id, tenantId });
    if (!comp) throw new NotFoundException('Component not found');
    if (data.formula) {
      const validation = this.formulaEngine.validate(data.formula);
      if (!validation.valid)
        throw new BadRequestException(
          `Formula errors: ${validation.errors.join(', ')}`,
        );
    }
    return this.model
      .findOneAndUpdate({ _id: id, tenantId }, { $set: data }, { new: true })
      .lean();
  }
 
  async publish(tenantId: string, id: string, userId: string) {
    const comp = await this.model.findOne({ _id: id, tenantId });
    if (!comp) throw new NotFoundException('Component not found');
    const version = comp.version + 1;
    await this.versionModel.create({
      tenantId,
      componentId: id,
      version,
      snapshot: comp.toObject(),
      publishedBy: new Types.ObjectId(userId),
    });
    return this.model
      .findOneAndUpdate(
        { _id: id },
        { $set: { status: 'active', version } },
        { new: true },
      )
      .lean();
  }
 
  async clone(tenantId: string, id: string) {
    const comp = await this.model.findOne({ _id: id, tenantId }).lean();
    if (!comp) throw new NotFoundException('Component not found');
    const { _id, componentCode, ...rest } = comp;
    return this.model.create({
      ...rest,
      componentCode: `${componentCode}_COPY`,
      status: 'draft',
      version: 1,
    });
  }
 
  async archive(tenantId: string, id: string) {
    return this.model
      .findOneAndUpdate(
        { _id: id, tenantId },
        { $set: { status: 'archived' } },
        { new: true },
      )
      .lean();
  }
 
  async getSlabs(tenantId: string, componentId: string) {
    return this.slabModel
      .find({ tenantId, componentId })
      .sort({ priority: 1 })
      .lean();
  }
}
 
// ── 3. Formula Service ──
@Injectable()
export class PayrollFormulaService {
  constructor(
    @InjectModel(PayrollFormulaDefinition.name)
    private readonly model: Model<PayrollFormulaDefinition>,
    @InjectModel(PayrollFormulaTestCase.name)
    private readonly testModel: Model<PayrollFormulaTestCase>,
    private readonly formulaEngine: PayrollFormulaEngine,
  ) {}
 
  async validate(expression: string) {
    return this.formulaEngine.validate(expression);
  }
 
  async preview(expression: string, variables: Record<string, number>) {
    return this.formulaEngine.preview(expression, variables);
  }
 
  async runTestCase(tenantId: string, testCaseId: string) {
    const tc = await this.testModel.findOne({ _id: testCaseId, tenantId });
    if (!tc) throw new NotFoundException('Test case not found');
    const formula = await this.model.findOne({ _id: tc.formulaId, tenantId });
    if (!formula) throw new NotFoundException('Formula not found');
    const result = this.formulaEngine.preview(
      formula.expression,
      tc.inputVariables,
    );
    const passed = result.error
      ? false
      : Math.abs(result.result - tc.expectedOutput) < 0.01;
    await this.testModel.updateOne(
      { _id: testCaseId },
      {
        $set: {
          actualOutput: result.result,
          result: passed ? 'passed' : 'failed',
        },
      },
    );
    return {
      passed,
      expected: tc.expectedOutput,
      actual: result.result,
      error: result.error,
    };
  }
}
 
// ── 4. Salary Structure Service ──
@Injectable()
export class SalaryStructureService {
  constructor(
    @InjectModel(SalaryStructure.name)
    private readonly model: Model<SalaryStructure>,
    @InjectModel(SalaryStructureVersion.name)
    private readonly versionModel: Model<SalaryStructureVersion>,
    @InjectModel(SalaryStructureComponent.name)
    private readonly compModel: Model<SalaryStructureComponent>,
    @InjectModel(SalaryStructureAssignmentRule.name)
    private readonly ruleModel: Model<SalaryStructureAssignmentRule>,
  ) {}
 
  async list(tenantId: string) {
    return this.model.find({ tenantId }).sort({ structureName: 1 }).lean();
  }
  async getById(tenantId: string, id: string): Promise<any> {
    const s = await this.model.findOne({ _id: id, tenantId }).lean();
    if (!s) throw new NotFoundException('Structure not found');
    const components = await this.compModel
      .find({ tenantId, structureId: id })
      .lean();
    return { ...s, components };
  }
  async create(tenantId: string, data: Partial<SalaryStructure>) {
    return this.model.create({ ...data, tenantId });
  }
  async update(tenantId: string, id: string, data: Partial<SalaryStructure>) {
    return this.model
      .findOneAndUpdate({ _id: id, tenantId }, { $set: data }, { new: true })
      .lean();
  }
  async publish(tenantId: string, id: string, userId: string) {
    const s = await this.model.findOne({ _id: id, tenantId });
    if (!s) throw new NotFoundException('Structure not found');
    const version = s.version + 1;
    await this.versionModel.create({
      tenantId,
      structureId: id,
      version,
      snapshot: s.toObject(),
      publishedBy: new Types.ObjectId(userId),
    });
    return this.model
      .findOneAndUpdate(
        { _id: id },
        { $set: { status: 'published', version } },
        { new: true },
      )
      .lean();
  }
  async clone(tenantId: string, id: string) {
    const s = await this.model.findOne({ _id: id, tenantId }).lean();
    if (!s) throw new NotFoundException('Structure not found');
    const { _id, structureCode, ...rest } = s;
    return this.model.create({
      ...rest,
      structureCode: `${structureCode}_COPY`,
      status: 'draft',
      version: 1,
    });
  }
  async assign(
    tenantId: string,
    id: string,
    data: Partial<SalaryStructureAssignmentRule>,
  ) {
    return this.ruleModel.create({ ...data, tenantId, structureId: id });
  }
}
 
// ── 5. Employee Compensation Service ──
@Injectable()
export class EmployeeCompensationService {
  constructor(
    @InjectModel(EmployeeCompensation.name)
    private readonly model: Model<EmployeeCompensation>,
    @InjectModel(EmployeeCompensationVersion.name)
    private readonly versionModel: Model<EmployeeCompensationVersion>,
    @InjectModel(EmployeeSalaryComponent.name)
    private readonly empCompModel: Model<EmployeeSalaryComponent>,
    @InjectModel(CompensationRevision.name)
    private readonly revisionModel: Model<CompensationRevision>,
    @InjectModel(CompensationHistory.name)
    private readonly historyModel: Model<CompensationHistory>,
    @InjectModel(CompensationApproval.name)
    private readonly approvalModel: Model<CompensationApproval>,
  ) {}
 
  async getByEmployee(tenantId: string, employeeId: string): Promise<any> {
    const comp = await this.model
      .findOne({ tenantId, employeeId, status: 'active' })
      .sort({ effectiveFrom: -1 })
      .lean();
    if (!comp) throw new NotFoundException('No active compensation found');
    const components = await this.empCompModel
      .find({ tenantId, compensationId: comp._id })
      .lean();
    return { ...comp, components };
  }
 
  async create(
    tenantId: string,
    employeeId: string,
    data: Partial<EmployeeCompensation>,
    userId: string,
  ) {
    // Supersede previous active compensation
    await this.model.updateMany(
      { tenantId, employeeId, status: 'active' },
      { $set: { status: 'superseded' } },
    );
    const comp = await this.model.create({
      ...data,
      tenantId,
      employeeId,
      createdBy: new Types.ObjectId(userId),
    });
    await this.historyModel.create({
      tenantId,
      employeeId,
      compensationId: comp._id,
      action: 'created',
      newValues: data,
      performedBy: new Types.ObjectId(userId),
    });
    return comp;
  }
 
  async createRevision(
    tenantId: string,
    employeeId: string,
    data: Partial<CompensationRevision>,
    userId: string,
  ) {
    const current = await this.model
      .findOne({ tenantId, employeeId, status: 'active' })
      .lean();
    return this.revisionModel.create({
      ...data,
      tenantId,
      employeeId,
      previousCompensationId: current?._id,
      previousCTC: current?.ctc ?? 0,
      createdBy: new Types.ObjectId(userId),
    });
  }
 
  async approveRevision(tenantId: string, revisionId: string, userId: string) {
    const rev = await this.revisionModel.findOne({ _id: revisionId, tenantId });
    if (!rev) throw new NotFoundException('Revision not found');
    await this.revisionModel.updateOne(
      { _id: revisionId },
      {
        $set: {
          approvalStatus: 'approved',
          approvedBy: new Types.ObjectId(userId),
        },
      },
    );
    return { success: true };
  }
 
  async getHistory(tenantId: string, employeeId: string) {
    return this.revisionModel
      .find({ tenantId, employeeId })
      .sort({ effectiveFrom: -1 })
      .lean();
  }
}
 
// ── 6. Payroll Calendar & Group Service ──
@Injectable()
export class PayrollCalendarService {
  constructor(
    @InjectModel(PayrollCalendar.name)
    private readonly calendarModel: Model<PayrollCalendar>,
    @InjectModel(PayrollPeriod.name)
    private readonly periodModel: Model<PayrollPeriod>,
    @InjectModel(PayrollGroup.name)
    private readonly groupModel: Model<PayrollGroup>,
    @InjectModel(PayrollGroupAssignment.name)
    private readonly assignmentModel: Model<PayrollGroupAssignment>,
  ) {}
 
  async listCalendars(tenantId: string) {
    return this.calendarModel.find({ tenantId }).lean();
  }
  async createCalendar(tenantId: string, data: Partial<PayrollCalendar>) {
    return this.calendarModel.create({ ...data, tenantId });
  }
  async listGroups(tenantId: string) {
    return this.groupModel.find({ tenantId }).lean();
  }
  async createGroup(tenantId: string, data: Partial<PayrollGroup>) {
    return this.groupModel.create({ ...data, tenantId });
  }
  async assignGroup(
    tenantId: string,
    groupId: string,
    data: Partial<PayrollGroupAssignment>,
  ) {
    return this.assignmentModel.create({ ...data, tenantId, groupId });
  }
  async listPeriods(tenantId: string, filters: Record<string, unknown> = {}) {
    return this.periodModel
      .find({ tenantId, ...filters })
      .sort({ startDate: -1 })
      .lean();
  }
  async openPeriod(tenantId: string, periodId: string) {
    return this.periodModel
      .findOneAndUpdate(
        { _id: periodId, tenantId },
        { $set: { status: 'open' } },
        { new: true },
      )
      .lean();
  }
  async closePeriod(tenantId: string, periodId: string) {
    return this.periodModel
      .findOneAndUpdate(
        { _id: periodId, tenantId },
        { $set: { status: 'closed' } },
        { new: true },
      )
      .lean();
  }
}
 
// ── 7. Payroll Input Service ──
@Injectable()
export class PayrollInputService {
  constructor(
    @InjectModel(PayrollInput.name) private readonly model: Model<PayrollInput>,
    @InjectModel(PayrollInputBatch.name)
    private readonly batchModel: Model<PayrollInputBatch>,
    @InjectModel(PayrollInputValidation.name)
    private readonly validationModel: Model<PayrollInputValidation>,
    @InjectModel(PayrollAttendanceInput.name)
    private readonly attModel: Model<PayrollAttendanceInput>,
    @InjectModel(PayrollLeaveInput.name)
    private readonly leaveModel: Model<PayrollLeaveInput>,
  ) {}
 
  async list(tenantId: string, periodId: string) {
    return this.model.find({ tenantId, periodId }).lean();
  }
  async create(tenantId: string, data: Partial<PayrollInput>) {
    return this.model.create({ ...data, tenantId });
  }
  async createBulk(
    tenantId: string,
    inputs: Partial<PayrollInput>[],
  ): Promise<any> {
    return this.model.insertMany(inputs.map((i) => ({ ...i, tenantId })));
  }
  async validate(tenantId: string, periodId: string) {
    const inputs = await this.model.find({
      tenantId,
      periodId,
      status: 'pending',
    });
    let valid = 0;
    let errors = 0;
    for (const input of inputs) {
      if (input.amount < 0) {
        await this.validationModel.create({
          tenantId,
          inputId: input._id,
          severity: 'error',
          message: 'Negative amount',
          field: 'amount',
        });
        await this.model.updateOne(
          { _id: input._id },
          { $set: { status: 'rejected' } },
        );
        errors++;
      } else {
        await this.model.updateOne(
          { _id: input._id },
          { $set: { status: 'validated' } },
        );
        valid++;
      }
    }
    return { valid, errors };
  }
  async approve(tenantId: string, inputId: string) {
    return this.model
      .findOneAndUpdate(
        { _id: inputId, tenantId },
        { $set: { status: 'approved' } },
        { new: true },
      )
      .lean();
  }
}
 
// ── 8. Payroll Run Service ──
@Injectable()
export class PayrollRunService {
  constructor(
    @InjectModel(PayrollRun.name) private readonly model: Model<PayrollRun>,
    @InjectModel(PayrollRunEmployee.name)
    private readonly empModel: Model<PayrollRunEmployee>,
    @InjectModel(PayrollRunStage.name)
    private readonly stageModel: Model<PayrollRunStage>,
    @InjectModel(PayrollRunApproval.name)
    private readonly approvalModel: Model<PayrollRunApproval>,
    @InjectModel(PayrollRunHistory.name)
    private readonly historyModel: Model<PayrollRunHistory>,
    @InjectModel(PayrollRunValidation.name)
    private readonly validationModel: Model<PayrollRunValidation>,
    @InjectModel(PayrollRunException.name)
    private readonly exceptionModel: Model<PayrollRunException>,
    @InjectModel(PayrollCalculationResult.name)
    private readonly resultModel: Model<PayrollCalculationResult>,
    @InjectModel(PayrollCalculationComponent.name)
    private readonly calcCompModel: Model<PayrollCalculationComponent>,
    @InjectModel(PayrollLock.name)
    private readonly lockModel: Model<PayrollLock>,
    private readonly calculationEngine: PayrollCalculationEngine,
  ) {}
 
  async list(tenantId: string) {
    return this.model.find({ tenantId }).sort({ createdAt: -1 }).lean();
  }
  async getById(tenantId: string, id: string) {
    const run = await this.model.findOne({ _id: id, tenantId }).lean();
    if (!run) throw new NotFoundException('Payroll run not found');
    return run;
  }
 
  async create(tenantId: string, data: Partial<PayrollRun>, userId: string) {
    return this.model.create({
      ...data,
      tenantId,
      createdBy: new Types.ObjectId(userId),
    });
  }
 
  async calculate(tenantId: string, runId: string) {
    return this.calculationEngine.executeRun(tenantId, runId);
  }
 
  async submit(tenantId: string, runId: string, userId: string) {
    await this.recordHistory(tenantId, runId, 'submitted', userId);
    return this.model
      .findOneAndUpdate(
        { _id: runId, tenantId },
        { $set: { status: 'review_pending' } },
        { new: true },
      )
      .lean();
  }
 
  async approve(
    tenantId: string,
    runId: string,
    userId: string,
    level: string,
  ) {
    await this.approvalModel.create({
      tenantId,
      runId,
      approverId: new Types.ObjectId(userId),
      approvalLevel: level,
      status: 'approved',
    });
    await this.recordHistory(tenantId, runId, 'approved', userId);
    return this.model
      .findOneAndUpdate(
        { _id: runId, tenantId },
        {
          $set: {
            status: 'approved',
            approvedBy: new Types.ObjectId(userId),
            approvedAt: new Date(),
          },
        },
        { new: true },
      )
      .lean();
  }
 
  async reject(
    tenantId: string,
    runId: string,
    userId: string,
    comments: string,
  ) {
    await this.approvalModel.create({
      tenantId,
      runId,
      approverId: new Types.ObjectId(userId),
      approvalLevel: 'hr_review',
      status: 'rejected',
      comments,
    });
    await this.recordHistory(tenantId, runId, 'rejected', userId);
    return this.model
      .findOneAndUpdate(
        { _id: runId, tenantId },
        { $set: { status: 'calculation_pending' } },
        { new: true },
      )
      .lean();
  }
 
  async lock(tenantId: string, runId: string, userId: string) {
    await this.lockModel.create({
      tenantId,
      runId,
      lockedBy: new Types.ObjectId(userId),
      lockedAt: new Date(),
    });
    await this.resultModel.updateMany(
      { tenantId, runId },
      { $set: { isLocked: true } },
    );
    await this.recordHistory(tenantId, runId, 'locked', userId);
    return this.model
      .findOneAndUpdate(
        { _id: runId, tenantId },
        { $set: { status: 'locked', lockedAt: new Date() } },
        { new: true },
      )
      .lean();
  }
 
  async reopen(tenantId: string, runId: string, userId: string) {
    await this.recordHistory(tenantId, runId, 'reopened', userId);
    return this.model
      .findOneAndUpdate(
        { _id: runId, tenantId },
        { $set: { status: 'reopened' } },
        { new: true },
      )
      .lean();
  }
 
  async cancel(tenantId: string, runId: string, userId: string) {
    await this.recordHistory(tenantId, runId, 'cancelled', userId);
    return this.model
      .findOneAndUpdate(
        { _id: runId, tenantId },
        { $set: { status: 'cancelled' } },
        { new: true },
      )
      .lean();
  }
 
  async getEmployees(tenantId: string, runId: string) {
    return this.empModel.find({ tenantId, runId }).lean();
  }
  async getExceptions(tenantId: string, runId: string) {
    return this.exceptionModel.find({ tenantId, runId }).lean();
  }
 
  async getVariance(tenantId: string, runId: string) {
    const results = await this.resultModel.find({ tenantId, runId }).lean();
    return {
      employees: results.length,
      totalGross: results.reduce((s, r) => s + r.grossEarnings, 0),
      totalNet: results.reduce((s, r) => s + r.netPay, 0),
    };
  }
 
  private async recordHistory(
    tenantId: string,
    runId: string,
    action: string,
    userId: string,
  ) {
    const run = await this.model.findOne({ _id: runId, tenantId });
    await this.historyModel.create({
      tenantId,
      runId,
      action,
      previousStatus: run?.status,
      newStatus: action,
      performedBy: new Types.ObjectId(userId),
    });
  }
}
 
// ── 9. Loan Service ──
@Injectable()
export class PayrollLoanService {
  constructor(
    @InjectModel(LoanType.name) private readonly typeModel: Model<LoanType>,
    @InjectModel(EmployeeLoan.name)
    private readonly loanModel: Model<EmployeeLoan>,
    @InjectModel(LoanApproval.name)
    private readonly approvalModel: Model<LoanApproval>,
    @InjectModel(LoanRepaymentSchedule.name)
    private readonly scheduleModel: Model<LoanRepaymentSchedule>,
    @InjectModel(LoanRepayment.name)
    private readonly repaymentModel: Model<LoanRepayment>,
    @InjectModel(LoanAdjustment.name)
    private readonly adjustmentModel: Model<LoanAdjustment>,
    @InjectModel(LoanForeclosure.name)
    private readonly foreclosureModel: Model<LoanForeclosure>,
  ) {}
 
  async list(tenantId: string, filters: Record<string, unknown> = {}) {
    return this.loanModel.find({ tenantId, ...filters }).lean();
  }
  async getById(tenantId: string, id: string) {
    const loan = await this.loanModel.findOne({ _id: id, tenantId }).lean();
    if (!loan) throw new NotFoundException('Loan not found');
    return loan;
  }
 
  async create(tenantId: string, data: Partial<EmployeeLoan>, userId: string) {
    const loan = await this.loanModel.create({
      ...data,
      tenantId,
      createdBy: new Types.ObjectId(userId),
    });
    // Generate repayment schedule
    if (loan.tenureMonths > 0 && loan.principalAmount > 0) {
      await this.generateSchedule(
        tenantId,
        loan._id.toString(),
        loan.principalAmount,
        loan.interestRate,
        loan.tenureMonths,
        loan.interestType,
      );
    }
    return loan;
  }
 
  async approve(tenantId: string, id: string, userId: string) {
    await this.approvalModel.create({
      tenantId,
      loanId: id,
      approverId: new Types.ObjectId(userId),
      status: 'approved',
    });
    return this.loanModel
      .findOneAndUpdate(
        { _id: id, tenantId },
        {
          $set: { status: 'approved', approvedBy: new Types.ObjectId(userId) },
        },
        { new: true },
      )
      .lean();
  }
 
  async reject(tenantId: string, id: string, userId: string, comments: string) {
    await this.approvalModel.create({
      tenantId,
      loanId: id,
      approverId: new Types.ObjectId(userId),
      status: 'rejected',
      comments,
    });
    return this.loanModel
      .findOneAndUpdate(
        { _id: id, tenantId },
        { $set: { status: 'rejected' } },
        { new: true },
      )
      .lean();
  }
 
  async getSchedule(tenantId: string, loanId: string) {
    return this.scheduleModel
      .find({ tenantId, loanId })
      .sort({ installmentNumber: 1 })
      .lean();
  }
 
  async reschedule(
    tenantId: string,
    loanId: string,
    newTenure: number,
    userId: string,
  ) {
    const loan = await this.loanModel.findOne({ _id: loanId, tenantId });
    if (!loan) throw new NotFoundException('Loan not found');
    await this.scheduleModel.deleteMany({
      tenantId,
      loanId,
      status: 'pending',
    });
    await this.generateSchedule(
      tenantId,
      loanId,
      loan.outstandingBalance,
      loan.interestRate,
      newTenure,
      loan.interestType,
    );
    await this.adjustmentModel.create({
      tenantId,
      loanId,
      adjustmentType: 'reschedule',
      details: { newTenure },
      performedBy: new Types.ObjectId(userId),
    });
    return { success: true };
  }
 
  async foreclose(
    tenantId: string,
    loanId: string,
    waivedAmount: number,
    userId: string,
  ) {
    const loan = await this.loanModel.findOne({ _id: loanId, tenantId });
    if (!loan) throw new NotFoundException('Loan not found');
    const finalAmount = loan.outstandingBalance - waivedAmount;
    await this.foreclosureModel.create({
      tenantId,
      loanId,
      outstandingAtForeclosure: loan.outstandingBalance,
      waivedAmount,
      finalSettlementAmount: finalAmount,
      foreclosureDate: new Date(),
      approvedBy: new Types.ObjectId(userId),
    });
    return this.loanModel
      .findOneAndUpdate(
        { _id: loanId },
        { $set: { status: 'foreclosed', outstandingBalance: 0 } },
        { new: true },
      )
      .lean();
  }
 
  private async generateSchedule(
    tenantId: string,
    loanId: string,
    principal: number,
    rate: number,
    months: number,
    interestType: string,
  ) {
    const schedules = [];
    let outstanding = principal;
    const monthlyRate = rate / 12 / 100;
 
    for (let i = 1; i <= months; i++) {
      let principalComp: number;
      let interestComp: number;
 
      if (interestType === 'interest_free') {
        principalComp = Math.round(principal / months);
        interestComp = 0;
      } else if (interestType === 'flat') {
        principalComp = Math.round(principal / months);
        interestComp = Math.round(principal * monthlyRate);
      } else {
        // Reducing balance EMI
        const emi =
          monthlyRate > 0
            ? (principal * monthlyRate * Math.pow(1 + monthlyRate, months)) /
              (Math.pow(1 + monthlyRate, months) - 1)
            : principal / months;
        interestComp = Math.round(outstanding * monthlyRate);
        principalComp = Math.round(emi - interestComp);
      }
 
      outstanding -= principalComp;
      const dueDate = new Date();
      dueDate.setMonth(dueDate.getMonth() + i);
 
      schedules.push({
        tenantId,
        loanId,
        installmentNumber: i,
        dueDate,
        principalComponent: principalComp,
        interestComponent: interestComp,
        totalInstallment: principalComp + interestComp,
        outstandingAfter: Math.max(0, outstanding),
      });
    }
 
    await this.scheduleModel.insertMany(schedules);
  }
}
 
// ── 10. Salary Advance Service ──
@Injectable()
export class SalaryAdvanceService {
  constructor(
    @InjectModel(SalaryAdvancePolicy.name)
    private readonly policyModel: Model<SalaryAdvancePolicy>,
    @InjectModel(SalaryAdvanceRequest.name)
    private readonly requestModel: Model<SalaryAdvanceRequest>,
    @InjectModel(SalaryAdvanceApproval.name)
    private readonly approvalModel: Model<SalaryAdvanceApproval>,
    @InjectModel(SalaryAdvanceRecoverySchedule.name)
    private readonly scheduleModel: Model<SalaryAdvanceRecoverySchedule>,
  ) {}
 
  async list(tenantId: string, filters: Record<string, unknown> = {}) {
    return this.requestModel.find({ tenantId, ...filters }).lean();
  }
  async create(
    tenantId: string,
    data: Partial<SalaryAdvanceRequest>,
    userId: string,
  ) {
    return this.requestModel.create({
      ...data,
      tenantId,
      createdBy: new Types.ObjectId(userId),
    });
  }
  async approve(tenantId: string, id: string, userId: string, amount: number) {
    await this.approvalModel.create({
      tenantId,
      advanceId: id,
      approverId: new Types.ObjectId(userId),
      status: 'approved',
    });
    const advance = await this.requestModel.findOneAndUpdate(
      { _id: id, tenantId },
      {
        $set: {
          status: 'approved',
          approvedAmount: amount,
          outstandingAmount: amount,
          approvedBy: new Types.ObjectId(userId),
        },
      },
      { new: true },
    );
    if (advance && advance.recoveryMonths > 0) {
      const perMonth = Math.round(amount / advance.recoveryMonths);
      const schedules = [];
      for (let i = 1; i <= advance.recoveryMonths; i++) {
        schedules.push({
          tenantId,
          advanceId: id,
          installmentNumber: i,
          amount:
            i === advance.recoveryMonths
              ? amount - perMonth * (advance.recoveryMonths - 1)
              : perMonth,
        });
      }
      await this.scheduleModel.insertMany(schedules);
    }
    return advance;
  }
}
 
// ── 11. Reimbursement Service ──
@Injectable()
export class PayrollReimbursementService {
  constructor(
    @InjectModel(ReimbursementType.name)
    private readonly typeModel: Model<ReimbursementType>,
    @InjectModel(ReimbursementClaim.name)
    private readonly claimModel: Model<ReimbursementClaim>,
    @InjectModel(ReimbursementItem.name)
    private readonly itemModel: Model<ReimbursementItem>,
    @InjectModel(ReimbursementApproval.name)
    private readonly approvalModel: Model<ReimbursementApproval>,
    @InjectModel(ReimbursementSettlement.name)
    private readonly settlementModel: Model<ReimbursementSettlement>,
  ) {}
 
  async listTypes(tenantId: string) {
    return this.typeModel.find({ tenantId, isActive: true }).lean();
  }
  async listClaims(tenantId: string, filters: Record<string, unknown> = {}) {
    return this.claimModel.find({ tenantId, ...filters }).lean();
  }
  async createClaim(
    tenantId: string,
    data: Partial<ReimbursementClaim>,
    userId: string,
  ) {
    return this.claimModel.create({
      ...data,
      tenantId,
      createdBy: new Types.ObjectId(userId),
    });
  }
  async approveClaim(
    tenantId: string,
    claimId: string,
    userId: string,
    approvedAmount: number,
  ) {
    await this.approvalModel.create({
      tenantId,
      claimId,
      approverId: new Types.ObjectId(userId),
      status: 'approved',
    });
    return this.claimModel
      .findOneAndUpdate(
        { _id: claimId, tenantId },
        {
          $set: {
            status: 'approved',
            approvedAmount,
            approvedBy: new Types.ObjectId(userId),
          },
        },
        { new: true },
      )
      .lean();
  }
}
 
// ── 12. Payslip Service ──
@Injectable()
export class PayslipService {
  constructor(
    @InjectModel(Payslip.name) private readonly model: Model<Payslip>,
    @InjectModel(PayslipTemplate.name)
    private readonly templateModel: Model<PayslipTemplate>,
    @InjectModel(PayslipDeliveryLog.name)
    private readonly deliveryModel: Model<PayslipDeliveryLog>,
    @InjectModel(PayrollCalculationResult.name)
    private readonly resultModel: Model<PayrollCalculationResult>,
    @InjectModel(PayrollCalculationComponent.name)
    private readonly calcCompModel: Model<PayrollCalculationComponent>,
  ) {}
 
  async list(tenantId: string, filters: Record<string, unknown> = {}) {
    return this.model
      .find({ tenantId, ...filters })
      .sort({ createdAt: -1 })
      .lean();
  }
  async getById(tenantId: string, id: string) {
    const payslip = await this.model.findOne({ _id: id, tenantId }).lean();
    if (!payslip) throw new NotFoundException('Payslip not found');
    return payslip;
  }
  async getByEmployeeAndPeriod(
    tenantId: string,
    employeeId: string,
    periodId: string,
  ) {
    return this.model.findOne({ tenantId, employeeId, periodId }).lean();
  }
 
  async generateForRun(tenantId: string, runId: string) {
    const results = await this.resultModel.find({ tenantId, runId }).lean();
    const payslips = [];
    for (const result of results) {
      const existing = await this.model.findOne({
        tenantId,
        runId,
        employeeId: result.employeeId,
      });
      if (existing) {
        await this.model.updateOne(
          { _id: existing._id },
          {
            $inc: { version: 1 },
            $set: { generatedAt: new Date(), status: 'generated' },
          },
        );
      } else {
        payslips.push({
          tenantId,
          runId,
          employeeId: result.employeeId,
          resultId: result._id,
          periodId: (result as Record<string, unknown>)['periodId'] ?? runId,
          generatedAt: new Date(),
          status: 'generated',
        });
      }
    }
    if (payslips.length > 0) await this.model.insertMany(payslips);
    return {
      generated: payslips.length,
      updated: results.length - payslips.length,
    };
  }
 
  async send(tenantId: string, payslipId: string) {
    const payslip = await this.model.findOne({ _id: payslipId, tenantId });
    if (!payslip) throw new NotFoundException('Payslip not found');
    await this.deliveryModel.create({
      tenantId,
      payslipId,
      employeeId: payslip.employeeId,
      channel: 'email',
      status: 'sent',
    });
    return this.model
      .findOneAndUpdate(
        { _id: payslipId },
        { $set: { status: 'delivered', deliveredAt: new Date() } },
        { new: true },
      )
      .lean();
  }
}
 
// ── 13. Payment Service ──
@Injectable()
export class PayrollPaymentService {
  constructor(
    @InjectModel(PayrollPaymentBatch.name)
    private readonly batchModel: Model<PayrollPaymentBatch>,
    @InjectModel(PayrollPaymentInstruction.name)
    private readonly instructionModel: Model<PayrollPaymentInstruction>,
    @InjectModel(PayrollBankFile.name)
    private readonly bankFileModel: Model<PayrollBankFile>,
    @InjectModel(PayrollPaymentReconciliation.name)
    private readonly reconModel: Model<PayrollPaymentReconciliation>,
  ) {}
 
  async createBatch(tenantId: string, runId: string, userId: string) {
    return this.batchModel.create({
      tenantId,
      runId,
      batchName: `Batch-${Date.now()}`,
      generatedBy: new Types.ObjectId(userId),
    });
  }
  async getBatch(tenantId: string, batchId: string) {
    return this.batchModel.findOne({ _id: batchId, tenantId }).lean();
  }
  async listInstructions(tenantId: string, batchId: string) {
    return this.instructionModel.find({ tenantId, batchId }).lean();
  }
}
 
// ── 14. Accounting Service ──
@Injectable()
export class PayrollAccountingService {
  constructor(
    @InjectModel(PayrollAccountingMapping.name)
    private readonly mappingModel: Model<PayrollAccountingMapping>,
    @InjectModel(PayrollJournalExport.name)
    private readonly journalModel: Model<PayrollJournalExport>,
    @InjectModel(PayrollCostAllocation.name)
    private readonly allocationModel: Model<PayrollCostAllocation>,
  ) {}
 
  async getMappings(tenantId: string) {
    return this.mappingModel.find({ tenantId }).lean();
  }
  async createMapping(
    tenantId: string,
    data: Partial<PayrollAccountingMapping>,
  ) {
    return this.mappingModel.create({ ...data, tenantId });
  }
  async generateJournal(tenantId: string, runId: string, periodId: string) {
    return this.journalModel.create({
      tenantId,
      runId,
      periodId,
      entries: [],
      status: 'generated',
    });
  }
}
 
// ── 15. Full & Final Settlement Service ──
@Injectable()
export class FullAndFinalService {
  constructor(
    @InjectModel(FullAndFinalSettlement.name)
    private readonly model: Model<FullAndFinalSettlement>,
    @InjectModel(SettlementComponent.name)
    private readonly compModel: Model<SettlementComponent>,
    @InjectModel(SettlementRecovery.name)
    private readonly recoveryModel: Model<SettlementRecovery>,
    @InjectModel(SettlementApproval.name)
    private readonly approvalModel: Model<SettlementApproval>,
  ) {}
 
  async create(
    tenantId: string,
    employeeId: string,
    data: Partial<FullAndFinalSettlement>,
    userId: string,
  ) {
    return this.model.create({
      ...data,
      tenantId,
      employeeId,
      createdBy: new Types.ObjectId(userId),
    });
  }
 
  async calculate(tenantId: string, settlementId: string) {
    const earnings = await this.compModel
      .find({ tenantId, settlementId, type: 'earning' })
      .lean();
    const recoveries = await this.recoveryModel
      .find({ tenantId, settlementId })
      .lean();
    const totalEarnings = earnings.reduce((s, e) => s + e.amount, 0);
    const totalRecoveries = recoveries.reduce((s, r) => s + r.amount, 0);
    return this.model
      .findOneAndUpdate(
        { _id: settlementId, tenantId },
        {
          $set: {
            totalEarnings,
            totalRecoveries,
            netSettlement: totalEarnings - totalRecoveries,
            status: 'calculated',
          },
        },
        { new: true },
      )
      .lean();
  }
 
  async approve(tenantId: string, settlementId: string, userId: string) {
    await this.approvalModel.create({
      tenantId,
      settlementId,
      approverId: new Types.ObjectId(userId),
      status: 'approved',
    });
    return this.model
      .findOneAndUpdate(
        { _id: settlementId, tenantId },
        {
          $set: { status: 'approved', approvedBy: new Types.ObjectId(userId) },
        },
        { new: true },
      )
      .lean();
  }
}
 
// ── 16. Dashboard Service ──
@Injectable()
export class PayrollDashboardService {
  constructor(
    @InjectModel(PayrollRun.name) private readonly runModel: Model<PayrollRun>,
    @InjectModel(PayrollCalculationResult.name)
    private readonly resultModel: Model<PayrollCalculationResult>,
    @InjectModel(PayrollCalculationComponent.name)
    private readonly calcCompModel: Model<PayrollCalculationComponent>,
    @InjectModel(EmployeeLoan.name)
    private readonly loanModel: Model<EmployeeLoan>,
    @InjectModel(ReimbursementClaim.name)
    private readonly reimbModel: Model<ReimbursementClaim>,
    @InjectModel(PayrollRunException.name)
    private readonly exceptionModel: Model<PayrollRunException>,
  ) {}
 
  async getSummary(tenantId: string) {
    const latestRun = await this.runModel
      .findOne({
        tenantId,
        status: { $in: ['completed', 'locked', 'approved'] },
      })
      .sort({ createdAt: -1 })
      .lean();
    if (!latestRun) return { hasData: false };
    return {
      hasData: true,
      runId: latestRun._id,
      status: latestRun.status,
      totalEmployees: latestRun.totalEmployees,
      totalGross: latestRun.totalGross,
      totalDeductions: latestRun.totalDeductions,
      totalNetPay: latestRun.totalNetPay,
      totalEmployerCost: latestRun.totalEmployerCost,
    };
  }
 
  async getPayrollCost(tenantId: string) {
    return this.runModel
      .find({ tenantId, status: { $in: ['completed', 'locked'] } })
      .sort({ createdAt: -1 })
      .limit(12)
      .select('runName totalGross totalNetPay totalEmployerCost createdAt')
      .lean();
  }
 
  async getDepartmentCost(tenantId: string, runId: string) {
    return this.resultModel.aggregate([
      { $match: { tenantId, runId } },
      {
        $group: {
          _id: '$departmentId',
          totalGross: { $sum: '$grossEarnings' },
          totalNet: { $sum: '$netPay' },
          count: { $sum: 1 },
        },
      },
    ]);
  }
 
  async getExceptions(tenantId: string, runId: string) {
    return this.exceptionModel.find({ tenantId, runId }).lean();
  }
 
  async getLoanSummary(tenantId: string) {
    return this.loanModel.aggregate([
      { $match: { tenantId, status: 'active' } },
      {
        $group: {
          _id: null,
          totalOutstanding: { $sum: '$outstandingBalance' },
          totalLoans: { $sum: 1 },
        },
      },
    ]);
  }
}
 
// ── 17. Import/Export Service ──
@Injectable()
export class PayrollImportExportService {
  constructor(
    @InjectModel(PayrollImportJob.name)
    private readonly importModel: Model<PayrollImportJob>,
    @InjectModel(PayrollImportRow.name)
    private readonly importRowModel: Model<PayrollImportRow>,
    @InjectModel(PayrollExportJob.name)
    private readonly exportModel: Model<PayrollExportJob>,
  ) {}
 
  async createImportJob(
    tenantId: string,
    data: Partial<PayrollImportJob>,
    userId: string,
  ) {
    return this.importModel.create({
      ...data,
      tenantId,
      createdBy: new Types.ObjectId(userId),
    });
  }
  async getImportJob(tenantId: string, jobId: string) {
    return this.importModel.findOne({ _id: jobId, tenantId }).lean();
  }
  async createExportJob(
    tenantId: string,
    data: Partial<PayrollExportJob>,
    userId: string,
  ) {
    return this.exportModel.create({
      ...data,
      tenantId,
      createdBy: new Types.ObjectId(userId),
    });
  }
}