跳到正文
DEV Community· Monu Kumar·· 48 分鐘前AI 評分45

如何用 Python 在銀行拒收前檢查阿聯酋 WPS 薪金檔案(SIF)

Check a UAE WPS salary file (SIF) in Python before the bank rejects it

AI 導讀

這篇教學提供一個只使用 Python 標準函式庫的腳本,讓用戶在上載前檢查阿聯酋 WPS 薪金資訊檔案(SIF),減少常見錯誤導致銀行拒收。腳本會檢查檔案結構、員工及銀行代碼、IBAN 校驗位、日期、薪金金額、總額和檔名是否相符。

正文

Private-sector salaries in the UAE are paid through the Wage Protection System (WPS), which runs at the Central Bank of the UAE. Each payroll run starts with a Salary Information File (SIF), a small text file that the employer uploads to its bank or exchange house.

The bank checks the file before anyone is paid. Some mistakes, such as an invalid routing code or a wrong IBAN, get the whole file rejected, and Mashreq's guide says that rejection can take up to two working days to come back. Meanwhile, every employee in the file is waiting for their salary.

This post explains the format and gives you a Python script, using only the standard library, that catches the common mistakes before you upload.

The format in brief

A SIF is plain text with comma-separated fields and no header row. It has one EDR (employee detail record) line per employee and one SCR (salary control record) line at the end. Some banks also use EVP lines for variable pay.

Each EDR line has 10 fields:

# Field Format
1 Record type EDR
2 Employee's person ID from the labour authority 14 characters
3 Routing code of the employee's bank or exchange house 9 digits
4 Employee's IBAN or salary card number an IBAN is 23 characters
5 Pay start date YYYY-MM-DD
6 Pay end date YYYY-MM-DD
7 Days in the pay period end date − start date + 1
8 Fixed salary AED, up to 2 decimals, no minus sign
9 Variable salary 0.00 if none
10 Days of unpaid leave 0 if none

The SCR line also has 10 fields:

# Field Format
1 Record type SCR
2 Employer's establishment ID 13 digits
3 Routing code of the employer's bank 9 digits
4 File creation date YYYY-MM-DD
5 File creation time HHMM
6 Salary month MMYYYY
7 Number of EDR lines must match the file
8 Total salary fixed + variable, summed over all EDR lines
9 Currency AED
10 Employer reference optional (some banks ask for NONE)

The file name is the establishment ID followed by the creation date and time as YYMMDDHHMMSS, for example 1000000000001261126093000.SIF. The date and time in the name must match the SCR line.

Here's a valid file for two employees. The IDs and IBANs are made up, but the IBANs have valid check digits:

EDR,10000000000001,203320101,AE070331234567890123456,2026-10-01,2026-10-31,31,8000.00,500.00,0
EDR,10000000000002,203320101,AE700330000000000004521,2026-10-01,2026-10-31,31,6000.00,0.00,2
SCR,1000000000001,203320101,2026-11-26,0930,102026,2,14500.00,AED,October payroll

What the script checks

  • Structure: every line has 10 fields, and there's exactly one SCR line, as the last line. Empty lines and quotation marks aren't allowed.
  • IDs and routing codes: a 14-character person ID, a 13-digit establishment ID and 9-digit routing codes. Each employee can appear only once.
  • IBANs: the check digits (the standard mod-97 test), and that the 3-digit bank code inside the IBAN matches digits 2–4 of the routing code. Mashreq's IBAN guide describes the bank code this way. This catches an employee who changed banks when only one of the two fields was updated.
  • Dates: the days in the period equal end − start + 1, every pay period falls inside the salary month, pay dates are within a year of today, and the file isn't dated in the future.
  • Money: no minus signs, at most two decimals, and the SCR count and total match the EDR lines exactly. The script adds amounts with Decimal instead of float, so a one-fils difference is caught and float rounding can't cause false alarms.
  • File name: the establishment ID, date and time in the name match the SCR line.

The script

"""Check a UAE WPS salary information file (SIF) before you upload it.

Usage: python sif_check.py 1000000000001261126093000.SIF

Field rules differ slightly between banks and exchange houses,
so adjust the patterns below to match your agent's SIF guide.
"""
import re
import sys
from datetime import date, datetime
from decimal import Decimal
from pathlib import Path

PERSON_ID = re.compile(r"\d{14}")        # employee's labour person ID
EMPLOYER_ID = re.compile(r"\d{13}")      # establishment ID
ROUTING = re.compile(r"\d{9}")           # Central Bank routing code
AMOUNT = re.compile(r"\d+(\.\d{1,2})?")  # no minus sign, at most 2 decimals
TIME = re.compile(r"([01]\d|2[0-3])[0-5]\d")             # HHMM
SALARY_MONTH = re.compile(r"(0[1-9]|1[0-2])\d{4}")       # MMYYYY
FILE_NAME = re.compile(r"(\d{13})(\d{6})(\d{6})\.sif", re.IGNORECASE)


def iban_ok(iban):
    """UAE IBAN: AE, 2 check digits, 3-digit bank code, 16-digit account."""
    if not re.fullmatch(r"AE\d{21}", iban):
        return False
    moved = iban[4:] + iban[:4]
    return int("".join(str(int(ch, 36)) for ch in moved)) % 97 == 1


def to_date(text):
    try:
        return datetime.strptime(text, "%Y-%m-%d").date()
    except ValueError:
        return None


def check_edr(f, bad, today):
    """Check one employee line. Returns (salary, start, end); any can be None."""
    if not PERSON_ID.fullmatch(f[1]):
        bad("person ID should be 14 digits")
    if not ROUTING.fullmatch(f[2]):
        bad("routing code should be 9 digits")
    account = f[3]
    if account.startswith("AE"):
        if not iban_ok(account):
            bad("IBAN is malformed or fails its check digits")
        elif ROUTING.fullmatch(f[2]) and account[4:7] != f[2][1:4]:
            bad("IBAN bank code doesn't match the routing code")
    elif not account.isdigit():
        bad("account should be an IBAN or a salary card number")

    start, end = to_date(f[4]), to_date(f[5])
    if not (start and end):
        bad("pay dates must be YYYY-MM-DD")
        start = end = None
    elif end < start:
        bad("pay end date is before the start date")
    else:
        if not f[6].isdigit() or int(f[6]) != (end - start).days + 1:
            bad(f"days in period should be {(end - start).days + 1}")
        if max(abs((start - today).days), abs((end - today).days)) > 365:
            bad("pay dates are more than a year from today")

    if not (f[9].isdigit() and int(f[9]) <= 999):
        bad("unpaid leave days should be a number from 0 to 999")
    if not (AMOUNT.fullmatch(f[7]) and AMOUNT.fullmatch(f[8])):
        bad("salaries need digits, up to 2 decimals and no minus sign")
        return None, start, end
    return Decimal(f[7]) + Decimal(f[8]), start, end


def check(path):
    problems = []
    lines = path.read_text(encoding="utf-8-sig").splitlines()
    edrs, scrs, seen = [], [], set()
    today = date.today()

    for n, line in enumerate(lines, start=1):
        def bad(msg, n=n):
            problems.append(f"line {n}: {msg}")

        if not line.strip() or '"' in line:
            bad("empty lines and quotation marks aren't allowed")
            continue
        f = [x.strip() for x in line.split(",")]
        if f[0] not in ("EDR", "SCR", "EVP"):
            bad(f"unknown record type {f[0]!r}")
        elif f[0] == "EVP":
            continue  # variable-pay lines: check against your bank's guide
        elif len(f) != 10:
            bad(f"{f[0]} lines need 10 fields, found {len(f)}")
        elif f[0] == "SCR":
            scrs.append((n, f))
        else:
            if f[1] in seen:
                bad(f"employee {f[1]} appears more than once")
            seen.add(f[1])
            edrs.append((n, check_edr(f, bad, today)))

    if len(scrs) != 1 or scrs[0][0] != len(lines):
        return problems + ["file needs exactly one SCR line, as the last line"]

    n, s = scrs[0]
    def bad(msg):
        problems.append(f"line {n}: {msg}")

    if not EMPLOYER_ID.fullmatch(s[1]):
        bad("establishment ID should be 13 digits")
    if not ROUTING.fullmatch(s[2]):
        bad("employer's routing code should be 9 digits")
    created = to_date(s[3])
    if not created or not TIME.fullmatch(s[4]):
        bad("creation date and time must be YYYY-MM-DD and HHMM")
    elif created > today:
        bad("creation date is in the future")
    if not SALARY_MONTH.fullmatch(s[5]):
        bad("salary month must be MMYYYY")
    if not s[6].isdigit() or int(s[6]) != len(edrs):
        bad(f"EDR count says {s[6]}, but the file has {len(edrs)} EDR lines")
    total = sum((r[0] for _, r in edrs if r[0] is not None), Decimal("0"))
    if not AMOUNT.fullmatch(s[7]) or Decimal(s[7]) != total:
        bad(f"salary total says {s[7]}, but the EDR lines add up to {total:.2f}")
    if s[8] != "AED":
        bad("currency must be AED")

    if SALARY_MONTH.fullmatch(s[5]):
        month = (int(s[5][:2]), int(s[5][2:]))
        for edr_line, (_, start, end) in edrs:
            if start and {(start.month, start.year), (end.month, end.year)} != {month}:
                problems.append(f"line {edr_line}: pay period isn't in salary month {s[5]}")

    name = FILE_NAME.fullmatch(path.name)
    if not name:
        problems.append("file name should be the employer ID, YYMMDDHHMMSS and .SIF")
    elif created and TIME.fullmatch(s[4]):
        if (name[1], name[2], name[3][:4]) != (s[1], created.strftime("%y%m%d"), s[4]):
            problems.append("file name doesn't match the SCR employer ID, date and time")

    def line_no(problem):
        m = re.match(r"line (\d+):", problem)
        return int(m[1]) if m else len(lines) + 1

    return sorted(problems, key=line_no)


if __name__ == "__main__":
    found = check(Path(sys.argv[1]))
    print("\n".join(found) or "No problems found.")
    sys.exit(1 if found else 0)

Running it

Here's a broken version of the file above, saved as 1000000000001261126101500.SIF:

EDR,10000000000001,203320101,AE070331234567890123457,2026-10-01,2026-10-31,30,8000.00,500.00,0
EDR,10000000000001,802420101,AE700330000000000004521,2026-09-01,2026-09-30,30,-6000.00,0.00,0
SCR,1000000000001,203320101,2026-11-26,0930,102026,2,14500.00,AED,October payroll
$ python sif_check.py 1000000000001261126101500.SIF
line 1: IBAN is malformed or fails its check digits
line 1: days in period should be 31
line 2: employee 10000000000001 appears more than once
line 2: IBAN bank code doesn't match the routing code
line 2: salaries need digits, up to 2 decimals and no minus sign
line 2: pay period isn't in salary month 102026
line 3: salary total says 14500.00, but the EDR lines add up to 8500.00
file name doesn't match the SCR employer ID, date and time

The script exits with code 1 when it finds a problem, so you can run it in CI or as a step before your payroll export gets uploaded.

What it can't check

  • Whether the IDs exist. It checks that person IDs, establishment IDs and routing codes are well formed, not that they're registered in WPS. Only your bank or exchange house can check that.
  • Your agent's exact rules. Banks and exchange houses differ. Dubai Islamic Bank's guide, for example, allows employer IDs of 13 to 35 characters, and some agents need EVP lines for variable pay. Adjust the patterns at the top of the script to match your agent's SIF guide.

Sources

For the rules around the file, such as payment due dates, enforcement and the upgraded WPS, see our longer guide: The UAE Wage Protection System.

This article was written with help from AI. The script was tested on the sample files above, and the rules were checked against the bank guides listed.

來源:DEV Community · dev.to