b2b-audit-cli 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- b2b_audit_cli-1.0.0/LICENSE +21 -0
- b2b_audit_cli-1.0.0/PKG-INFO +21 -0
- b2b_audit_cli-1.0.0/README.md +11 -0
- b2b_audit_cli-1.0.0/b2b_audit_cli/__init__.py +20 -0
- b2b_audit_cli-1.0.0/b2b_audit_cli/cli.py +124 -0
- b2b_audit_cli-1.0.0/b2b_audit_cli/validators.py +315 -0
- b2b_audit_cli-1.0.0/pyproject.toml +35 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 B2B Compliance Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: b2b-audit-cli
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Brazilian B2B compliance CLI (CNPJ, FEBRABAN Boleto, ANS TISS XML, NCM LC 214, and Pro Enterprise Sync).
|
|
5
|
+
Author: B2B Compliance Labs
|
|
6
|
+
Author-email: engineering@b2bcompliance.local
|
|
7
|
+
License: MIT
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# b2b-audit-cli
|
|
12
|
+
|
|
13
|
+
Official Brazilian B2B Regulatory & Financial Compliance CLI (`v1.0.0`).
|
|
14
|
+
|
|
15
|
+
## Commands
|
|
16
|
+
|
|
17
|
+
- `b2b-audit cnpj <value> [--json]`: Mathematical CNPJ check-digit verification and formatting.
|
|
18
|
+
- `b2b-audit boleto <line> [--json]`: FEBRABAN bank (47-digit) & utility (48-digit) boleto Mod 10 / Mod 11 validation.
|
|
19
|
+
- `b2b-audit tiss <file_or_xml> [--json]`: ANS TISS XML structural parser and required-tag auditor.
|
|
20
|
+
- `b2b-audit ncm <code8> [--json]`: 8-digit NCM validation and LC 214/2025 IBS/CBS tax regime classification.
|
|
21
|
+
- `b2b-audit pro-sync [--rail auto|rapidapi|apify] [--batch <items>] [--json]`: Enterprise batch sync using `RAPIDAPI_API_KEY` or `APIFY_API_TOKEN`.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# b2b-audit-cli
|
|
2
|
+
|
|
3
|
+
Official Brazilian B2B Regulatory & Financial Compliance CLI (`v1.0.0`).
|
|
4
|
+
|
|
5
|
+
## Commands
|
|
6
|
+
|
|
7
|
+
- `b2b-audit cnpj <value> [--json]`: Mathematical CNPJ check-digit verification and formatting.
|
|
8
|
+
- `b2b-audit boleto <line> [--json]`: FEBRABAN bank (47-digit) & utility (48-digit) boleto Mod 10 / Mod 11 validation.
|
|
9
|
+
- `b2b-audit tiss <file_or_xml> [--json]`: ANS TISS XML structural parser and required-tag auditor.
|
|
10
|
+
- `b2b-audit ncm <code8> [--json]`: 8-digit NCM validation and LC 214/2025 IBS/CBS tax regime classification.
|
|
11
|
+
- `b2b-audit pro-sync [--rail auto|rapidapi|apify] [--batch <items>] [--json]`: Enterprise batch sync using `RAPIDAPI_API_KEY` or `APIFY_API_TOKEN`.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""b2b_audit_cli package."""
|
|
2
|
+
|
|
3
|
+
__version__ = "1.0.0"
|
|
4
|
+
|
|
5
|
+
from .validators import (
|
|
6
|
+
audit_boleto,
|
|
7
|
+
audit_cnpj,
|
|
8
|
+
audit_ncm_lc214,
|
|
9
|
+
audit_tiss_xml,
|
|
10
|
+
sync_pro_enterprise,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"__version__",
|
|
15
|
+
"audit_cnpj",
|
|
16
|
+
"audit_boleto",
|
|
17
|
+
"audit_tiss_xml",
|
|
18
|
+
"audit_ncm_lc214",
|
|
19
|
+
"sync_pro_enterprise",
|
|
20
|
+
]
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Command-line interface for b2b-audit-cli."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Sequence
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .validators import (
|
|
15
|
+
audit_boleto,
|
|
16
|
+
audit_cnpj,
|
|
17
|
+
audit_ncm_lc214,
|
|
18
|
+
audit_tiss_xml,
|
|
19
|
+
sync_pro_enterprise,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
LOGGER = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _add_json_flag(parser: argparse.ArgumentParser, dest: str = "sub_json") -> None:
|
|
26
|
+
parser.add_argument("--json", action="store_true", dest=dest, help="Emit JSON output")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
30
|
+
parser = argparse.ArgumentParser(
|
|
31
|
+
prog="b2b-audit",
|
|
32
|
+
description="Brazilian B2B Regulatory & Financial Compliance CLI",
|
|
33
|
+
)
|
|
34
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
35
|
+
_add_json_flag(parser, dest="global_json")
|
|
36
|
+
|
|
37
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
38
|
+
|
|
39
|
+
p_cnpj = subparsers.add_parser("cnpj", help="Validate and format a Brazilian CNPJ")
|
|
40
|
+
p_cnpj.add_argument("value", help="CNPJ string (formatted or digits)")
|
|
41
|
+
_add_json_flag(p_cnpj)
|
|
42
|
+
|
|
43
|
+
p_boleto = subparsers.add_parser("boleto", help="Validate FEBRABAN boleto digitable line")
|
|
44
|
+
p_boleto.add_argument("line", help="47-digit or 48-digit boleto line")
|
|
45
|
+
_add_json_flag(p_boleto)
|
|
46
|
+
|
|
47
|
+
p_tiss = subparsers.add_parser("tiss", help="Audit ANS TISS XML structure")
|
|
48
|
+
p_tiss.add_argument("source", help="Path to TISS XML file or inline XML string")
|
|
49
|
+
_add_json_flag(p_tiss)
|
|
50
|
+
|
|
51
|
+
p_ncm = subparsers.add_parser("ncm", help="Validate 8-digit NCM and classify LC 214 rate")
|
|
52
|
+
p_ncm.add_argument("code", help="8-digit NCM code")
|
|
53
|
+
_add_json_flag(p_ncm)
|
|
54
|
+
|
|
55
|
+
p_sync = subparsers.add_parser("pro-sync", help="Enterprise Pro batch sync via RapidAPI/Apify")
|
|
56
|
+
p_sync.add_argument("--rail", choices=["auto", "rapidapi", "apify"], default="auto")
|
|
57
|
+
p_sync.add_argument("--item", action="append", default=[], help="Item to sync (repeatable)")
|
|
58
|
+
p_sync.add_argument("--batch-file", type=Path, default=None, help="Path to newline-delimited batch items")
|
|
59
|
+
_add_json_flag(p_sync)
|
|
60
|
+
|
|
61
|
+
return parser
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _emit(result: dict, as_json: bool) -> None:
|
|
65
|
+
if as_json:
|
|
66
|
+
print(json.dumps(result, ensure_ascii=False))
|
|
67
|
+
return
|
|
68
|
+
status = "VALID" if result.get("valid", result.get("ok", False)) else "INVALID"
|
|
69
|
+
print(f"[{status}] {json.dumps(result, ensure_ascii=False)}")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
73
|
+
logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
|
|
74
|
+
parser = build_parser()
|
|
75
|
+
args = parser.parse_args(argv)
|
|
76
|
+
as_json = bool(getattr(args, "global_json", False) or getattr(args, "sub_json", False))
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
if args.command == "cnpj":
|
|
80
|
+
res = audit_cnpj(args.value)
|
|
81
|
+
_emit(res, as_json)
|
|
82
|
+
return 0 if res["valid"] else 1
|
|
83
|
+
|
|
84
|
+
if args.command == "boleto":
|
|
85
|
+
res = audit_boleto(args.line)
|
|
86
|
+
_emit(res, as_json)
|
|
87
|
+
return 0 if res["valid"] else 1
|
|
88
|
+
|
|
89
|
+
if args.command == "tiss":
|
|
90
|
+
res = audit_tiss_xml(args.source)
|
|
91
|
+
_emit(res, as_json)
|
|
92
|
+
return 0 if res["valid"] else 1
|
|
93
|
+
|
|
94
|
+
if args.command == "ncm":
|
|
95
|
+
res = audit_ncm_lc214(args.code)
|
|
96
|
+
_emit(res, as_json)
|
|
97
|
+
return 0 if res["valid"] else 1
|
|
98
|
+
|
|
99
|
+
if args.command == "pro-sync":
|
|
100
|
+
items = list(args.item)
|
|
101
|
+
if args.batch_file is not None:
|
|
102
|
+
if not args.batch_file.is_file():
|
|
103
|
+
res = {"ok": False, "error": f"Batch file not found: {args.batch_file}"}
|
|
104
|
+
_emit(res, as_json)
|
|
105
|
+
return 1
|
|
106
|
+
items.extend(
|
|
107
|
+
line.strip()
|
|
108
|
+
for line in args.batch_file.read_text(encoding="utf-8").splitlines()
|
|
109
|
+
if line.strip()
|
|
110
|
+
)
|
|
111
|
+
res = asyncio.run(sync_pro_enterprise(items, rail=args.rail))
|
|
112
|
+
_emit(res, as_json)
|
|
113
|
+
return 0 if res.get("ok") else 1
|
|
114
|
+
|
|
115
|
+
parser.print_help()
|
|
116
|
+
return 2
|
|
117
|
+
except Exception as exc:
|
|
118
|
+
LOGGER.error("Unexpected CLI failure: %s", exc)
|
|
119
|
+
_emit({"ok": False, "error": str(exc)}, as_json)
|
|
120
|
+
return 1
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
sys.exit(main())
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"""Deterministic Brazilian regulatory validators and Pro enterprise sync."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
import xml.etree.ElementTree as ET
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Awaitable, Callable
|
|
15
|
+
|
|
16
|
+
LOGGER = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
STANDARD_IBS_CBS_RATE = 26.5
|
|
19
|
+
LC214_ZERO_RATE_CHAPTERS = {"02", "04", "07", "08", "10", "11"}
|
|
20
|
+
LC214_REDUCED_60_CHAPTERS = {"30", "90"}
|
|
21
|
+
LC214_SELECTIVE_TAX_CHAPTERS = {"22", "24", "87"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _digits_only(value: str | None) -> str:
|
|
25
|
+
return re.sub(r"\D+", "", str(value or ""))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def audit_cnpj(value: str | None) -> dict[str, Any]:
|
|
29
|
+
"""Validate and format a Brazilian CNPJ using official check digits."""
|
|
30
|
+
digits = _digits_only(value)
|
|
31
|
+
if len(digits) != 14 or len(set(digits)) == 1:
|
|
32
|
+
return {
|
|
33
|
+
"valid": False,
|
|
34
|
+
"digits": digits,
|
|
35
|
+
"formatted": None,
|
|
36
|
+
"reason": "CNPJ must have 14 non-identical digits",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
def _calc_dv(base: str, weights: list[int]) -> int:
|
|
40
|
+
total = sum(int(ch) * w for ch, w in zip(base, weights))
|
|
41
|
+
rem = total % 11
|
|
42
|
+
return 0 if rem < 2 else 11 - rem
|
|
43
|
+
|
|
44
|
+
w1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
|
|
45
|
+
w2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
|
|
46
|
+
|
|
47
|
+
dv1 = _calc_dv(digits[:12], w1)
|
|
48
|
+
if dv1 != int(digits[12]):
|
|
49
|
+
return {"valid": False, "digits": digits, "formatted": None, "reason": "First check digit mismatch"}
|
|
50
|
+
|
|
51
|
+
dv2 = _calc_dv(digits[:13], w2)
|
|
52
|
+
if dv2 != int(digits[13]):
|
|
53
|
+
return {"valid": False, "digits": digits, "formatted": None, "reason": "Second check digit mismatch"}
|
|
54
|
+
|
|
55
|
+
formatted = f"{digits[:2]}.{digits[2:5]}.{digits[5:8]}/{digits[8:12]}-{digits[12:]}"
|
|
56
|
+
return {"valid": True, "digits": digits, "formatted": formatted, "reason": "OK"}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _mod10(block: str) -> int:
|
|
60
|
+
total = 0
|
|
61
|
+
weight = 2
|
|
62
|
+
for ch in reversed(block):
|
|
63
|
+
prod = int(ch) * weight
|
|
64
|
+
total += (prod // 10) + (prod % 10)
|
|
65
|
+
weight = 1 if weight == 2 else 2
|
|
66
|
+
return (10 - (total % 10)) % 10
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _mod11_bank(block: str) -> int:
|
|
70
|
+
total = 0
|
|
71
|
+
weight = 2
|
|
72
|
+
for ch in reversed(block):
|
|
73
|
+
total += int(ch) * weight
|
|
74
|
+
weight = 2 if weight == 9 else weight + 1
|
|
75
|
+
dv = 11 - (total % 11)
|
|
76
|
+
return 1 if dv in (0, 10, 11) else dv
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _mod11_utility(block: str) -> int:
|
|
80
|
+
total = 0
|
|
81
|
+
weight = 2
|
|
82
|
+
for ch in reversed(block):
|
|
83
|
+
total += int(ch) * weight
|
|
84
|
+
weight = 2 if weight == 9 else weight + 1
|
|
85
|
+
rem = total % 11
|
|
86
|
+
if rem in (0, 1):
|
|
87
|
+
return 0
|
|
88
|
+
if rem == 10:
|
|
89
|
+
return 1
|
|
90
|
+
return 11 - rem
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def audit_boleto(line: str | None) -> dict[str, Any]:
|
|
94
|
+
"""Validate FEBRABAN bank (47 digits) or utility (48 digits) boleto digitable line."""
|
|
95
|
+
digits = _digits_only(line)
|
|
96
|
+
if len(digits) == 47:
|
|
97
|
+
errors: list[str] = []
|
|
98
|
+
fields = [
|
|
99
|
+
("field_1", digits[0:9], int(digits[9])),
|
|
100
|
+
("field_2", digits[10:20], int(digits[20])),
|
|
101
|
+
("field_3", digits[21:31], int(digits[31])),
|
|
102
|
+
]
|
|
103
|
+
for label, payload, expected_dv in fields:
|
|
104
|
+
if _mod10(payload) != expected_dv:
|
|
105
|
+
errors.append(f"{label} Mod-10 check digit mismatch")
|
|
106
|
+
|
|
107
|
+
barcode = digits[0:4] + digits[32] + digits[33:47] + digits[4:9] + digits[10:20] + digits[21:31]
|
|
108
|
+
dv_general = int(barcode[4])
|
|
109
|
+
if _mod11_bank(barcode[:4] + barcode[5:]) != dv_general:
|
|
110
|
+
errors.append("General barcode Mod-11 check digit mismatch")
|
|
111
|
+
|
|
112
|
+
amount_cents = int(digits[37:47])
|
|
113
|
+
return {
|
|
114
|
+
"valid": len(errors) == 0,
|
|
115
|
+
"kind": "bancario_47",
|
|
116
|
+
"bank_code": digits[:3],
|
|
117
|
+
"currency_code": digits[3],
|
|
118
|
+
"amount_brl": round(amount_cents / 100.0, 2),
|
|
119
|
+
"barcode": barcode,
|
|
120
|
+
"errors": errors,
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if len(digits) == 48 and digits.startswith("8"):
|
|
124
|
+
errors = []
|
|
125
|
+
currency_id = int(digits[2])
|
|
126
|
+
calc_fn = _mod10 if currency_id in (6, 7) else _mod11_utility if currency_id in (8, 9) else None
|
|
127
|
+
if calc_fn is None:
|
|
128
|
+
return {
|
|
129
|
+
"valid": False,
|
|
130
|
+
"kind": "arrecadacao_48",
|
|
131
|
+
"errors": [f"Unsupported currency/module identifier: {currency_id}"],
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
blocks = []
|
|
135
|
+
for idx in range(4):
|
|
136
|
+
start = idx * 12
|
|
137
|
+
block = digits[start : start + 11]
|
|
138
|
+
expected_dv = int(digits[start + 11])
|
|
139
|
+
blocks.append(block)
|
|
140
|
+
if calc_fn(block) != expected_dv:
|
|
141
|
+
errors.append(f"block_{idx + 1} check digit mismatch")
|
|
142
|
+
|
|
143
|
+
barcode = "".join(blocks)
|
|
144
|
+
if calc_fn(barcode[:3] + barcode[4:]) != int(barcode[3]):
|
|
145
|
+
errors.append("General utility barcode check digit mismatch")
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
"valid": len(errors) == 0,
|
|
149
|
+
"kind": "arrecadacao_48",
|
|
150
|
+
"segment_id": digits[1],
|
|
151
|
+
"currency_id": currency_id,
|
|
152
|
+
"barcode": barcode,
|
|
153
|
+
"errors": errors,
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
"valid": False,
|
|
158
|
+
"kind": "unknown",
|
|
159
|
+
"digits_length": len(digits),
|
|
160
|
+
"errors": ["Expected 47-digit bank boleto or 48-digit utility boleto starting with 8"],
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _strip_ns(tag: str) -> str:
|
|
165
|
+
return tag.split("}", 1)[-1] if "}" in tag else tag
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def audit_tiss_xml(source: str | None) -> dict[str, Any]:
|
|
169
|
+
"""Parse and audit ANS TISS XML structure and required tags."""
|
|
170
|
+
raw_input = str(source or "").strip()
|
|
171
|
+
if not raw_input:
|
|
172
|
+
return {"valid": False, "score": 0, "errors": ["Empty TISS XML input"], "tags_found": []}
|
|
173
|
+
|
|
174
|
+
xml_text = raw_input
|
|
175
|
+
source_type = "inline"
|
|
176
|
+
if not raw_input.startswith("<"):
|
|
177
|
+
path = Path(raw_input)
|
|
178
|
+
if not path.is_file():
|
|
179
|
+
return {
|
|
180
|
+
"valid": False,
|
|
181
|
+
"score": 0,
|
|
182
|
+
"errors": [f"TISS XML file not found or invalid XML string: {raw_input}"],
|
|
183
|
+
"tags_found": [],
|
|
184
|
+
}
|
|
185
|
+
try:
|
|
186
|
+
xml_text = path.read_text(encoding="utf-8")
|
|
187
|
+
source_type = "file"
|
|
188
|
+
except OSError as exc:
|
|
189
|
+
LOGGER.error("Failed reading TISS XML file %s: %s", path, exc)
|
|
190
|
+
return {"valid": False, "score": 0, "errors": [f"Cannot read file: {exc}"], "tags_found": []}
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
root = ET.fromstring(xml_text)
|
|
194
|
+
except ET.ParseError as exc:
|
|
195
|
+
return {"valid": False, "score": 0, "errors": [f"Malformed XML: {exc}"], "tags_found": []}
|
|
196
|
+
|
|
197
|
+
tags = {_strip_ns(el.tag) for el in root.iter()}
|
|
198
|
+
required = ["mensagemTISS", "cabecalho", "identificacaoTransacao", "epilogo", "hash"]
|
|
199
|
+
errors = [f"Missing required TISS tag: {t}" for t in required if t not in tags]
|
|
200
|
+
if "prestadorParaOperadora" not in tags and "operadoraParaPrestador" not in tags:
|
|
201
|
+
errors.append("Missing prestadorParaOperadora or operadoraParaPrestador block")
|
|
202
|
+
|
|
203
|
+
score = max(0, 100 - len(errors) * 16)
|
|
204
|
+
return {
|
|
205
|
+
"valid": len(errors) == 0,
|
|
206
|
+
"source_type": source_type,
|
|
207
|
+
"root_tag": _strip_ns(root.tag),
|
|
208
|
+
"score": score,
|
|
209
|
+
"errors": errors,
|
|
210
|
+
"tags_found": sorted(tags),
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def audit_ncm_lc214(code: str | None) -> dict[str, Any]:
|
|
215
|
+
"""Validate 8-digit NCM code and classify IBS/CBS tax regime under LC 214/2025."""
|
|
216
|
+
digits = _digits_only(code)
|
|
217
|
+
if len(digits) != 8 or digits == "00000000":
|
|
218
|
+
return {
|
|
219
|
+
"valid": False,
|
|
220
|
+
"ncm": digits,
|
|
221
|
+
"formatted": None,
|
|
222
|
+
"reason": "NCM must contain exactly 8 digits and cannot be all zeros",
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
chapter = digits[:2]
|
|
226
|
+
heading = digits[:4]
|
|
227
|
+
subheading = digits[:6]
|
|
228
|
+
formatted = f"{digits[:4]}.{digits[4:6]}.{digits[6:]}"
|
|
229
|
+
|
|
230
|
+
if chapter in LC214_ZERO_RATE_CHAPTERS:
|
|
231
|
+
reduction = 100
|
|
232
|
+
selective = False
|
|
233
|
+
regime = "Cesta Basica Nacional / Aliquota Zero (LC 214)"
|
|
234
|
+
elif chapter in LC214_REDUCED_60_CHAPTERS:
|
|
235
|
+
reduction = 60
|
|
236
|
+
selective = False
|
|
237
|
+
regime = "Reducao 60% Saude/Dispositivos (LC 214)"
|
|
238
|
+
elif chapter in LC214_SELECTIVE_TAX_CHAPTERS:
|
|
239
|
+
reduction = 0
|
|
240
|
+
selective = True
|
|
241
|
+
regime = "Aliquota Padrao + Imposto Seletivo (LC 214)"
|
|
242
|
+
else:
|
|
243
|
+
reduction = 0
|
|
244
|
+
selective = False
|
|
245
|
+
regime = "Aliquota Padrao IBS/CBS (LC 214)"
|
|
246
|
+
|
|
247
|
+
effective_rate = round(STANDARD_IBS_CBS_RATE * (1.0 - reduction / 100.0), 2)
|
|
248
|
+
return {
|
|
249
|
+
"valid": True,
|
|
250
|
+
"ncm": digits,
|
|
251
|
+
"formatted": formatted,
|
|
252
|
+
"chapter": chapter,
|
|
253
|
+
"heading": heading,
|
|
254
|
+
"subheading": subheading,
|
|
255
|
+
"lc214_regime": regime,
|
|
256
|
+
"reduction_pct": reduction,
|
|
257
|
+
"selective_tax_applicable": selective,
|
|
258
|
+
"effective_reference_rate_pct": effective_rate,
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _http_post_json(url: str, headers: dict[str, str], payload: dict[str, Any]) -> dict[str, Any]:
|
|
263
|
+
data = json.dumps(payload).encode("utf-8")
|
|
264
|
+
req = urllib.request.Request(url=url, data=data, headers=headers, method="POST")
|
|
265
|
+
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
266
|
+
body = resp.read().decode("utf-8")
|
|
267
|
+
return {"status_code": resp.status, "body": json.loads(body) if body else {}}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
async def sync_pro_enterprise(
|
|
271
|
+
batch_items: list[str],
|
|
272
|
+
rail: str = "auto",
|
|
273
|
+
transport: Callable[[str, dict[str, str], dict[str, Any]], Awaitable[dict[str, Any]] | dict[str, Any]] | None = None,
|
|
274
|
+
) -> dict[str, Any]:
|
|
275
|
+
"""Synchronize enterprise compliance batch using RapidAPI or Apify credentials."""
|
|
276
|
+
rapid_key = os.getenv("RAPIDAPI_API_KEY", "").strip()
|
|
277
|
+
apify_token = os.getenv("APIFY_API_TOKEN", "").strip()
|
|
278
|
+
|
|
279
|
+
chosen_rail = rail.lower().strip()
|
|
280
|
+
if chosen_rail == "auto":
|
|
281
|
+
if rapid_key:
|
|
282
|
+
chosen_rail = "rapidapi"
|
|
283
|
+
elif apify_token:
|
|
284
|
+
chosen_rail = "apify"
|
|
285
|
+
else:
|
|
286
|
+
return {
|
|
287
|
+
"ok": False,
|
|
288
|
+
"rail": "none",
|
|
289
|
+
"error": "Missing RAPIDAPI_API_KEY or APIFY_API_TOKEN environment variable",
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if chosen_rail == "rapidapi":
|
|
293
|
+
if not rapid_key:
|
|
294
|
+
return {"ok": False, "rail": "rapidapi", "error": "RAPIDAPI_API_KEY is not configured"}
|
|
295
|
+
url = "https://b2b-compliance-auditor.p.rapidapi.com/v1/batch-sync"
|
|
296
|
+
headers = {"Content-Type": "application/json", "X-RapidAPI-Key": rapid_key}
|
|
297
|
+
elif chosen_rail == "apify":
|
|
298
|
+
if not apify_token:
|
|
299
|
+
return {"ok": False, "rail": "apify", "error": "APIFY_API_TOKEN is not configured"}
|
|
300
|
+
url = "https://api.apify.com/v2/acts/b2b-compliance~auditor/runs"
|
|
301
|
+
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {apify_token}"}
|
|
302
|
+
else:
|
|
303
|
+
return {"ok": False, "rail": chosen_rail, "error": f"Unsupported rail: {chosen_rail}"}
|
|
304
|
+
|
|
305
|
+
payload = {"items": batch_items, "count": len(batch_items)}
|
|
306
|
+
try:
|
|
307
|
+
if transport is not None:
|
|
308
|
+
maybe = transport(url, headers, payload)
|
|
309
|
+
remote = await maybe if asyncio.iscoroutine(maybe) else maybe
|
|
310
|
+
else:
|
|
311
|
+
remote = await asyncio.to_thread(_http_post_json, url, headers, payload)
|
|
312
|
+
return {"ok": True, "rail": chosen_rail, "synced_count": len(batch_items), "remote": remote}
|
|
313
|
+
except (urllib.error.URLError, TimeoutError, ValueError, RuntimeError) as exc:
|
|
314
|
+
LOGGER.error("Pro enterprise sync failed on rail %s: %s", chosen_rail, exc)
|
|
315
|
+
return {"ok": False, "rail": chosen_rail, "error": str(exc)}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "b2b-audit-cli"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Brazilian B2B compliance CLI (CNPJ, FEBRABAN Boleto, ANS TISS XML, NCM LC 214, and Pro Enterprise Sync)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "B2B Compliance Labs", email = "engineering@b2bcompliance.local" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["cnpj", "boleto", "febraban", "tiss", "ans", "ncm", "lc214", "compliance", "cli"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 5 - Production/Stable",
|
|
18
|
+
"Environment :: Console",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
21
|
+
"License :: OSI Approved :: MIT License",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.10",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Topic :: Office/Business :: Financial",
|
|
27
|
+
"Topic :: Security"
|
|
28
|
+
]
|
|
29
|
+
dependencies = []
|
|
30
|
+
|
|
31
|
+
[project.scripts]
|
|
32
|
+
b2b-audit = "b2b_audit_cli.cli:main"
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
include = ["b2b_audit_cli*"]
|