# DIAN

A DIAN source keeps the DIAN document list (Excel) of one Colombian company in a
Space and, with an XML grant, the XML of every listed document. It holds the
company's NIT (without check digit), the cédula of the legal representative in
the RUT (stored encrypted, returned only as its last three digits) and a mail
grant of the Space for the mailbox in the RUT (IMAP, Gmail or Microsoft 365).

How a sync runs (`dian.sync.run` or the source's schedule):
1. Adlass asks the DIAN portal to email the company's access link.
2. It reads that email from the source's mailbox through the mail grant, as the
   owner of the mail connection, and checks that the link belongs to the NIT.
3. It exports the Excel from the day before the last synced day (the first time
   from `start_date`, default 1 January) to today, one export per calendar
   year, into the source's folder.
4. With `xml_grant_id` it imports the XML of every listed document (see
   `dian.xml.import`) before the next year.
The run is a `SYNC` run: poll `dian.runs.get`; `result.exports` lists each
export with `document_id`, `rows` and the XML counts. Its steps are child runs
(`parent_run_id`).

Operations:
- `dian.sources.create`, `update`, `get`, `list`, `pause`, `resume`, `delete`.
  Space admins manage sources; the mail connection must be theirs and the grant
  must allow `messages.search` and `messages.get`.
- `dian.sync.run`: sync a source now. `dian.runs.list`: runs of a Space or a
  source. `dian.runs.get`: one run.
- Single steps: `dian.token.request` (link of a source's company),
  `dian.excel.export` (a link pasted by the user, one calendar year) and
  `dian.xml.import` (XMLs of a stored workbook).

Rules:
- The DIAN keeps one live access link per company: every new request voids the
  previous one. Adlass runs at most one token request, export or sync per NIT
  on the whole platform; a second one fails with `dian_nit_busy`. Do not retry
  at once. Once a workspace's source received the link of a NIT (`verified_at`),
  no other workspace can create a source for that NIT or request its link with an
  unverified source (`dian_nit_claimed`).
- `schedule` (cron or rule with a timezone) runs a source at most every 6 hours;
  without it only `dian.sync.run` starts a sync.
- A source pauses after 5 failed syncs in a row, at once when its grants stop
  working, and at once when the access link never arrives before the source was
  ever verified (`verified_at`: the first time the link arrived in its mailbox).
  `dian.sources.resume` starts again.
- Billing: browser minutes of the portal sessions (`browser.minute`), each mail
  call of the mail connection and each XML fetch (12.5 credits).
