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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import datetime
import re

from pydantic import (
    BaseModel,
    computed_field,
    Field,
    ValidationInfo,
    model_validator,
    ConfigDict
)
import pandas as pd


class UKPayslipSchema(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)
    pay_period_start_date: datetime.date | None = Field(
        default=None,
        description="Pay period's start date in YYYY-MM-DD format",
        examples=["2025-02-01"],
    )
    pay_period_end_date: datetime.date | None = Field(
        default=None,
        description="Pay period's end date in YYYY-MM-DD format",
        examples=["2025-02-28"],
    )
    pay_period_days: int | None = Field(
        default=None,
        description="pay_period_end_date - pay_period_start_date in days",
        examples=[28],
    )
    pay_date: datetime.date | None = Field(None)
    full_name: str | None = Field(
        default=None,
        description="Applicant's full name. Must consist of at least 2 words, have length gte 2 & lte 61",
        examples=["Jodie Pippa"],
    )
    employer_name: str | None = Field(
        default=None,
        description="Employer name extracted",
        examples=["ABC Ltd"],
    )
    is_basic_pay_net_pay_other_salary_components_present: bool = Field(
        default=False,
        description="Boolean indicating whether Basic Pay, Net Pay, other requisite salary components/line items are present in the payslip",
        examples=[True, False],
    )
    is_tax_deducation_present: bool = Field(
        default=False,
        description="Boolean flag indicating whether Tax Deduction line item is present in the payslip",
        examples=[True, False],
    )
    is_ni_deduction_present: bool = Field(
        default=False,
        description="Boolean flag indicating whether NI/National Insurance deduction line item is present in the payslip",
        examples=[True, False],
    )
    complete_employee_address: str | None = Field(
        default=None,
        description="Employee's complete address as a string",
        examples=["123 Maple Street, London, UK, SW1A 1AA"],
    )
    # employee_number: int | None = Field(
    #     default=None,
    #     description="Employee number",
    #     examples=[3558, 1234],
    # )

    pay_dates_err_msgs: str | None = None
    full_name_err_msgs: str | None = None
    employer_name_err_msgs: str | None = None
    payslip_line_item_presence_err_msgs: str | None = None
    complete_employee_address_err_msgs: str | None = None
    validation_policy_status_df: pd.DataFrame = pd.DataFrame(
        columns=["Policy", "Value", "Status", "Message"])
    # employee_number_err_msgs: str | None = None
    # is_red_flagged: bool = False

    @model_validator(mode="after")
    def validate_full_name(self, info: ValidationInfo):
        """Match applicant's full name against provided name (case-insensitive)"""
        try:
            err_msgs = []
            expected = (
                info.context.get("application_summary_full_name")
                if info.context
                else None
            )

            if not self.full_name:
                err_msgs.append("Applicant's full name not present")
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", self.full_name, False, "Applicant's full name is not present"]
            else:
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", self.full_name, True, "Applicant's full name is present"]

            full_name_val_len = len(self.full_name) if self.full_name else 0
            if not (2 <= full_name_val_len <= 61):
                err_msgs.append(
                    "Full name must have a length of at least 2 & at most 61"
                )
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", full_name_val_len, False, "Full name has a length of at least 2 & at most 61"]
            else:
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", full_name_val_len, True, "Full name has a length of at least 2 & at most 61"]

            if not self.full_name or len(self.full_name.strip().split(" ")) < 2:
                err_msgs.append(
                    "Full name must consist of at least 2 words (first name + last name)"
                )
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names",  self.full_name , False, "Full name does not consist of at least 2 words (first name + last name)"]
            else:
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", len(self.full_name.strip().split(" ")), True, "Full name consists of at least 2 words (first name + last name)"]

            if (
                not expected
                or not self.full_name
                or self.full_name.lower() != expected.lower()
            ):
                err_msgs.append("Name mismatch with provided value")
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", f"{self.full_name}, {expected}", False, "Name does not match with provided value"]
            else:
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", f"{self.full_name}, {expected}", True, "Name matches with provided value"]

            self.full_name_err_msgs = ", ".join(err_msgs) if err_msgs else None
            return self
        except Exception as e:
            # logger.exception(e, exc_info=True)
            # return None
            raise

    @model_validator(mode="after")
    def validate_employer_name(self, info: ValidationInfo):
        """Match employer against provided employer name (case-insensitive)"""
        try:
            err_msgs = []
            expected = (
                info.context.get("application_summary_employer_name")
                if info.context
                else None
            )
            employer_name_val = self.employer_name

            if not employer_name_val:
                err_msgs.append("Employer name not present")
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", employer_name_val, False, "Employer name is not present"]
            else:

                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", employer_name_val, True, "Employer name is present"]

            is_employer_name_match = (
                expected
                and employer_name_val
                and employer_name_val.lower() == expected.lower()
            )

            if not is_employer_name_match:
                err_msgs.append("Employer name mismatch with provided value")
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", f"{employer_name_val}, {expected}", False, "Employer name does not match with provided value"]
            else:
                self.validation_policy_status_df.loc[len(
                    self.validation_policy_status_df)] = ["Employer & Customer Names", f"{employer_name_val}, {expected}", True, "Employer name matches with provided value"]
                # # Allowed: letters, numbers, spaces, and common name punctuation
                # pattern = r"^[A-Za-z0-9&\-,.()'/@ ]{2,100}$"

                # if not re.match(pattern, employer_name_val):
                #     err_msgs.append("Employer name contains invalid characters")
                if not re.search(r"[A-Za-z]", employer_name_val):
                    err_msgs.append(
                        "Employer name must contain at least one letter")
                if employer_name_val.strip() == "":
                    err_msgs.append("Employer name cannot be only whitespace")

            self.employer_name_err_msgs = ", ".join(
                err_msgs) if err_msgs else None
            return self
        except Exception as e:
            # logger.exception(e, exc_info=True)
            # return None
            raise

    @model_validator(mode="after")
    def validate_payslip_dates(self):
        try:
            err_msgs = []
            today = datetime.date.today()
            threshold_date = today - datetime.timedelta(days=35)

            if not self.pay_period_start_date or not self.pay_period_end_date:
                err_msgs.append(
                    "Undated Payslips"
                )
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Undated Payslips",
                    f"{self.pay_period_start_date}, {self.pay_period_end_date}",
                    False,
                    "Undated payslip",
                ]
            else:
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Undated Payslips",
                    f"{self.pay_period_start_date}, {self.pay_period_end_date}",
                    True,
                    "Dated payslip",
                ]
                # self.is_red_flagged = True

            
            if self.pay_date:
                if not (threshold_date <= self.pay_date <= today):
                    err_msgs.append(
                        "Pay date must be within the last 35 days & not in the future"
                    )
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Pay Date Requirement",
                        self.pay_date,
                        False,
                        "Pay date is not within the last 35 days & not in the future",
                    ]
                else:
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Pay Date Requirement",
                        self.pay_date,
                        True,
                        "Pay date is within the last 35 days & not in the future",
                    ]

            # elif self.pay_period_end_date:
            else:
                if not (threshold_date <= self.pay_period_end_date <= today):
                    err_msgs.append(
                        "Pay period's end date must be within the last 35 days & not in the future"
                    )
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Pay Period End Date (DD/MM/YYYY, if no pay date)",
                        self.pay_date,
                        False,
                        "Pay date is not within the last 35 days &/or in the future",
                    ]
                else:
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Pay Period End Date (DD/MM/YYYY, if no pay date)",
                        self.pay_date,
                        True,
                        "Pay date is within the last 35 days & not in the future",
                    ]

                prev_month_end = datetime.date.today().replace(day=1) - \
                    datetime.timedelta(days=1)
                prev_month_start = prev_month_end.replace(day=1)
                if not (
                    prev_month_start <= self.pay_period_start_date
                    and self.pay_period_start_date < self.pay_period_end_date <= today
                ):
                    err_msgs.append(
                        "Payslip date(s) must not be older than those of the last calendar month"
                    )

                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Pay Period Month (MM/YYYY, if no pay date) basis pay period duration",
                        self.pay_date,
                        False,
                        "Payslip date(s) is older than those of the last calendar month",
                    ]
                else:
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Pay Period Month (MM/YYYY, if no pay date) basis pay period duration",
                        self.pay_date,
                        True,
                        "Payslip date(s) is not older than those of the last calendar month",
                    ]

            if self.pay_period_start_date and self.pay_period_end_date:

                if self.pay_period_start_date >= self.pay_period_end_date:
                    err_msgs.append(
                        "Pay period's start date must be before the end date")
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Pay Period Start & End Dates",
                        f"{self.pay_period_start_date}, {self.pay_period_end_date}",
                        False,
                        "Pay period's start date is not before the end date",
                    ]
                else:
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Pay Period Start & End Dates",
                        f"{self.pay_period_start_date}, {self.pay_period_end_date}",
                        True,
                        "Pay period's start date is before the end date",
                    ]



                if (self.pay_period_end_date - self.pay_period_start_date).days < 28:
                    err_msgs.append(
                        "Pay period's start date & end date must have a gap of at least 28 days"
                    )
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Submission Requirement (Monthly Pay)",
                        (self.pay_period_end_date - self.pay_period_start_date).days,
                        False,
                        "Pay period's start date & end date donot have a gap of at least 28 days",
                    ]
                else:
                    self.validation_policy_status_df.loc[
                        len(self.validation_policy_status_df)
                    ] = [
                        "Submission Requirement (Monthly Pay)",
                        (self.pay_period_end_date - self.pay_period_start_date).days,
                        True,
                        "Pay period's start date & end date have a gap of at least 28 days",
                    ]
            else:
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Pay Period Start & End Dates",
                    f"{self.pay_period_start_date}, {self.pay_period_end_date}",
                    False,
                    "Pay period's start date is not before the end date",
                ]
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Submission Requirement (Monthly Pay)",
                    f"{self.pay_period_start_date}, {self.pay_period_end_date}",
                    False,
                    "Pay period's start date & end date donot have a gap of at least 28 days",
                ]
                                

            self.pay_dates_err_msgs = ", ".join(err_msgs) if err_msgs else None
            return self
        except Exception as e:
            # logger.exception(e, exc_info=True)
            # return None
            raise

    @model_validator(mode="after")
    def validate_payslip_components_checks(self):
        try:
            err_msgs = []

            if not self.is_basic_pay_net_pay_other_salary_components_present:
                err_msgs.append(
                    "Basic salary, Net Salary and/or other requisite salary components not present"
                )

                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Requisite salary line items",
                    self.is_basic_pay_net_pay_other_salary_components_present,
                    False,
                    "Basic salary, Net Salary and/or other requisite salary components not present",
                ]
            else:
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Requisite salary line items",
                    self.is_basic_pay_net_pay_other_salary_components_present,
                    True,
                    "Basic salary, Net Salary and/or other requisite salary components are present",
                ]

            if not self.is_tax_deducation_present:
                err_msgs.append("Tax Deduction line item must be present")
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Tax & NI Contributions",
                    self.is_tax_deducation_present,
                    False,
                    "Tax Deduction line item is not present",
                ]
            else:
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Tax & NI Contributions",
                    self.is_tax_deducation_present,
                    True,
                    "Tax Deduction line item is present",
                ]

            if not self.is_ni_deduction_present:
                err_msgs.append("NI/National Insurance line item must be present")
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Tax & NI Contributions",
                    self.is_ni_deduction_present,
                    False,
                    "NI/National Insurance line item is not present",
                ]
            else:
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Tax & NI Contributions",
                    self.is_ni_deduction_present,
                    True,
                    "NI/National Insurance line item is present",
                ]

            self.payslip_line_item_presence_err_msgs = (
                ", ".join(err_msgs) if err_msgs else None
            )
            return self
        except Exception as e:
            # logger.exception(e, exc_info=True)
            # return None
            raise

    @model_validator(mode="after")
    def validate_complete_address(self, info: ValidationInfo):
        try:
            err_msgs = []
            expected = (
                info.context.get("application_summary_complete_address")
                if info.context
                else None
            )
            val = self.complete_employee_address

            if not val:
                err_msgs.append("Applicant's address not present")
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Applicant Address",
                    val,
                    False,
                    "Applicant's address not present",
                ]
            else:
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Applicant Address",
                    val,
                    True,
                    "Applicant's address is present",
                ]

            length = len(val) if val else 0
            if not (10 <= length <= 300):
                err_msgs.append(
                    "Applicant's complete address must have a length of at least 10 & at most 300"
                )
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Applicant Address",
                    length,
                    False,
                    "Applicant's complete address does not have a length of at least 10 & at most 300",
                ]
            else:
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Applicant Address",
                    length,
                    True,
                    "Applicant's complete address has a length of at least 10 & at most 300",
                ]

            if not expected or not val or val.lower() != expected.lower():
                err_msgs.append("Complete address mismatch with provided value")
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Applicant Address",
                    f"{val}, {expected}",
                    False,
                    "Complete address mismatch with provided value",
                ]
            else:
                self.validation_policy_status_df.loc[
                    len(self.validation_policy_status_df)
                ] = [
                    "Applicant Address",
                    f"{val}, {expected}",
                    True,
                    "Complete address matches with provided value",
                ]

            self.complete_employee_address_err_msgs = (
                ", ".join(err_msgs) if err_msgs else None
            )
            return self
        except Exception as e:
            # logger.exception(e, exc_info=True)
            # return None
            raise

    # @model_validator(mode="after")
    # def validate_employee_number(self):
    #     try:
    #         if self.employee_number and self.employee_number <= 25:
    #             self.complete_employee_address_err_msgs = "Employee number low"
    #         return self
    #     except Exception as e:
    #         raise

    @computed_field
    @property
    def is_red_flagged(self) -> bool:
        if any([
            self.pay_dates_err_msgs,
            self.full_name_err_msgs,
            self.employer_name_err_msgs,
            self.payslip_line_item_presence_err_msgs,
            self.complete_employee_address_err_msgs,
            # self.employee_number_err_msgs,
        ]):
            return True
        return False