Automate Excel to ERP Sync with Python and Webhooks for SMEs
A production engineering blueprint to replace fragile Excel-to-ERP copy-paste across Odoo, Sage, Dolibarr, Pennylane, and Shopify with a deterministic Python pipeline: Polars/openpyxl ingestion, Pydantic v2 validation, SHA-256 idempotency keys, HMAC-SHA256 webhooks, a Dead-Letter Queue, and daily SQL reconciliation.
Direct answer
To replace manual Excel-to-ERP copy-paste in an SME without duplicate invoices or silent drift, build a deterministic Python pipeline: snapshot network spreadsheets before parsing with Polars or openpyxl, validate every row with Pydantic v2, hash canonical business fields into a SHA-256 idempotency key, verify HMAC-SHA256 webhooks with replay checks, isolate errors in a Dead-Letter Queue, and run daily SQL reconciliation.
1. Why manual Excel to ERP copy-paste breaks SME operations
Across 10-to-150-person SMEs, the real operational backbone is rarely a single unified system. Sales reps quote in spreadsheets, warehouse staff export stock movements as CSV files, e-commerce orders land in Shopify, and finance teams re-key totals into Odoo, Sage, Dolibarr, or Pennylane at the end of every week. At first glance, manually copying 40 orders or 250 stock lines feels cheaper than building an integration. In production, the hidden operational tax compounds fast.
Empirical audits on SME back-offices consistently show three recurring failure modes once daily volume crosses 30 documents:
- Invisible labor burn: An operations or accounting clerk spending 35 minutes every morning exporting, cleaning columns, fixing broken accents, and re-uploading CSV files loses roughly 135 hours per year on a single repetitive bridge, before counting month-end reconciliation fire drills.
- Silent numeric and identifier corruption: Opening a CSV in desktop Excel automatically strips leading zeros from French SIREN numbers (
012345678becomes12345678), converts long EAN/SKU codes into scientific notation (3.76012E+12), and flips ambiguous dates betweenDD/MM/YYYYandMM/DD/YYYY. - Duplicate postings and credit-note churn: When a manual ERP import times out at row 180 of 300, the operator rarely knows which lines committed. Re-uploading the whole workbook creates duplicate customer invoices, distorts inventory counts, and forces accounting teams to issue sequential credit notes to keep their Factur-X EN 16931 and 18-column DGFiP FEC ledger balanced.
The goal of an engineering-grade bridge is not merely speed; it is determinism. Running the exact same workbook twice, recovering from a mid-batch network drop, or receiving the same Shopify or ERP webhook three times must always produce the exact same accounting state with zero duplicate records and a verifiable audit trail.
2. Quantified comparison: Manual Excel vs Zapier/Make vs Idempotent Python
When SMEs outgrow manual copy-paste, they usually evaluate two paths: hosted no-code workflow tools (Zapier, Make) or a self-hosted deterministic Python service (or hybrid n8n + Python worker). The comparison table below models a typical wholesale or B2B SME synchronizing 50,000 rows per month across order exports, stock updates, and billing status webhooks.
| Engineering criterion | Manual Excel copy-paste / CSV upload | Hosted no-code SaaS (Zapier / Make) | Deterministic Python + SQLite/Postgres + Webhooks |
|---|---|---|---|
| Annual recurring cost (50k rows/month) | 0 EUR license, but 120 to 220 staff hours/year (~4,500 to 8,500 EUR loaded cost) | 1,800 to 6,000+ EUR/year in per-task / per-operation tiers as row volume scales | 120 to 960 EUR/year European VPS + optional monitoring (zero per-row tax) |
| Throughput on 25,000-row workbook | Manual split into 500-row batches; 25 to 60 minutes with high error rate | Frequent timeouts, task quota spikes, and fragile iterator pagination | Under 1.2 seconds parsing via Polars Rust calamine; rate-limited async upsert |
| Idempotency on HTTP 429 / 502 retries | None; partial upload retry causes duplicate orders or skipped lines | Weak; linear retry often re-triggers entire scenario without business hash ledger | Strict SHA-256 business key + local sync_ledger + Idempotency-Key header |
| Encoding, dates & EU decimal control | Broken by desktop Excel auto-formatting (CP1252, scientific notation, date flips) | Limited regex/formatter nodes; floats introduce 0.01 EUR rounding drift | Explicit utf-8-sig/cp1252 decode, Decimal cent math, strict Pydantic v2 rules |
| Error handling & Dead-Letter Queue | Entire import aborts or silently drops bad rows | Generic error email; hard to replay only the 7 bad lines out of 2,000 | Row-level SQL sync_dlq quarantine; valid 1,993 rows commit, 7 replay cleanly |
| Auditability & financial close | Zero trace of who edited which cell before upload | 30-to-60-day opaque execution logs locked inside vendor SaaS | Immutable SQL reconciliation ledger proving delta_cents = 0 every evening |
No-code platforms still make sense for low-volume glue (sending a Slack message when a web form submits). As soon as financial documents, ERP stock quantities, or B2B order lines cross the wire, a small version-controlled Python service pays for itself within weeks and removes every per-task ceiling.
3. Step 1: Safe Excel and CSV ingestion (Polars, openpyxl, SMB locks, encodings)
Every reliable Excel-to-ERP bridge begins with defensive ingestion. Two production rules eliminate 80% of recurring cron crashes before a single API call is fired. First, never read directly from a shared SMB network drive or synced OneDrive/SharePoint folder while users may have the file open. Ignore Microsoft Office lock artifacts starting with ~$, verify that the file is not still being written, and copy it atomically into an isolated temporary directory using shutil.copy2.
Second, never trust automatic type inference on business identifiers. According to the official Polars Python API documentation for pl.read_excel, Polars defaults to the Rust-based calamine parser (which handles .xlsx, .xlsb, and .xls dramatically faster than pure-Python parsers) and supports explicit schema_overrides plus infer_schema_length=None. Forcing columns such as order_ref, customer_siren, sku, unit_price_ht, and order_date to pl.String ensures that leading zeros stay intact and raw strings reach your validator unmodified.
For legacy CSV exports emitted by French ERP suites such as Sage 100, Dolibarr, or Pennylane, files frequently arrive in Windows CP1252 with semicolon delimiters (;) or UTF-8 with a Byte Order Mark (utf-8-sig). Detecting encoding explicitly in descending strictness (utf-8-sig before cp1252) prevents mojibake like Crédit or silent column-name mismatches caused by an invisible \ufeff prefix on the first header.
from __future__ import annotations
import shutil
import tempfile
from pathlib import Path
import openpyxl
import polars as pl
def read_excel_snapshot(src_path: Path, sheet_name: str = "Orders") -> list[dict[str, object]]:
"""Copy network Excel file atomically before reading so Windows/SMB locks never fail the run."""
if src_path.name.startswith("~$"):
raise ValueError(f"Ignoring Office lock file: {src_path.name}")
with tempfile.TemporaryDirectory(prefix="erp_sync_") as tmp_dir:
local_copy = Path(tmp_dir) / src_path.name
shutil.copy2(src_path, local_copy)
if local_copy.suffix.lower() in {".xlsx", ".xlsb", ".xls"}:
# Polars uses the Rust calamine engine by default; override IDs as Utf8 to keep leading zeros.
df = pl.read_excel(
source=local_copy,
sheet_name=sheet_name,
engine="calamine",
schema_overrides={
"order_ref": pl.String,
"customer_siren": pl.String,
"sku": pl.String,
"unit_price_ht": pl.String,
"order_date": pl.String,
},
infer_schema_length=None,
)
return df.to_dicts()
# Fallback for CSV exports from Sage, Dolibarr, or Pennylane (UTF-8 BOM vs CP1252)
raw_bytes = local_copy.read_bytes()
for enc in ("utf-8-sig", "cp1252", "latin-1"):
try:
text = raw_bytes.decode(enc)
break
except UnicodeDecodeError:
continue
else:
raise ValueError(f"Unsupported CSV encoding for {src_path.name}")
sep = ";" if text.splitlines()[0].count(";") >= text.splitlines()[0].count(",") else ","
df = pl.read_csv(
text.encode("utf-8"),
separator=sep,
infer_schema_length=0,
truncate_ragged_lines=False,
)
return df.to_dicts()
def read_large_xlsx_streaming(src_path: Path, sheet_name: str = "Orders") -> list[dict[str, object]]:
"""Low-memory fallback using openpyxl read_only + data_only (reads cached formula values)."""
wb = openpyxl.load_workbook(src_path, read_only=True, data_only=True)
try:
ws = wb[sheet_name]
rows_iter = ws.iter_rows(values_only=True)
headers = [str(cell).strip() if cell is not None else "" for cell in next(rows_iter)]
return [dict(zip(headers, row)) for row in rows_iter if any(v is not None for v in row)]
finally:
wb.close()
When working with very wide or heavily styled legacy .xlsx workbooks where you want bounded streaming memory, keep openpyxl.load_workbook(path, read_only=True, data_only=True) as a clean fallback. Always pass data_only=True so openpyxl reads Excel's cached calculated values rather than raw formula strings such as =SUM(D2:D12), and always close the workbook inside a finally block to release OS file handles.
4. Step 2: Pydantic v2 schema validation, SHA-256 keys, and DLQ quarantine
Raw spreadsheet rows must never touch an ERP endpoint directly. Insert a strict validation boundary powered by Pydantic v2 (BaseModel, ConfigDict(extra="forbid", str_strip_whitespace=True), and @field_validator(..., mode="before")). Setting extra="forbid" immediately catches silent schema drift whenever someone inserts or renames a column in a shared Excel template, instead of silently dropping that data on the floor.
Inside the validator layer, enforce four deterministic transformations verified in real SME environments:
- Exact EU/FR decimal parsing into
Decimaland integer cents: Strip non-breaking spaces (\u00a0and narrow no-break space\u202fproduced by French Excel thousands formatting), remove currency labels, determine whether comma or dot is the decimal mark based on rightmost position, and compute line net totals in integer cents withROUND_HALF_UP. Never use binary IEEE-754 floats for money. - Unambiguous date parsing: Accept ISO
YYYY-MM-DD, FrenchDD/MM/YYYY, native Pythondate/datetimeobjects, and Excel 1900 serial integers (origin1899-12-30). Reject unparseable strings into quarantine rather than letting a heuristic library silently swap day and month. - CSV/Excel formula neutralization (OWASP CWE-1236): Reject or sanitize text fields starting with
=,+,-,@, tab, or carriage return before they propagate into downstream accounting CSV exports or BI sheets. - Deterministic SHA-256 idempotency key: Hash a canonical sorted JSON object of the immutable business attributes (
source_system,order_ref,line_index,customer_siren,sku, normalizedquantity,net_cents, ISOorder_date,currency). Even if a user sorts the Excel sheet differently and re-exports it tomorrow, every unchanged line produces the exact same 64-character SHA-256 digest.
from __future__ import annotations
import hashlib
import json
import re
from datetime import date, datetime, timedelta
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
EXCEL_EPOCH = date(1899, 12, 30)
FORMULA_PREFIX_RE = re.compile(r"^[=+\-@\t\r]")
def normalize_decimal_str(raw: Any) -> Decimal:
"""Convert French/EU formatted amounts like '1 250,50 EUR' into exact Decimal."""
if isinstance(raw, Decimal):
return raw
if isinstance(raw, (int, float)):
return Decimal(str(raw))
text = str(raw or "").replace("\u00a0", "").replace("\u202f", "").replace(" ", "")
text = re.sub(r"(?i)(eur|€|usd|\$)", "", text).strip()
if "," in text and "." in text:
# Decide decimal separator by rightmost punctuation (1.250,50 vs 1,250.50)
if text.rfind(",") > text.rfind("."):
text = text.replace(".", "").replace(",", ".")
else:
text = text.replace(",", "")
elif "," in text:
text = text.replace(",", ".")
try:
return Decimal(text)
except InvalidOperation as exc:
raise ValueError(f"Invalid decimal amount: {raw!r}") from exc
def normalize_date_value(raw: Any) -> date:
"""Parse ISO YYYY-MM-DD, French DD/MM/YYYY, datetime objects, or Excel serial dates."""
if isinstance(raw, datetime):
return raw.date()
if isinstance(raw, date):
return raw
if isinstance(raw, (int, float)) and 30000 <= raw <= 70000:
return EXCEL_EPOCH + timedelta(days=int(raw))
text = str(raw or "").strip()
for fmt in ("%Y-%m-%d", "%d/%m/%Y", "%d-%m-%Y", "%Y/%m/%d"):
try:
return datetime.strptime(text, fmt).date()
except ValueError:
continue
raise ValueError(f"Unrecognized date format (expected ISO or DD/MM/YYYY): {raw!r}")
class ErpOrderLine(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
source_system: str = Field(min_length=2, max_length=32)
order_ref: str = Field(min_length=3, max_length=64)
line_index: int = Field(ge=1)
customer_siren: str = Field(pattern=r"^\d{9}$")
sku: str = Field(min_length=1, max_length=64)
quantity: Decimal = Field(gt=0)
unit_price_ht: Decimal = Field(ge=0)
vat_rate_pct: Decimal = Field(ge=0, le=30)
order_date: date
currency: str = Field(default="EUR", pattern=r"^[A-Z]{3}$")
@field_validator("order_ref", "sku", "source_system", mode="before")
@classmethod
def sanitize_formula_injection(cls, value: Any) -> str:
text = str(value or "").strip()
if FORMULA_PREFIX_RE.match(text):
raise ValueError(f"Potential CSV/Excel formula injection blocked (CWE-1236): {text!r}")
return text
@field_validator("quantity", "unit_price_ht", "vat_rate_pct", mode="before")
@classmethod
def parse_eu_decimal(cls, value: Any) -> Decimal:
return normalize_decimal_str(value)
@field_validator("order_date", mode="before")
@classmethod
def parse_mixed_date(cls, value: Any) -> date:
return normalize_date_value(value)
@property
def net_cents(self) -> int:
amount = (self.quantity * self.unit_price_ht).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return int(amount * 100)
def idempotency_key(self) -> str:
"""Deterministic SHA-256 key stable across retries and file re-exports."""
canonical = {
"src": self.source_system.lower(),
"ref": self.order_ref.upper(),
"line": self.line_index,
"siren": self.customer_siren,
"sku": self.sku.upper(),
"qty": str(self.quantity.normalize()),
"cents": self.net_cents,
"date": self.order_date.isoformat(),
"cur": self.currency,
}
encoded = json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(encoded).hexdigest()
def split_valid_and_dlq(rows: list[dict[str, Any]], source_system: str) -> tuple[list[ErpOrderLine], list[dict[str, Any]]]:
valid: list[ErpOrderLine] = []
dlq: list[dict[str, Any]] = []
for idx, row in enumerate(rows, start=2):
payload = {"source_system": source_system, **row}
try:
valid.append(ErpOrderLine.model_validate(payload))
except ValidationError as exc:
dlq.append({"excel_row": idx, "raw": row, "errors": exc.errors(include_url=False)})
return valid, dlq
Notice the batch isolation pattern in split_valid_and_dlq: if row 412 of a 1,500-row supplier sheet has a malformed 8-digit SIREN or a negative quantity, the 1,499 valid rows still sync on schedule while row 412 lands in the Dead-Letter Queue with its exact Excel row number and structured Pydantic error list. Operations staff fix one row instead of blocking an entire afternoon of shipments.
5. Step 3: Retry-safe ERP upserts (429/502) and HMAC-SHA256 webhooks
Modern SaaS ERP and e-commerce APIs (Odoo JSON-RPC / External API, Pennylane REST API, Dolibarr REST API, Sage Business Cloud, Shopify Admin GraphQL) enforce strict burst rate limits and occasionally return transient 429 Too Many Requests or 502/503/504 gateway errors during peak hours. An unguarded for row in rows: requests.post(...) loop creates the exact nightmare you tried to eliminate: half the workbook lands in the ERP, the script crashes, and the next cron tick posts duplicates.
Solving this cleanly requires a two-sided contract:
- Outbound ERP upserts: Check your local
sync_ledgertable byidempotency_keybefore sending any HTTP request. Send the same key in theIdempotency-Keyheader (or map it to an external unique reference field likeclient_order_refin Odoo orref_extin Dolibarr). On429or5xx, respect the server'sRetry-Afterheader when present, otherwise apply bounded exponential backoff with random jitter. On permanent4xxbusiness rejections (unknown SKU, closed fiscal period, locked customer credit line), write the response body tosync_dlqand continue processing the remaining batch. - Inbound HMAC-SHA256 webhooks: When an ERP or e-commerce store notifies your Python worker of an event (for example, invoice paid in Pennylane, stock adjusted in Odoo, or Shopify B2B Purchase Order paid via
orders/paid), verify the cryptographic signature over the raw request bytes before decoding JSON. Always use constant-time comparison (hmac.compare_digest), enforce a strict timestamp skew window (maximum 300 seconds) to block replay attacks, and record the webhook's unique delivery ID in SQL so duplicate webhook deliveries become safe no-ops.
from __future__ import annotations
import hashlib
import hmac
import random
import sqlite3
import time
from typing import Any
import httpx
def verify_hmac_webhook(
raw_body: bytes,
signature_header: str,
timestamp_header: str,
secret: str,
max_skew_seconds: int = 300,
) -> bool:
"""Verify HMAC-SHA256 webhook signature and reject stale replays (> 5 min)."""
try:
sent_ts = int(timestamp_header)
except (TypeError, ValueError):
return False
if abs(int(time.time()) - sent_ts) > max_skew_seconds:
return False
signed_payload = f"{sent_ts}.".encode("utf-8") + raw_body
expected_sig = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
provided_sig = signature_header.removeprefix("sha256=").strip()
return hmac.compare_digest(expected_sig, provided_sig)
def push_line_idempotent(
client: httpx.Client,
conn: sqlite3.Connection,
erp_endpoint: str,
api_token: str,
idem_key: str,
payload: dict[str, Any],
max_attempts: int = 5,
) -> str:
"""Upsert one validated record into Odoo/Dolibarr/Pennylane/Sage with 429/502 backoff."""
existing = conn.execute(
"SELECT erp_remote_id, status FROM sync_ledger WHERE idempotency_key = ?",
(idem_key,),
).fetchone()
if existing and existing[1] == "SYNCED":
return str(existing[0])
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
"Idempotency-Key": idem_key,
}
for attempt in range(1, max_attempts + 1):
resp = client.post(erp_endpoint, json=payload, headers=headers, timeout=15.0)
if resp.status_code in (200, 201):
remote_id = str(resp.json().get("id", ""))
conn.execute(
"""
INSERT INTO sync_ledger (idempotency_key, order_ref, net_cents, currency, erp_remote_id, status, updated_at)
VALUES (?, ?, ?, ?, ?, 'SYNCED', datetime('now'))
ON CONFLICT(idempotency_key) DO UPDATE SET
erp_remote_id = excluded.erp_remote_id,
status = 'SYNCED',
updated_at = datetime('now')
""",
(idem_key, payload["order_ref"], payload["net_cents"], payload["currency"], remote_id),
)
conn.commit()
return remote_id
if resp.status_code in (429, 500, 502, 503, 504) and attempt < max_attempts:
retry_after = resp.headers.get("Retry-After")
delay = float(retry_after) if (retry_after and retry_after.isdigit()) else min(30.0, (2 ** attempt) + random.uniform(0.1, 0.9))
time.sleep(delay)
continue
# Permanent 4xx business error -> quarantine into DLQ without stopping the batch
conn.execute(
"""
INSERT INTO sync_dlq (idempotency_key, order_ref, http_status, error_body, payload_json, created_at)
VALUES (?, ?, ?, ?, ?, datetime('now'))
""",
(idem_key, payload["order_ref"], resp.status_code, resp.text[:1000], str(payload)),
)
conn.commit()
raise RuntimeError(f"ERP rejected {payload['order_ref']} with HTTP {resp.status_code}")
raise RuntimeError(f"Exhausted {max_attempts} attempts for {payload['order_ref']}")
For higher-concurrency deployments processing webhooks alongside scheduled Excel drops, swap SQLite (which works reliably in WAL mode for single-worker SME workloads up to tens of thousands of rows per day) for PostgreSQL with INSERT ... ON CONFLICT (idempotency_key) DO NOTHING and an async queue such as Redis/Celery, RQ, or PostgreSQL FOR UPDATE SKIP LOCKED.
6. Step 4: Daily SQLite / PostgreSQL financial reconciliation and DLQ replay
Logging 200 OK lines to stdout is not financial verification. A real production sync closes the loop every evening with an automated reconciliation query comparing expected source totals against confirmed ERP records grouped by day and currency. If delta_cents is non-zero or the open Dead-Letter Queue contains even one unresolved row, the job sends a concise alert email or Slack/Teams summary containing only the exact failing references and reasons.
-- 1. Local idempotency ledger & Dead-Letter Queue (SQLite 3.35+ / PostgreSQL compatible)
CREATE TABLE IF NOT EXISTS sync_ledger (
idempotency_key TEXT PRIMARY KEY,
order_ref TEXT NOT NULL,
net_cents INTEGER NOT NULL,
currency TEXT NOT NULL DEFAULT 'EUR',
erp_remote_id TEXT,
status TEXT NOT NULL CHECK (status IN ('PENDING', 'SYNCED', 'QUARANTINED')),
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sync_dlq (
id INTEGER PRIMARY KEY AUTOINCREMENT,
idempotency_key TEXT NOT NULL,
order_ref TEXT NOT NULL,
http_status INTEGER,
error_body TEXT NOT NULL,
payload_json TEXT NOT NULL,
resolved_at TEXT,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sync_ledger_date_status ON sync_ledger (updated_at, status);
CREATE INDEX IF NOT EXISTS idx_sync_dlq_open ON sync_dlq (resolved_at) WHERE resolved_at IS NULL;
-- 2. Daily financial reconciliation query: compare source totals vs ERP acknowledged rows
SELECT
substr(updated_at, 1, 10) AS sync_day,
currency,
COUNT(*) AS total_rows,
SUM(CASE WHEN status = 'SYNCED' THEN 1 ELSE 0 END) AS synced_rows,
SUM(CASE WHEN status <> 'SYNCED' THEN 1 ELSE 0 END) AS pending_or_failed,
ROUND(SUM(CASE WHEN status = 'SYNCED' THEN net_cents ELSE 0 END) / 100.0, 2) AS synced_net_eur,
ROUND(SUM(net_cents) / 100.0, 2) AS expected_net_eur,
(SUM(net_cents) - SUM(CASE WHEN status = 'SYNCED' THEN net_cents ELSE 0 END)) AS delta_cents
FROM sync_ledger
WHERE updated_at >= date('now', '-7 days')
GROUP BY sync_day, currency
ORDER BY sync_day DESC, currency;
-- 3. Open Dead-Letter Queue backlog check (alert ops if count > 0)
SELECT order_ref, http_status, substr(error_body, 1, 140) AS reason, created_at
FROM sync_dlq
WHERE resolved_at IS NULL
ORDER BY created_at DESC
LIMIT 50;
Once an operator corrects the underlying issue (for instance, adding a missing SKU in Odoo or updating a customer's VAT number in Sage), a single CLI replay command re-reads unresolved sync_dlq entries, re-validates them against Pydantic v2, pushes them with the exact same SHA-256 idempotency key, and stamps resolved_at = datetime('now'). You never manually re-upload a whole Excel sheet again.
7. Five classic production pitfalls and hardening checklist
Even well-intentioned internal Python scripts break in month two if they miss five SME-specific edge cases observed repeatedly on real client migrations:
- CP1252 vs UTF-8 BOM header mismatch: A CSV exported from Windows Excel often begins with bytes
EF BB BF. If your script opens it with plainencoding="utf-8"instead ofutf-8-sig, the first column name becomes\ufefforder_refand every row fails schema validation. Always decode withutf-8-sigfirst, thencp1252. - Silent date inversion on mixed workbooks: When one branch office saves dates in French
04/06/2026(June 4) and another pastes ISO or US strings, naivedateutil.parser.parsesilently guesses month-first and books revenue in the wrong VAT period. Lock the accepted format list explicitly per source system. - Floating-point cent drift (
0.01 EURerrors): Parsing prices with pandas/Pythonfloatturns19.99 * 3into59.970000000000006. Across 400 invoice lines, 1-cent rounding drift triggers rejection on strict e-invoicing platforms (EN 16931 BR-CO-15). Compute every line and VAT bucket inDecimaland store integer cents in SQL. - Retry storms doubling invoices on HTTP 502/504: A reverse proxy timeout does not mean the ERP rolled back the transaction; Odoo or Pennylane may have committed the invoice 200 ms after Nginx returned
504 Gateway Timeout. Always combine an upstream external reference check with your local SHA-256sync_ledgerbefore issuing a retry. - Windows SMB locks and partial SFTP uploads: Cron jobs scanning a hot folder every 5 minutes frequently grab a 40 MB Excel file while FileZilla or Windows Explorer is only 60% done writing it. Require atomic upload-then-rename (
.part->.xlsx), ignore~$*lock files, and verify two identical file-size readings 2 seconds apart before copying to a temporary workspace.
Production launch checklist before retiring manual imports: (1) Run 5 business days in shadow dry-run mode comparing generated ERP payloads against the finance team's manual entries until delta_cents = 0; (2) keep API tokens and HMAC secrets strictly in environment variables or a root-only 0600 file outside git; (3) enable SQLite WAL mode (PRAGMA journal_mode=WAL;) or PostgreSQL with daily off-site backups; (4) wire systemd timer failure alerts plus a daily 18:00 reconciliation summary; (5) document the exact 2-step DLQ replay procedure for non-developers.
8. Frequently asked questions
Why do Zapier and Make workflows fail on SME Excel-to-ERP synchronization?
Task-based no-code connectors charge per line item, drop context when a 5,000-row workbook hits API rate limits, and rarely enforce deterministic row-level idempotency across partial failures. When an ERP returns HTTP 429 or 502 halfway through a batch, retrying the whole scenario often creates duplicate invoices or skips rows silently without a Dead-Letter Queue or SQL ledger.
Should a Python ERP sync pipeline use Polars or openpyxl to read Excel files?
Use Polars with its default Rust calamine engine for speed and explicit schema_overrides on ID columns so SKU codes and SIREN numbers never lose leading zeros. Fall back to openpyxl in read_only=True, data_only=True mode when you need streaming cell iteration on legacy workbooks or must inspect workbook structure while keeping RAM flat.
How does a SHA-256 idempotency key stop duplicate orders and invoices in Odoo, Sage, or Pennylane?
Instead of trusting volatile Excel row numbers, you serialize the stable business fields (source system, external order reference, line index, SKU, normalized quantity, integer net cents, ISO date, and currency) into canonical sorted JSON and hash it with SHA-256. Checking that hash in a local SQLite or PostgreSQL sync_ledger and sending it in the Idempotency-Key HTTP header guarantees that retries never double-post.
How do you handle French decimal commas, CP1252 CSV files, and DD/MM/YYYY dates safely?
Never rely on system locale settings or Python float arithmetic. Decode incoming CSV bytes explicitly across utf-8-sig, cp1252, and latin-1, strip non-breaking spaces (U+00A0 and U+202F), parse amounts into exact Decimal objects with integer cent rounding, and run an explicit date parser covering ISO YYYY-MM-DD, French DD/MM/YYYY, and Excel serial integers without ever guessing US MM/DD/YYYY order.
Why must incoming ERP and Shopify webhooks be verified with HMAC-SHA256 and a timestamp window?
Public webhook endpoints can be probed or replayed over the internet. Recomputing an HMAC-SHA256 digest over the exact raw request bytes and timestamp, comparing it with hmac.compare_digest to prevent timing leaks, rejecting timestamps older than 300 seconds, and deduplicating event IDs in SQL blocks both forged payloads and network replay storms.
How do you read an Excel file from a Windows SMB share or SharePoint folder without lock errors?
Excel creates a temporary ~$ lock file and holds an exclusive write lock while an employee edits a sheet. Always ignore filenames starting with ~$, copy the workbook atomically to a local temporary directory with shutil.copy2, verify that file size is stable across two short checks, and parse only the local snapshot so the pipeline never collides with active users.
Replace manual Excel to ERP copy-paste with a fixed-price Python pipeline
Need a reliable, audit-ready bridge between your spreadsheets, Odoo, Sage, Dolibarr, Pennylane, or Shopify without per-task SaaS lock-in? Eclipse Technology builds deterministic Python and n8n workflows at fixed scope (starting from our SME automation packages at 590 EUR, 890 EUR, and 1 290 EUR HT, with optional European hosting and monitoring at 80 EUR HT/month, or custom ERP connectors scoped in writing within 24 business hours). You keep 100% ownership of the source code and SQL audit ledger.
Related Eclipse Technology engineering guides: Factur-X EN 16931, EU VAT & FEC Guide · Shopify B2B Purchase Orders & Net 30 Without Plus · All technical guides