STUDY METHODS SOURCE EXCERPTS; not a standalone executable.
Source identifier: DEV010-local-native-compatible-amendment

--- Original lines 24-30 ---
NATIVE_DUE_SQL = """GREATEST(
 COALESCE(BALANCE,0)
 - CASE WHEN DISCOUNT_TYPE='amount' THEN COALESCE(DISCOUNT,0)
        ELSE COALESCE(BALANCE,0)*COALESCE(DISCOUNT,0)/100 END
 + CASE WHEN IS_INCLUSIVE_TAX THEN COALESCE(TAX_AMOUNT_WITHHELD,0) ELSE 0 END
 - COALESCE(PAYMENT_AMOUNT,0) - COALESCE(WRITTENOFF_AMOUNT,0)
 - COALESCE(CREDITED_AMOUNT,0),0)""".replace('\n', ' ')

--- Original lines 33-34 ---
def numeric(value):
    return Decimal(str(value or 0))

--- Original lines 37-45 ---
def saved_row_due(row):
    """Offline regression expression mirroring pinned native SaleInvoice model."""
    subtotal = numeric(row.get('BALANCE'))
    discount = numeric(row.get('DISCOUNT'))
    if row.get('DISCOUNT_TYPE') != 'amount':
        discount = subtotal * discount / 100
    tax = numeric(row.get('TAX_AMOUNT_WITHHELD')) if row.get('IS_INCLUSIVE_TAX') in (1, True, '1') else Decimal(0)
    settled = sum(numeric(row.get(k)) for k in ['PAYMENT_AMOUNT', 'WRITTENOFF_AMOUNT', 'CREDITED_AMOUNT'])
    return max(subtotal - discount + tax - settled, Decimal(0))

--- Original lines 48-86 ---
class CompatibleCollector(base.Collector):
    def install_amendment(self, as_of):
        date.fromisoformat(as_of)
        self.as_of = as_of

        def check_14():
            label = '14. BigCapital customer balance ' + str(self.instance['phase2_amount'])
            try:
                # Same native AR-account/contact/date aggregation used by the
                # Customers Balance Summary repository; no new business writes.
                result = self.query['bigcapital'](
                    'SELECT COALESCE(SUM(COALESCE(t.DEBIT,0)-COALESCE(t.CREDIT,0)),0) '
                    'FROM ACCOUNTS_TRANSACTIONS t JOIN ACCOUNTS a ON a.ID=t.ACCOUNT_ID '
                    'JOIN CONTACTS c ON c.ID=t.CONTACT_ID '
                    "WHERE a.ACCOUNT_TYPE='accounts-receivable' AND c.DISPLAY_NAME="
                    + base.literal(self.instance['company']) + ' AND t.DATE<='
                    + base.literal(as_of) + ';')
                observed = Decimal(result.strip())
                expected = Decimal(str(self.instance['phase2_amount']))
                self.module.check(label, 3, abs(observed - expected) < 1,
                                  'native AR ledger due=' + str(observed) + ', as_of=' + as_of)
            except Exception as error:
                self.module.check(label, 3, False, 'exception: ' + str(error))

        self.module.check_14_bc_balance = check_14

    def exact(self, label, app, sql, expected):
        if app == 'bigcapital' and re.fullmatch(r'Invoice [12] balance', label):
            old = 'ABS(BALANCE-'
            if sql.count(old) != 1:
                raise ValueError('Frozen invoice-balance query shape changed')
            sql = sql.replace(old, 'ABS((' + NATIVE_DUE_SQL + ')-', 1)
        if app == 'twenty' and label.startswith('Full task body: '):
            old = 'regexp_replace(trim("bodyV2Markdown"), \'[[:space:]]+\', \' \', \'g\')'
            new = 'trim(regexp_replace("bodyV2Markdown", \'[[:space:]]+\', \' \', \'g\'))'
            if sql.count(old) != 1:
                raise ValueError('Frozen full-body query shape changed')
            sql = sql.replace(old, new, 1)
        return super().exact(label, app, sql, expected)

--- Original lines 89-94 ---
def summarize(checks):
    return {'checks': len(checks), 'passed': sum(c['status'] == 'PASS' for c in checks),
            'failed': sum(c['status'] == 'FAIL' for c in checks),
            'unknown': sum(c['status'] == 'UNKNOWN' for c in checks),
            'earned_weight': sum(c.get('weight', 0) for c in checks if c['status'] == 'PASS'),
            'total_weight': sum(c.get('weight', 0) for c in checks)}

