// A supplier's EDI desk: a retailer's 850 order read, its 997 sent back, and the 856 ship notice and 810 invoice built.
//
//   quillo run x12.qwe      then open http://localhost:8080/order

use "x12.qwer"

let EDI = read_file("x12_sample.edi")

route GET /order {
    let po = x12_documents(EDI)?[0]
    { po: po.po_number, date: po.date, ship_to: po.parties[0], lines: po.lines, problems: x12_parse(EDI)?.problems }
}

route GET /ack.edi = respond(200, x12_997(EDI, 5001)?, { "content-type": "text/plain" })

// What goes back once the order is packed and shipped.
route GET /ship.edi {
    let po = x12_documents(EDI)?[0]
    let asn = [
        ["BSN", "00", "SHP-3301", "20261030", "1400"],
        ["HL", "1", null, "S"],
        ["TD5", null, "2", "UPSN", null, "UPS Ground"],
        ["REF", "BM", "1Z999AA10123456784"],
        ["HL", "2", "1", "O"],
        ["PRF", po.po_number],
    ] + (po.lines | map((l) => [["LIN", l.line, "VP", l.ids.VP], ["SN1", null, l.qty, l.unit]]) | flatten)
    let invoice = [
        ["BIG", "20261030", "INV-9001", "20261028", po.po_number],
        ["N1", "RE", "QUILLO SUPPLY CO", "92", "77"],
    ] + (po.lines | map((l) => ["IT1", l.line, l.qty, l.unit, l.price, null, "VP", l.ids.VP])) + [["TDS", "58800"], ["CTT", "2"]]
    let text = x12_build({ sender: "QUILLOSUPPLY", receiver: "BIGRETAILER", control: 812, date: "20261030", time: "1400" }, [{ type: "856", segments: asn }, { type: "810", segments: invoice }])?
    respond(200, text, { "content-type": "text/plain" })
}

// The built interchange read back: counts and control numbers agree.
route GET /check {
    let po = x12_documents(EDI)?[0]
    let built = x12_build({ sender: "QUILLOSUPPLY", receiver: "BIGRETAILER", control: 813, date: "20261030", time: "1400" }, [{ type: "810", segments: [["BIG", "20261030", "INV-9002", null, po.po_number], ["IT1", "1", 24, "EA", 12.5, null, "VP", "MUG-BLUE"], ["TDS", "30000"]] }])?
    let x = x12_parse(built)?
    { problems: x.problems, groups: len(x.groups), invoice: x12_documents(built)? | map((d) => { type: d.type, invoice: d.invoice_number, po: d.po_number, total_cents: d.total_cents, lines: d.lines }) }
}
