← Back to Documentation
Marg ERP logo

Marg ERP Integration with UAE FTA E-Invoicing via TrustBill

Connect Marg ERP 9+ (Silver / Gold / Platinum + Pharma / Retail / Compumove / Restaurant + Marg on Cloud) via the TrustBill Windows Desktop Agent · Version 1.0 · September 2026

Overview

This guide describes how Marg ERP — the on-premise Windows ERP by Marg Compusoft — connects to TrustBill, a UAE FTA-accredited service provider (ASP), so Marg users in the UAE can issue PINT-AE compliant e-invoices without changing their day-to-day billing workflow.

Marg is a desktop-first ERP heavily used by pharmacies, retail chains, distribution and FMCG in the GCC. It is Indian-native — its default tax model is Indian GST (CGST/SGST/IGST + HSN/SAC + IRN), and its default e-invoicing hooks target India's Invoice Registration Portal (IRP). UAE customers still run Marg with 5% VAT ledgers, TRN fields and UAE VAT return layouts, but Marg does not ship a native UAE PINT-AE XML generator or an accredited-ASP transmission channel.

TrustBill closes that gap through the TrustBill Desktop Agent for Marg — a signed Windows service installed on the same PC or LAN server as Marg. The agent reads posted vouchers from Marg's XML export (or ODBC / Marg API), remaps any residual GST-shaped fields to UAE VAT, ships the payload to TrustBill over TLS 1.3, and TrustBill generates PINT-AE XML, validates it, and delivers it via a certified UAE ASP (Tron-Stride or Storecove). The FTA acknowledgement reference is written back into the voucher's Narration field on the next agent cycle.

What this integration delivers

  • Read-only Windows agent — cannot create, edit, delete or post vouchers in Marg
  • Works with Marg ERP 9+ across Silver, Gold, Platinum editions + Marg Pharma, Retail, Compumove and Restaurant variants + Marg on Cloud
  • Sales, Sales Return, Purchase and Purchase Return vouchers mapped to PINT-AE document types
  • Automatic GST → UAE VAT remapping — CGST/SGST/IGST tax lines collapsed to a single 5% VAT line
  • Pharma batch numbers and expiry dates preserved end to end
  • Retail POS Cash Memos treated as simplified tax invoices when total < 10,000 AED and no buyer TRN
  • FTA acknowledgement stamped back into the voucher Narration on the next agent cycle
  • Bulk migration path for historical Marg vouchers via CSV export

What is Marg ERP?

Marg ERP 9+ (branded Marg ERP 9 / Marg 9.6 / Marg 9.7+ / Marg 9.8+) is a Windows-based accounting + inventory + billing ERP developed by Marg Compusoft (now Marg ERP Limited). It is the market leader in Indian pharmacy and retail chain automation and has a large installed base across the GCC — especially UAE pharmacies, medical distributors, FMCG wholesalers, and multi-outlet retail chains.

  • Ships as a Windows installer; data stored per-company in a local file store (Marg 9 Silver / Gold) or in an SQL Server backend (Platinum)
  • Vertical-specific product lines: Marg Pharma (batch / expiry / DL / manufacturer inventory), Marg Retail (multi-outlet POS + loyalty), Marg Compumove (distribution + secondary sales), Marg Restaurant, Marg Salon
  • Editions: Silver (single-user, single-company), Gold (LAN multi-user, up to ~10 concurrent), Platinum (SQL Server + advanced modules + branch consolidation)
  • Additional product: Marg on Cloud (Marg's official RDP-hosted VM offering)
  • Data path — typical: C:\Marg\{CompanyDir}\
  • Import / Export via a documented XML / CSV dialect; ODBC on Platinum; a REST API (limited surface) on newer builds targeted at cloud connectors
  • UAE VAT: not a separate SKU — customers configure their company with 5% VAT rates and TRN fields under the standard tax master

Why Marg needs an ASP bridge — plus a tax remapping layer: Marg's default tax model is Indian GST with HSN/SAC codes, CGST/SGST/IGST split lines, and IRN/QR-code hooks pointing at India's IRP. UAE users usually override this to a single 5% VAT ledger, but many templates still emit GST-shaped rows. TrustBill remaps them cleanly so nothing has to change inside Marg.

Supported Marg Versions & Editions

The TrustBill Desktop Agent works with every Marg 9+ build. Marg Compusoft ships continuous point releases (9.6 → 9.7 → 9.8 → 9.9 …); every one is covered by the same agent.

Marg release / editionDeploymentBackendSupport level
Marg ERP 9+ (9.6 – 9.9 point releases)Windows on-premiseLocal file store or SQLFull — recommended
Marg 9 SilverSingle-PC on-premiseLocal file storeFull via XML export path
Marg 9 GoldLAN multi-user (up to ~10 concurrent)Shared file store on serverFull — most common in UAE deployments
Marg 9 PlatinumLAN multi-user + advanced modules + branch consolidationSQL Server backendFull — ODBC also available
Marg on CloudRDP-hosted Windows VM by MargSQL Server on the hosted VMFull — agent installed inside the hosted VM
Marg PharmaAny of the aboveFull — batch + expiry preserved (see Pharma section)
Marg Retail (multi-outlet POS)Any of the aboveFull — Cash Memos handled as simplified profile
Marg Compumove (distribution)Any of the aboveFull — high-volume B2B pattern
Marg Restaurant / SalonAny of the aboveFull — POS-heavy workflows treated as simplified profile
Marg 8.x and olderLegacy — pre-VAT / pre-GSTLocal file storeBest-effort — upgrade to Marg 9+ strongly recommended

Prerequisites

On the Marg side

  • Marg ERP 9+ (9.6 or newer) on Windows 10 / 11 / Server 2019+
  • Company configured for UAE — set Country = United Arab Emirates in Master → Company Info and switch off Indian-GST-specific defaults (Tools → Options → GST → Disable)
  • 15-digit UAE TRN saved on Company Master (Master → Company → TRN No.)
  • 15-digit TRN saved on each B2B Party master (Master → Account → Party → TRN)
  • Tax Categories configured for UAE — VAT 5%, Zero-Rated, Exempt, Reverse Charge, Out of Scope (created under Master → Tax Category)
  • Marg's Enable Data Import/Export setting turned on (Tools → Advanced Configuration → Import/Export → Enable)
  • A Windows account with read permission on the Marg data folder (XML path) or a valid ODBC DSN pointed at the SQL backend (Platinum)

On the TrustBill side

  • A TrustBill SME account (one account = one TRN = one Marg company)
  • Completed KYB (business verification) — trade licence + TRN certificate uploaded
  • Submission mode set to test or sandbox during onboarding, live for production
  • The Desktop Agent installer is downloaded from Sources → Add Marg — no manual credential setup, the wizard mints a fresh shared secret

Integration Architecture

Marg has no public cloud API, so the flow mirrors the QuickBooks Desktop / BUSY pattern: the customer's Windows agent pushes to TrustBill.

Outbound flow (Marg → TrustBill → FTA)

  1. A user posts a Sales voucher in Marg (Transaction → Sale → Add).
  2. The TrustBill Desktop Agent's scheduler wakes on its poll interval (default: every 5 minutes) and asks Marg for vouchers modified since the last sync via the XML export (or ODBC on Platinum).
  3. The agent applies the GST → UAE VAT remapping pass (see GST → UAE VAT Remapping) and serialises the vouchers into TrustBill's InvoiceCreateInput shape.
  4. The agent POSTs to https://api.trustbill.ae/v1/invoices over TLS 1.3 with the agent's Bearer JWT.
  5. TrustBill stores the invoice as draft.
  6. If auto-submit is enabled, POST /v1/invoices/submit fires immediately.
  7. Pipeline: queued → transformed → validated → delivered. ASP forwards to FTA over Peppol.

Inbound flow (FTA → TrustBill → Marg)

  1. The ASP posts an inbound webhook to TrustBill when the FTA acknowledges or rejects the invoice.
  2. TrustBill's Marg worker enqueues a Narration write-back keyed on the Marg voucher's UUID.
  3. On the agent's next cycle, it dequeues pending write-backs and updates the invoice's Narration field via a Marg XML import (or SQL UPDATE on Platinum).
  4. Narration stamp format: TrustBill: {status} · {peppol-uuid} · {ISO date}
  5. Latency: up to one poll interval (default 5 min) after FTA ack.

Connection Methods

Four ways to bridge Marg to TrustBill. All except CSV run through the Desktop Agent.

1. Desktop Agent + Marg XML Import/Export (recommended)

The agent uses Marg's own documented XML dialect — the same feature customers use for master transfer, bank imports, etc. Works on every Marg edition including Silver and Marg on Cloud.

  • Works on Silver / Gold / Platinum / Marg on Cloud
  • No SQL access required — reads from the Marg data folder
  • Delta-only sync via Marg's Last Modified filter
  • Write-back done via XML import — Marg's own audit log preserves accountability

2. Desktop Agent + ODBC / direct SQL (Platinum only)

Marg Platinum exposes the SQL Server backend over ODBC. Faster than XML export for high-volume pharma / distribution companies.

  • Marg Platinum only
  • Faster on 1,000+ vouchers / day
  • Read-only queries on the voucher tables; single UPDATE on Narration for write-back
  • Requires a Windows ODBC DSN pointed at the Marg SQL instance

3. Desktop Agent + Marg REST API

Newer Marg builds ship a limited REST API (originally intended for Marg-branded cloud connectors). Where present, the agent prefers it over XML — it's the fastest path for delta reads.

  • Enabled from Tools → Advanced Configuration → API → Enable REST endpoints
  • Runs on http://localhost:9880/marg-api by default
  • Requires an internal Marg API key generated from the same screen

4. CSV Export (one-off migrations)

For historical vouchers, export via Reports → Sales Register → Print → Export → CSV. Use TrustBill's marg-csv-normaliser script to remap columns, then upload via POST /v1/invoices/bulk.

Which method should I use?

For 90% of Marg UAE customers, use the Desktop Agent + XML path — works on Silver / Gold / Platinum and Marg on Cloud. Switch to ODBC only if you're on Platinum with 1,000+ daily vouchers. Use Marg REST API when your Marg build has it enabled — it's marginally faster. Use CSV only for historical migrations before go-live.

TrustBill Desktop Agent for Marg

A signed Windows service (~18 MB) installed on the same machine as Marg (or any LAN host that can reach the Marg data folder / SQL backend). Once installed, it runs headless — no UI to keep open.

Install steps

  1. Sign into TrustBill → Sources → Add Marg. Enter a display name and click Continue.
  2. TrustBill mints a fresh 32-byte shared secret and returns a signed installer URL. Copy the plaintext secret — shown once.
  3. Download the installer, run it as Administrator. The wizard asks for: Marg data folder path (or SQL DSN, or REST endpoint), the shared secret, the TrustBill API endpoint (pre-filled), and a chosen tax remapping profile.
  4. The installer registers a Windows service TrustBill Marg Agent (auto-start, Local System or a dedicated service account).
  5. Within one poll cycle, the connection status in the TrustBill Sources page flips from Awaiting first sync to Connected.

Configuration file

The agent's C:\ProgramData\TrustBill\marg-agent\config.yaml holds the runtime settings:

api_endpoint: https://api.trustbill.ae tenant_id: <redacted> shared_secret: <argon2id-hash-only> marg: method: xml # xml | odbc | rest data_path: C:\Marg\MyCompany odbc_dsn: null # required if method: odbc rest_endpoint: null # required if method: rest company_code: MYC vertical: pharma # pharma | retail | distribution | restaurant | general poll_interval_seconds: 300 prices_include_vat: false seller_arabic_name: "شركة تجارية ذ.م.م" tax_remapping_profile: uae_vat_5 # collapses CGST/SGST/IGST → VAT 5%

Where to run the agent: the agent must reach Marg's data folder or SQL backend AND make outbound HTTPS to api.trustbill.ae. On single-PC Silver installs, run it on the same PC. On LAN Gold / Platinum, run it on the Marg database server. For Marg on Cloud, run it inside the hosted VM.

Authentication (Shared Secret)

The Desktop Agent authenticates to TrustBill with a per-connection shared secret — same argon2id-hash pattern used across all TrustBill's on-premise integrations (QuickBooks Desktop, BUSY, Focus RT, Marg).

AspectDetail
Secret length32 bytes, base64-encoded
Storage on TrustBillArgon2id hash only — never re-shown after generation
Storage on the agentWindows DPAPI-encrypted at rest in config.yaml
Session modelAgent exchanges secret for a short-lived JWT (60 min), refreshed automatically
RotationTrustBill Sources → Marg → Rotate Secret. Rotation preserves connection identity; only the agent needs the new secret pasted in

Idempotency-Key derivation for Marg

Every TrustBill write endpoint requires an Idempotency-Key. Derive it from Marg's stable voucher UUID:

Idempotency-Key: marg::{company_code}::voucher::{voucher_uuid}

Agent retries after a network blip reuse the same key — TrustBill returns the cached response, so duplicates never reach the FTA.

GST → UAE VAT Remapping

This is the biggest Marg-specific concern and the reason the Marg connector needs a remapping pass that other cloud-ERP connectors don't. Even when a UAE Marg company has been "switched to VAT", many Marg templates still emit GST-shaped rows — the agent normalises them before sending to TrustBill.

What the remapping pass does

Marg / Indian-GST artefactTrustBill / UAE-VAT replacementNotes
CGST + SGST split (e.g. 2.5% + 2.5% = 5%)Single vatRate: 0.05 lineAgent merges the two rows before emitting
IGST (inter-state 5% / 12% / 18%)vatRate: 0.05 if 5% is the intended UAE rate; other IGST rates flagged as unmappedIn UAE-only deployments, IGST should not appear at all; if it does, review the Marg tax master
GSTIN (15-char Indian format)Ignored; UAE TRN read from the Party's TRN No. field insteadIf a Party has only GSTIN populated, the connector blocks with trn_missing
HSN / SAC codesPreserved on lines[].sellerItemId for traceability, not emitted to PINT-AEPINT-AE uses UN/CEFACT and Peppol codes; HSN/SAC is India-only
Place of Supply (state code)DiscardedUAE VAT has no state-of-supply; only designated zone matters (see UAE Scenarios)
Reverse Charge (RCM) tagKept — maps directly to taxCategory: reverse_charge_designated_zoneSemantics translate cleanly
E-Invoice (IRN) / QR-code hookDisabled by the agent for this voucherThe agent tags outbound vouchers so Marg's own IRP hook doesn't fire
HSN Summary rows in Sales RegisterSkipped — TrustBill re-computes totals from raw linesPrevents double-counting

Recommended: run the Marg "Switch to VAT" macro first. Marg Compusoft's own Tools → Country Change → United Arab Emirates macro removes most GST vestiges in one pass. TrustBill's remapping is a safety net; the cleanest deployments have the macro applied before the agent installs.

Marg → PINT-AE Field Mapping

The agent translates Marg's XML voucher shape into TrustBill's InvoiceCreateInput. Field names follow Marg's own XML dialect.

Header-level mapping

Marg fieldTrustBill fieldNotes
Voucher.BillNonumberHuman-readable ("INV/2026-27/00042"); 1–64 chars
Voucher.UUIDIdempotency-Key + sellerInvoiceReferenceMarg-internal UUID; stable across renumbering
Voucher.BillDateissueDateDD-MM-YYYY converted to ISO YYYY-MM-DD
Voucher.DueDatedueDateOptional
Voucher.VoucherTypeinvoiceTypeSale → sale, Purchase → purchase, Sale Return → credit_note, Purchase Return → debit_note, POS/Cash Memo → sale (simplified profile)
Voucher.CurrencycurrencyMust be AED; multi-currency vouchers converted at ExchangeRate
Company.LegalName / NameEnglishseller.nameFrom Marg Company Master
Company.NameArabic (or agent config seller_arabic_name)seller.legalNameArabicRequired by PINT-AE; fallback to agent config if Marg field is blank
Company.TRNseller.trn15-digit UAE TRN
Party.Namebuyer.nameParty master name
Party.NameArabicbuyer.legalNameArabicPreserved when populated
Party.TRNbuyer.trn15-digit TRN; leave empty for B2C / POS
Party.Countrybuyer.countryNormalised to ISO 3166-1 alpha-2
Party.Address1..3, City, Statebuyer.address.{line1,line2,city,state}
Voucher.RefBillNoreferencedInvoiceNumberRequired for Sale Return / Purchase Return — original voucher number
Voucher.NarrationnotesPreserved verbatim + used as the write-back target

Line-level mapping (ItemDetails/Item)

Marg fieldTrustBill fieldNotes
Item.Name / Descriptionlines[].descriptionSupports Arabic when Company code page is Unicode
Item.Qtylines[].quantityMust be > 0
Item.Ratelines[].unitPriceVAT-exclusive; agent strips VAT if prices_include_vat: true
Item.SchemeDisc / Discountlines[].discountAmountPer-line discount, applied before VAT
Item.Code / ItemCodelines[].sellerItemIdAlso carries HSN/SAC when present, for traceability
Item.Unit / UOMlines[].unitMarg UOM mapped to UN/ECE Rec 20 (Nos → C62, Kg → KGM, Ltr → LTR, Strip → C62)
Item.BatchNo (pharma)lines[].batchNumberPreserved for pharma / regulated goods — see Pharma section
Item.ExpiryDate (pharma)lines[].expiryDateISO YYYY-MM-DD
Item.TaxCategory / VATCodelines[].vatRate + lines[].taxCategoryMapped via the Marg Tax Type Mapping table
Item.CGST + SGST + IGSTCollapsed to single vatRateHandled by the GST → VAT remapping — sum of CGST + SGST must equal the intended UAE 5%

Totals are computed server-side

Do not send Marg's Voucher.NetAmt / TaxAmt / GrossAmt. TrustBill re-computes totals from the raw lines after the GST-remapping pass. If Marg's total differs from TrustBill's by more than ±0.01 AED, the connector logs a variance — usually because Marg's Adjustment or Round-Off ledger adjusts a rounding penny. Map that ledger to out_of_scope in the agent config and it will pass on the next cycle.

Create Invoice (draft)

Endpoint: POST /v1/invoices

A real Marg Pharma Sales voucher mapped to the TrustBill payload. Marg voucher: INV/2026-27/00042 — Sale of paracetamol strips with batch + expiry, at 5% VAT.

Request body

{ "number": "INV/2026-27/00042", "issueDate": "2026-09-08", "dueDate": "2026-10-08", "currency": "AED", "invoiceType": "sale", "buyer": { "name": "Al Wasl Pharmacy LLC", "legalNameArabic": "صيدلية الوصل ذ.م.م", "trn": "100633289400015", "country": "AE", "email": "purchase@alwaslpharm.example", "address": { "line1": "Al Wasl Road, Shop 12", "city": "Dubai", "country": "AE" } }, "seller": { "name": "Marg Pharma Distribution LLC", "legalNameArabic": "مارج للتوزيع الصيدلاني ذ.م.م", "trn": "100100100100021", "country": "AE" }, "lines": [ { "description": "Paracetamol 500mg — Strip of 10", "sellerItemId": "PARA-500-S10", "quantity": 200, "unit": "C62", "unitPrice": 3.50, "batchNumber": "PB240108", "expiryDate": "2027-01-31", "vatRate": 0.05, "taxCategory": "standard_5" } ], "sellerInvoiceReference": "Marg UUID e7c4b8a2-....", "notes": "Delivery on the same day" }

Response (201 Created) — abbreviated:

{ "id": "5f8d2c9e-....-uuid", "number": "INV/2026-27/00042", "status": "draft", "invoiceType": "sale", "totals": { "subtotal": 700, "tax": 35, "total": 735, "currency": "AED" }, "pipeline": [], "errors": [], "submissionMode": "sandbox", "source": "marg-desktop-agent" }

Sales Return & Purchase Return

Marg records Sales Returns and Purchase Returns as separate voucher types. The agent maps them directly.

Marg voucherinvoiceTypeRequired extra fields
Sale Return / Credit Notecredit_notereferencedInvoiceNumber = Voucher.RefBillNo, reasonCode
Purchase Return / Debit Notedebit_notereferencedInvoiceNumber = original Purchase voucher, reasonCode

Pharma expiry-return special case: Marg Pharma often posts returns with the original batch + expiry preserved. The agent forwards both to TrustBill so the FTA acknowledgement matches the original invoice's line-level detail.

Pharma Batch & Expiry Preservation

Marg Pharma tracks every line-level batch number, manufacturing date, expiry date, MRP, drug licence, and manufacturer. The agent preserves these fields on the wire even though PINT-AE itself only mandates a subset:

Marg Pharma fieldTrustBill / PINT-AE handling
BatchNolines[].batchNumber — emitted as PINT-AE line note
MfgDatelines[].manufactureDate — stored, not emitted (available for reconciliation)
ExpDatelines[].expiryDate — emitted as PINT-AE line note
MRPStored for cross-check against unitPrice; not emitted
DrugLicNo (Party master)Preserved on buyer.regulatoryReferences[] for audit
ManufacturerPrefixed onto the line description for FTA-visible traceability

Multiple batches on one invoice line: Marg posts these as multiple sub-lines under the same item name. The agent expands them into distinct lines[] entries so batch-level detail survives — this is important when the buyer's ERP or QMS ingests the PINT-AE XML for stock tracking.

Retail POS & Cash Memos

Marg Retail POS emits Cash Memos in high volume. The connector treats them like any other Sale voucher, with the automatic simplification rule:

  • Cash Memos where the Party has no TRN and total < 10,000 AED → PINT-AE simplified tax invoice profile
  • Cash Memos where the Party has a TRN → standard PINT-AE profile even if under 10,000 AED (customer explicitly identified themselves as a business)
  • Marg's tender-mix (Cash / Card / UPI / Split) is captured as paymentMeans[]
  • End-of-day Z-report tallying is unaffected — the agent still reads each individual Cash Memo, not the Z-total

Retail throughput tip: for outlets doing 500+ cash memos/day, drop the agent's poll_interval_seconds from 300 to 60. TrustBill's API easily absorbs the higher cadence.

Submit Invoice(s) for Delivery

Creating a draft in TrustBill does not deliver the invoice to the FTA. Submission is an explicit second call.

Endpoint: POST /v1/invoices/submit

{ "ids": ["5f8d2c9e-....-uuid"] }

Marg-specific UX: Marg has no plug-in surface for a third-party "Send to FTA" button, so auto-submit on ingest is the recommended pattern. The user's Save in Marg is effectively the send-to-FTA moment; the agent auto-submits within one poll interval.

Status Tracking & Narration Write-back

Marg has no custom-field infrastructure like Zoho / QBO, so write-back rides on the voucher's Narration field.

Narration stamp format

TrustBill: {status} · {peppol-uuid} · {ISO date}
TrustBill statusWritten back to Marg Narration?
draft / queued / transformed / validatedNo — not stable enough to stamp
deliveredYes — stamped on next agent cycle
acknowledgedYes — stamp refreshed with the FTA ack ref
rejectedYes — Narration shows TrustBill: rejected · <reject code>

Bulk Migration from Marg

The Desktop Agent pulls the last 12 months by default on first sync. For older history:

  1. In Marg: Reports → Sales Register → filter by date → Export → CSV
  2. Run the TrustBill marg-csv-normaliser script
  3. Upload in test mode via POST /v1/invoices/bulk
  4. Review the summary; repeat in sandbox and live

TrustBill CSV column headers

number,issueDate,dueDate,invoiceType,currency,sellerTrn,sellerName,sellerLegalNameArabic,buyerTrn,buyerName,buyerLegalNameArabic,buyerCountry,buyerAddressLine1,buyerCity,lineDescription,lineQty,lineUnit,lineUnitPrice,lineVatRate,lineTaxCategory,lineBatchNumber,lineExpiryDate,referencedInvoiceNumber,notes
LimitValue
Max rows per file1,000 vouchers
Max file size5 MB
Partial successYes — bad rows reported without rolling back the batch

Test / Sandbox / Live Modes

Marg has no separate sandbox instance. Use TrustBill's mode switch + a copied Marg company for isolated testing.

TrustBill modePurposeReaches FTA?
testLocal integration testing — no ASP callNo
sandboxEnd-to-end dry run against the ASP sandboxFTA sandbox only
liveReal, legally binding e-invoicingYes — the FTA production network

Marg-specific tip: use Marg's Master → Company → Copy Company to create a sandbox copy of production. Point the agent at the copy in sandbox mode, verify totals match Marg's VAT Report, then re-point at production in live mode.

Marg Tax Type Mapping (UAE)

After the GST → VAT remapping pass, Marg's residual VAT tax categories map cleanly to TrustBill's taxCategory enum. Custom-named categories (common in older Marg pharma companies migrated from pre-VAT setups) need a one-time mapping in the agent config.

Typical Marg Tax CategoryRateTrustBill vatRateTrustBill taxCategory
VAT 5% Sales / Standard Rated5%0.05standard_5
Zero Rated Sales — Export0%0zero_rated_export
Zero Rated Sales — Healthcare0%0zero_rated_healthcare
Zero Rated Sales — Education0%0zero_rated_education
Exempt Sales — FinancialExempt0exempt_financial
Exempt Sales — Residential RentExempt0exempt_residential_rent
RCM Sales / Designated Zone0%0reverse_charge_designated_zone
Out of Scope SalesNon-taxable0out_of_scope

Healthcare zero-rating (pharma-specific): Marg Pharma often defaults every SKU to Zero Rated Sales — Healthcare, but this is not universally correct — only qualifying medicines and medical equipment on the FTA list are zero-rated. Review your item master and reassign OTC and non-qualifying items to VAT 5% before go-live.

UAE-Specific Scenarios

Free Zone / Designated Zone sellers

Set the flag on your TrustBill tenant (Settings → Company → Zone Type = Designated) — Marg has no company-level flag. The flag flows through as seller.designatedZone: true so PINT-AE emits the free-zone declaration.

Margin scheme (used goods)

Use Marg's Item Category field and add the category name (e.g. "Margin Scheme") to the agent's margin_scheme_categories list. The agent sends lines[].marginScheme: true and uses the item's Cost as the margin base.

Reverse charge on imports

Purchase vouchers using Marg's RCM tax category map to invoiceType: purchase + taxCategory: reverse_charge_designated_zone. PINT-AE emits the ReverseCharge markers.

B2C simplified tax invoices (POS)

Cash Memos where the Party has no TRN and total < 10,000 AED emit the PINT-AE simplified profile automatically. See Retail POS.

Bilingual (Arabic + English) legal names

PINT-AE requires the seller's Arabic legal name. Marg 9.7+ has a dedicated Arabic-name field on Company Master; on older versions, the agent's seller_arabic_name config is the fallback. Buyer Arabic names come from Party.NameArabic when populated.

Multi-Company & Multi-Branch Marg

Multi-company

One Marg installation typically holds many companies (one folder per legal entity). Each company = one TRN = one TrustBill tenant. Configure the agent with a companies: list — one entry per company code, each with its own tenant credential.

Multi-branch consolidation (Platinum)

Marg Platinum supports branch consolidation into a single company file. When branches share a TRN, one TrustBill tenant covers all of them — the connector uses the Voucher.BranchCode field to prefix invoice numbers and prevent per-tenant duplicate collisions.

Error Handling

Three failure surfaces: Marg-side XML export errors (agent log), TrustBill pipeline errors (dashboard), and Narration write-back errors (agent log + dashboard).

LayerSymptomRoot causeAction
AgentAgent log: "cannot open Marg data folder"Service account lacks NTFS read permissionGrant the service account read access to the Marg data folder
AgentAgent log: "Marg XML export feature not enabled"Import/Export unticked in Marg ConfigurationIn Marg: Tools → Advanced Configuration → Import/Export → Enable
Pipelineinvalid_body — missing buyer TRNParty's TRN field empty (or only GSTIN populated)Fill the Party's TRN field in Marg; agent auto-retries
Pipelinearabic_seller_name_requiredCompany Arabic legal name emptyFill Marg Company → Name (Arabic), or set seller_arabic_name in agent config
Pipelinetotals_mismatchMarg Round-Off / Adjustment ledger not mappedAdd the ledger to agent config tax_mapping as out_of_scope
Pipelinegst_residue_detectedVoucher has CGST + SGST lines that don't sum to a UAE-legal VAT rateRun Marg's Country Change → UAE macro; TrustBill will accept the resulting VAT-only lines on the next cycle
Pipelineunknown_tax_typeCustom-named Marg Tax Category not mappedAdd mapping in agent config tax_mapping
Pipeline409 invoice_number_duplicateSame BillNo posted across two branches or two Marg companiesEnable per-branch prefixes in Marg (Master → Voucher Series) or keep companies separate at TRN level
Write-backNarration stamp doesn't appearVoucher is in a locked accounting period, or user lacks Modify permissionUnlock the period or grant Voucher-Modify to the agent's user
AgentDuplicate FTA submissions after service restartAgent lost its "already sent" markerConfirm Idempotency-Key formula uses Voucher.UUID — duplicates are safely deduped on TrustBill side

Setup Checklist

  1. Confirm Marg version (9.6+) and switch the company to UAE (Tools → Country Change → UAE)
  2. Enable XML Import/Export in Marg Advanced Configuration
  3. Fill Company TRN on Company Master
  4. Fill Arabic legal name on Company Master (or set seller_arabic_name in agent config)
  5. Populate Party TRNs for B2B customers
  6. Confirm UAE VAT Tax Categories exist (Standard 5%, Zero-Rated Export/Healthcare/Education, Exempt Financial/Rent, RCM Designated Zone, Out of Scope)
  7. Pharma customers: review item-level tax categories — reassign OTC items from Healthcare-zero to VAT 5% where required
  8. Create your TrustBill SME account and complete KYB
  9. Open the Connect Marg wizard in the TrustBill dashboard (Sources → Add Source → Marg)
  10. Copy the one-time shared secret shown in step 2 of the wizard
  11. Download and run the Desktop Agent installer as Administrator
  12. Point the wizard at the Marg data folder (or configure ODBC on Platinum)
  13. Enable sandbox mode in TrustBill
  14. Post a test Sales voucher in Marg — confirm it reaches acknowledged within one poll interval + 3 min
  15. Reconcile Marg's VAT Report against TrustBill's Delivered Invoices
  16. Switch to live mode when FTA registration is complete

Suggested test cases before go-live

  • B2B Sales voucher, single line, 5% VAT — expect acknowledged
  • Pharma sale with batch + expiry (200 strips paracetamol) — expect batch/expiry preserved in PINT-AE line notes
  • Pharma sale with multiple batches under one item — expect distinct lines[] entries per batch
  • Retail POS Cash Memo < 10,000 AED, no Party TRN — expect PINT-AE simplified profile
  • Sale Return referencing an earlier Sales voucher — expect matching pair
  • Voucher with residual CGST + SGST lines — expect them collapsed to VAT 5%
  • Voucher with IGST line — expect gst_residue_detected (needs Country Change macro)
  • Voucher with Round-Off adjustment — expect totals to match after mapping
  • Multi-branch consolidation voucher — expect BranchCode-prefixed invoice number
  • Multi-company database — expect vouchers routed to the correct TrustBill tenant
  • Bulk upload of 500 historical vouchers via CSV — expect partial success reported per row

Troubleshooting

SymptomLikely causeFix
Agent installed but no vouchers reach TrustBillWindows Service stopped, or agent points to wrong company folderCheck services.mscTrustBill Marg Agent = Running; verify data_path
Agent log shows "auth: nvu"Shared secret pasted incorrectly or rotatedRotate the secret in TrustBill Sources; paste new value; restart the service
Every voucher rejected with gst_residue_detectedMarg company was never switched to UAERun Tools → Country Change → UAE; also confirm tax_remapping_profile: uae_vat_5 in agent config
Pharma batch missing from PINT-AE XMLCompany file not on Marg Pharma vertical, or agent config vertical not setSet vertical: pharma in agent config; batch/expiry fields become mandatory
Retail throughput bottleneckPoll interval too long for high-volume outletsDrop poll_interval_seconds from 300 to 60
Arabic party names arrive as ???Marg company was created with a non-Unicode code pageRecreate the company as Unicode (Marg 9.7+ default); migrate masters via XML export
Multi-currency voucher totals mismatchMarg's exchange-rate precision set to 2 decimalsSet Master → Currency → Rate Precision = 6
Narration stamp truncatedUser's existing narration + stamp exceeds Marg's Narration limitShorten the base narration; TrustBill's stamp is ~75 chars — reserve 100 chars for it
Duplicate FTA submissions after a Marg reindexReindex bumped every voucher's Modified timestampReset the agent's high-water mark to today's date; historical vouchers are safely deduped via Idempotency-Key

Security Notes

  • Argon2id-hashed shared secret. The plaintext secret is shown once at wizard step 2 and never re-shown. TrustBill stores only the hash; the agent stores it Windows-DPAPI-encrypted.
  • Secret rotation is a first-class flow (Sources → Marg → Rotate Secret).
  • Read-only integration. The agent cannot create, edit, delete or post vouchers in Marg. The only write path is a targeted UPDATE / import on the Narration field of already-posted vouchers.
  • Signed installer. The Desktop Agent installer is signed with a TrustBill EV code-signing certificate.
  • TLS 1.3 in transit + AES-256-GCM at rest. Marg voucher data never leaves your PC / server in cleartext.
  • UAE data residency. All staging + PINT-AE XML + audit logs live in AWS me-central-1.
  • Pharma privacy note. Batch and drug-licence details flow only for line-level traceability; the agent never reads or transmits patient / prescription data — Marg Pharma's patient module is out of scope.
  • Agent audit log. Every poll cycle, every voucher pull, every Narration write-back is logged locally in C:\ProgramData\TrustBill\marg-agent\logs\ and mirrored to TrustBill's cloud logs.

Support & Contact

Technical Support

Escalation

For Marg go-live escalations, please include: your TrustBill tenant ID, the Marg edition (Silver / Gold / Platinum / Marg on Cloud / Pharma / Retail / Compumove), the company code, the failing voucher's BillNo + UUID, and the agent log line from the failing cycle (C:\ProgramData\TrustBill\marg-agent\logs\agent.log).