Search API documentation

Type to search the API docs.

Record a Vendor Cost, Payment Details and Invoice

Save a vendor cost and payment details on a Booth Service, then upload the invoice and verify both changes.

Example use case

Your electrical vendor sends an invoice and you want the amount and payment status beside the service it covers.

What you'll end up with

A Booth Service with the saved cost and payment details, plus its invoice attached to the same service.

Before you start

Have a workspace API key with financial access, the ID of a Booth Service you can edit with no invoice attached, and the invoice file.

Good to know

The API records payment details in ExhibitDay. It does not send money to the vendor.

At a glance

Time to try

About 15 minutes

Effect on your data

Updates records

Endpoints

6

The program updates one Booth Service and adds its invoice in a separate request. It writes a private local journal.

How it works

  1. Confirm the workspace and look up the payment status and Cost Centers.
  2. Read the Booth Service and save its revision. Use that revision to update the cost and payment details.
  3. Check the saved details and empty invoice slot, upload the invoice, and read the service again.

Record the payment details and attach the invoice

Use the ID of your test Booth Service and the payment status ID from your workspace. The requests below use example IDs.

Replace the example IDs and values with your own. Use the complete program below to save progress and check each result.

Step 1: Check the workspace

Confirm where the key can make changes.

curl -X GET "https://api.exhibitday.com/v1/references/workspace_info" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "id": 98765
}

Check: Confirm the returned id matches the workspace you intend to use.

Step 2: Look up payment statuses

Read the available labels so you can send the ID that matches your invoice.

curl -X GET "https://api.exhibitday.com/v1/references/payment_statuses" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "list_data": [
    { "id": 3, "name": "Not Paid Yet" }
  ]
}

Check: Find the ID for the status you intend to record.

Step 3: Look up Cost Centers

Read the workspace's Cost Centers when deciding how to allocate the cost.

curl -X GET "https://api.exhibitday.com/v1/references/cost_centers" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

[
  {
    "id": 21,
    "name": "Field Marketing"
  }
]

Check: Use IDs from your workspace if you supply a breakdown. You can also send a single amount.

Step 4: Read the Booth Service and its revision

Check that this is the right service and the invoice slot is empty.

curl -X GET "https://api.exhibitday.com/v1/events/booth_services/info?id=45678&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "id": 45678,
  "record_revision": "COPY_SERVICE_REVISION_FROM_YOUR_READ",
  "invoice_attachment": null
}

Check: Keep the full revision from your response. If an invoice is already attached, stop and review it first.

Step 5: Save cost and payment details

Send the amount and chosen payment status with the revision you just read.

curl -X PATCH "https://api.exhibitday.com/v1/events/booth_services" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":45678,\"cost\":{\"amount\":125.50},\"payment_status_id\":3,\"expected_revision\":\"COPY_SERVICE_REVISION_FROM_YOUR_READ\"}"

Example response (shortened)

{
  "record_revision": "NEW_SERVICE_REVISION"
}

Check: If you get record_changed (HTTP 409), read the service again before deciding whether to send a new update.

Step 6: Check the saved details and invoice slot

Read the service before sending the invoice.

curl -X GET "https://api.exhibitday.com/v1/events/booth_services/info?id=45678&%24include_record_revision=true" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "id": 45678,
  "payment_status_id": 3,
  "invoice_attachment": null
}

Check: Confirm the saved cost and payment details and check that the invoice slot is still empty.

Step 7: Attach the invoice

Send one invoice file to the Booth Service's invoice slot.

curl -X POST "https://api.exhibitday.com/v1/events/booth_services/invoice_attachment" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_UPLOAD_INVOICE_KEY" -F "booth_service_id=45678" -F "file=@vendor-invoice.pdf"

Example response (shortened)

{
  "invoice_attachment": {
    "id": 56789,
    "filename": "vendor-invoice.pdf"
  }
}

Check: Keep the ID from invoice_attachment.id.

Step 8: Read the service again

Verify the saved cost and invoice together.

curl -X GET "https://api.exhibitday.com/v1/events/booth_services/info?id=45678" -H "Authorization: Bearer YOUR_API_KEY"

See the complete example response below.

Check: Confirm the cost and payment status and match invoice_attachment.id to the ID you saved.

Try it

Before running the example

VariableWhat to put in itRequired?
EXHIBITDAY_API_KEYYour workspace API key.Yes
EXHIBITDAY_BOOTH_SERVICE_IDThe ID of an editable Booth Service with no attached invoice.Yes
EXHIBITDAY_COST_JSONA cost object with an amount or the complete Cost Center breakdown.Yes
EXHIBITDAY_PAYMENT_STATUS_IDThe ID from the payment-status list.Yes
EXHIBITDAY_INVOICE_PATHPath to one invoice file.Yes
EXHIBITDAY_JOB_IDA unique ID for this run. Use the same ID to continue it.Yes
EXHIBITDAY_JOURNALA private local path for the journal.Yes
EXHIBITDAY_PAYMENT_DUE_DATEA due date in YYYY-MM-DD format, if you want to set it.No
EXHIBITDAY_NEXT_PAYMENT_DUE_DATEThe next partial payment date in YYYY-MM-DD format. Only with payment status 2 (Partially Paid).No
EXHIBITDAY_PAYMENT_NOTESPlain-text payment notes, up to 200 characters.No
EXHIBITDAY_JOB_MODEUse new to start a run, or resume to continue an existing one. Defaults to resume.No

Bash

export EXHIBITDAY_API_KEY='YOUR_API_KEY'
export EXHIBITDAY_BOOTH_SERVICE_ID='45678'
export EXHIBITDAY_COST_JSON='{"amount":125.50}'
export EXHIBITDAY_PAYMENT_STATUS_ID='3'
export EXHIBITDAY_INVOICE_PATH='vendor-invoice.pdf'
export EXHIBITDAY_JOB_ID='vendor-invoices-payment-01'
export EXHIBITDAY_JOURNAL='vendor-invoices-payment-01.json'
export EXHIBITDAY_JOB_MODE='new'

PowerShell

$env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY'
$env:EXHIBITDAY_BOOTH_SERVICE_ID = '45678'
$env:EXHIBITDAY_COST_JSON = '{"amount":125.50}'
$env:EXHIBITDAY_PAYMENT_STATUS_ID = '3'
$env:EXHIBITDAY_INVOICE_PATH = 'vendor-invoice.pdf'
$env:EXHIBITDAY_JOB_ID = 'vendor-invoices-payment-01'
$env:EXHIBITDAY_JOURNAL = 'vendor-invoices-payment-01.json'
$env:EXHIBITDAY_JOB_MODE = 'new'

Use your own IDs, file paths and values. Then copy and run the complete program in your language.

Complete example program

Code Samples
#!/usr/bin/env bash
# Requires Bash, curl and Python3. No API key is written into the program.
python3 - <<'EXHIBITDAY_PY'
# Python 3; standard library only. Set EXHIBITDAY_API_KEY before running.
import http.client
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request

BASE = "https://api.exhibitday.com/v1"
SPEC = json.loads("{\"preserveNumbers\":true,\"requests\":{\"workspace_binding\":{\"method\":\"GET\",\"path\":\"/references/workspace_info\"},\"payment_choices\":{\"method\":\"GET\",\"path\":\"/references/payment_statuses\"},\"cost_center_choices\":{\"method\":\"GET\",\"path\":\"/references/cost_centers\"},\"service_before\":{\"method\":\"GET\",\"path\":\"/events/booth_services/info\"},\"save_payment\":{\"method\":\"PATCH\",\"path\":\"/events/booth_services\"},\"service_after_payment\":{\"method\":\"GET\",\"path\":\"/events/booth_services/info\"},\"upload_invoice\":{\"method\":\"POST\",\"path\":\"/events/booth_services/invoice_attachment\",\"file\":{\"name\":\"file\",\"maximum_bytes\":\"26214400\",\"extensions\":[\"png\",\"jpg\",\"jpeg\",\"bmp\",\"gif\",\"pdf\",\"msg\",\"eml\",\"doc\",\"docx\",\"ppt\",\"pptx\",\"xls\",\"xlsx\",\"csv\",\"rtf\",\"odp\",\"odt\",\"ods\",\"txt\",\"wks\",\"zip\"],\"content_types\":[]}},\"service_readback\":{\"method\":\"GET\",\"path\":\"/events/booth_services/info\"}}}")
API_KEY = os.environ["EXHIBITDAY_API_KEY"]
if any(ord(char) < 32 or ord(char) > 126 for char in API_KEY):
    raise RuntimeError("Use the API key as one ASCII header value without control characters")
if not API_KEY.strip():
    raise RuntimeError("Set EXHIBITDAY_API_KEY")

def decode_json(text):
    if SPEC["preserveNumbers"]:
        # Quote JSON NUMBER tokens, never text inside a JSON string, to keep CSV decimals exact.
        text = re.sub(r'"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?',
                      lambda m: m[0] if m[0].startswith('"') else json.dumps(m[0]), text)
    return json.loads(text)

from pathlib import Path
# This terminal version uses curl for HTTP and Python's standard library for JSON/CSV.
import subprocess
import tempfile

def transport(method, url, headers, data):
    with tempfile.TemporaryDirectory(prefix="exhibitday-guide-") as directory:
        folder = Path(directory)
        # curl may leave no output file for a valid bodyless304 response.
        (folder / "body").write_bytes(b"")
        command = ["curl", "--disable", "--silent", "--show-error", "--request", method, "--url", url,
                   "--max-time", "30", "--dump-header", str(folder / "headers"),
                   "--output", str(folder / "body"), "--write-out", "%{http_code}"]
        for name, value in headers.items():
            command += ["--header", name + ": " + value]
        if data is not None:
            (folder / "request").write_bytes(data)
            command += ["--data-binary", "@" + str(folder / "request")]
        result = subprocess.run(command, capture_output=True, text=True)
        if result.returncode:
            raise urllib.error.URLError(result.stderr.strip())
        response_headers = {}
        blocks = (folder / "headers").read_text(encoding="iso-8859-1").replace("\r\n", "\n").strip().split("\n\n")
        for line in blocks[-1].splitlines()[1:]:
            name, separator, value = line.partition(":")
            if separator:
                response_headers[name] = value.strip()
        return int(result.stdout), (folder / "body").read_bytes(), response_headers


class ApiError(RuntimeError):
    """An API error response. Branch on error_code (and status), never on the message text.
    uncertain is True when a PATCH or DELETE got no response or a server error: it may or may not have been applied."""
    def __init__(self, status, body, uncertain=False):
        self.status = status
        self.uncertain = uncertain
        self.error_code = body.get("error_code") if isinstance(body, dict) else None
        super().__init__(f"{body.get('error_code')} {body.get('error_params')}: {body.get('errors')} (request {body.get('request_id')})"
                         if isinstance(body, dict) else "HTTP " + str(status) if status else "No response")

def call(name, params=None, body=None, key=None):
    route = SPEC["requests"][name]
    headers = {"Authorization": "Bearer " + API_KEY, "Accept": "application/json"}
    if route["method"] == "POST":
        if not key: raise RuntimeError("Save a create key before sending POST")
        headers["Idempotency-Key"] = key
    data = None if body is None else json.dumps(body).encode("utf-8")
    if data is not None:
        headers["Content-Type"] = "application/json"
    query = urllib.parse.urlencode(params or {})
    url = BASE + route["path"] + ("?" + query if query else "")
    # Only GET has automatic retries in this workflow. A PATCH or DELETE that got no response or a
    # server error is never resent blindly: it may already have been applied, so the caller reads the record first.
    resend = route["method"] == "GET"
    for attempt in range(5):
        try:
            status, raw, response_headers = transport(route["method"], url, headers, data)
        except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException):
            if not resend:
                raise ApiError(0, None, uncertain=True)
            if attempt == 4:
                raise
            time.sleep(2 ** attempt)
            continue
        response_headers = {k.lower(): v for k, v in response_headers.items()}
        result = None
        if status != 304 and raw:
            try:
                result = decode_json(raw.decode("utf-8"))
            except (ValueError, UnicodeError):
                if status < 400:
                    raise RuntimeError("Expected a JSON success response")
        if status >= 500 and not resend:
            raise ApiError(status, result, uncertain=True)
        retry = resend and (status == 429 or status >= 500)
        if retry:
            if attempt == 4:
                raise RuntimeError("Retry limit reached; check the request outcome before starting a new create")
            delay = response_headers.get("retry-after", str(2 ** attempt))
            time.sleep(max(0, float(delay)))
            continue
        if status >= 400:
            raise ApiError(status, result)
        return {"status": status, "body": result, "headers": response_headers, "raw": raw}
    raise RuntimeError("Retry limit reached")


def deep_equal(left,right):
    if type(left) is not type(right): return False
    if isinstance(left,dict): return left.keys()==right.keys() and all(deep_equal(left[k],right[k]) for k in left)
    if isinstance(left,list): return len(left)==len(right) and all(deep_equal(a,b) for a,b in zip(left,right))
    return left==right

def either(left, right):
    if not isinstance(left, bool) or not isinstance(right, bool): raise RuntimeError("Expected Boolean criteria")
    return left or right

def equal(left, right):
    return type(left) is type(right) and left == right

def field(value, name):
    if not isinstance(value, dict) or name not in value: raise RuntimeError("Missing response field: " + name)
    return value[name]

import hashlib
import secrets
from pathlib import Path

class FileSnapshot:
    def __init__(self, name, data):
        self.name, self.data = name, bytes(data)
        self.sha256 = hashlib.sha256(self.data).hexdigest()


def file_length(value): return str(len(value.data))

def file_name(value): return value.name

def file_sha256(value): return value.sha256


def is_present(value):
    return value is not None and value != ""

def items(value):
    if not isinstance(value, list): raise RuntimeError("Expected a JSON array")
    return value

"""Strict private client journal reference; no transport or application dependency."""
from pathlib import Path
import hashlib
import os
import re
import secrets
from urllib.parse import urlsplit

PREAMBLE=b'EXHIBITDAY-GUIDE-JOURNAL 1\n'

class JournalRefusal(RuntimeError):
    pass

def utf8(value):
    if not isinstance(value,str):raise JournalRefusal('Journal fields are exact strings')
    return value.encode('utf-8',errors='strict')

def strings(values):
    raw=bytearray()
    for value in values:
        item=utf8(value);raw.extend(str(len(item)).encode('ascii'));raw.extend(b':');raw.extend(item)
    return bytes(raw)

def read_strings(raw):
    values=[];offset=0
    while offset<len(raw):
        end=raw.find(b':',offset)
        if end<0:raise JournalRefusal('Incomplete journal string length')
        length=raw[offset:end]
        if not re.fullmatch(b'0|[1-9][0-9]*',length):raise JournalRefusal('Noncanonical journal string length')
        size=int(length);offset=end+1
        if size>len(raw)-offset:raise JournalRefusal('Incomplete journal string')
        values.append(raw[offset:offset+size].decode('utf-8',errors='strict'));offset+=size
    return values

def digest(raw):return hashlib.sha256(raw).hexdigest().upper()

def fingerprint(pairs):
    values=[]
    for name,value in sorted(pairs.items()):
        if not re.fullmatch('[A-Za-z0-9_.-]+',name):raise JournalRefusal('Fingerprint field names must be explicit ASCII identifiers')
        if name.lower() in ('api_key','exhibitday_api_key'):raise JournalRefusal('Never fingerprint the API key')
        values.extend((name,value))
    return digest(strings(values))

def frame(values):
    raw=strings(values)
    return str(len(raw)).encode('ascii')+b' '+digest(raw).encode('ascii')+b'\n'+raw+b'\n'

def decode(raw):
    if not raw.startswith(PREAMBLE):raise JournalRefusal('Unknown or incomplete journal version')
    offset=len(PREAMBLE);records=[]
    while offset<len(raw):
        end=raw.find(b'\n',offset)
        if end<0:raise JournalRefusal('Incomplete journal frame header; reconcile before retry')
        match=re.fullmatch(b'(0|[1-9][0-9]*) ([0-9A-F]{64})',raw[offset:end])
        if match is None:raise JournalRefusal('Invalid journal frame header')
        size=int(match[1]);offset=end+1
        if size>=len(raw)-offset:raise JournalRefusal('Incomplete journal frame; reconcile before retry')
        payload=raw[offset:offset+size];offset+=size
        if raw[offset:offset+1]!=b'\n' or digest(payload).encode('ascii')!=match[2]:raise JournalRefusal('Journal integrity check failed; reconcile before retry')
        records.append(read_strings(payload));offset+=1
    return records

class Journal:
    def __init__(self,path,base,workspace,slug,job,input_fingerprint,writes,mode="resume"):
        self.path=Path(path);self.lock=Path(str(self.path)+'.lock');self.fd=None;self.owned=False;self.identity=None;self.tainted=False;self.intents={};self.saved_values={}
        address=urlsplit(base)
        if address.scheme not in ('https','http')or not address.netloc or address.username is not None or address.query or address.fragment or not re.fullmatch('[a-z][a-z0-9-]*',slug):raise JournalRefusal('Use the actual API base and closed guide slug')
        if not job.strip() or not re.fullmatch('[1-9][0-9]*',workspace) or not re.fullmatch('[0-9A-F]{64}',input_fingerprint):raise JournalRefusal('Use an actual workspace, explicit stable job ID and exact input fingerprint')
        if mode not in ("new","resume"):raise JournalRefusal("Choose new or resume for this local job")
        self.allowed={};manifest=[]
        for step,method,route in writes:
            if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.allowed or method not in ('POST','PATCH','DELETE')or not re.fullmatch('/v1/[A-Za-z0-9_/-]+',route)or'//'in route:raise JournalRefusal('Use a closed unique write manifest')
            self.allowed[step]=(method,route);manifest.extend((step,method,route))
        if not self.allowed:raise JournalRefusal('Only write workflows need a restart journal')
        self.header=['H','1',base,workspace,slug,job,input_fingerprint,digest(strings(manifest))]
        strings(self.header)
        try:
            self.fd=os.open(self.lock,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600);self.owned=True
        except FileExistsError:raise JournalRefusal('This journal is locked; do not run overlapping jobs or steal a stale lock')
        try:
            self.owner=secrets.token_hex(16);self.identity=os.fstat(self.fd)
            if os.write(self.fd,self.owner.encode('ascii'))!=len(self.owner):raise OSError('Incomplete lock identity write')
            os.fsync(self.fd)
            if self.path.is_symlink():raise JournalRefusal('Choose a private regular journal file')
            if mode=="resume" and not self.path.exists():raise JournalRefusal("Journal missing: stop and reconcile lost state before starting a new job")
            if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same job")
            if mode=="new":
                with open(self.path,'xb',buffering=0)as target:
                    target.write(PREAMBLE+frame(self.header));os.fsync(target.fileno())
            records=decode(self.path.read_bytes())
            if not records or records[0]!=self.header:raise JournalRefusal('Journal workspace/base/guide/job/input binding differs')
            for record in records[1:]:self.apply(record)
            if any(step not in self.saved_values for step in self.intents):raise JournalRefusal('A saved before-send intent lacks an ACK; stop and reconcile its outcome before retry')
        except BaseException:
            self.close();raise

    def apply(self,record):
        if not record:raise JournalRefusal('Empty journal record')
        if record[0]=='I':
            if len(record)!=6:raise JournalRefusal('Invalid intent shape')
            _,step,method,path,request_fingerprint,key=record
            if not re.fullmatch('[a-z][a-z0-9_-]*',step)or step in self.intents or self.allowed.get(step)!=(method,path)or not re.fullmatch('[0-9A-F]{64}',request_fingerprint)or any(name not in self.saved_values for name in self.intents):raise JournalRefusal('Invalid, future or repeated journal intent')
            if method=='POST'and not re.fullmatch('[0-9a-f]{32}',key)or method!='POST'and key!='':raise JournalRefusal('Invalid persisted action key')
            self.intents[step]={'method':method,'path':path,'request_fingerprint':request_fingerprint,'idempotency_key':key}
        elif record[0]=='A':
            if len(record)<3:raise JournalRefusal('Invalid ACK shape')
            _,step,count,*pairs=record
            if not re.fullmatch('0|[1-9][0-9]*',count)or len(pairs)!=2*int(count)or step not in self.intents or step in self.saved_values:raise JournalRefusal('ACK without exactly one prior intent')
            names=pairs[::2]
            if names!=sorted(set(names))or any(not re.fullmatch('[a-z][a-z0-9_]*',name)or name in ('api_key','exhibitday_api_key')for name in names):raise JournalRefusal('ACK saved fields must be unique sorted secret-free identifiers')
            self.saved_values[step]=dict(zip(names,pairs[1::2]))
        else:raise JournalRefusal('Unknown journal transition')

    def append(self,record):
        # The reader commits state only after complete length/digest recognition.
        # A torn append is retained and refused, never silently truncated.
        self.require_active();raw=frame(record)
        try:
            with open(self.path,'ab',buffering=0)as target:
                view=memoryview(raw)
                while view:
                    written=target.write(view)
                    if not written:raise OSError('Journal write did not advance')
                    view=view[written:]
                os.fsync(target.fileno())
        except BaseException:
            self.tainted=True;raise

    def require_active(self):
        if not self.owned or self.fd is None or self.identity is None or self.tainted:raise JournalRefusal('The journal scope is closed or its IO outcome needs reconciliation')
        current=self.lock.stat(follow_symlinks=False)
        if current.st_dev!=self.identity.st_dev or current.st_ino!=self.identity.st_ino or self.lock.read_text(encoding='ascii')!=self.owner:raise JournalRefusal('The journal lock was replaced; stop without deleting it')
    def acknowledged(self,step):
        self.require_active();return step in self.saved_values
    def saved(self,step):
        self.require_active()
        if step not in self.saved_values:raise JournalRefusal('No confirmed state exists for this step')
        return dict(self.saved_values[step])
    def begin(self,step,method,path,request_fingerprint):
        self.require_active()
        if step in self.intents:raise JournalRefusal('Never blindly repeat an existing action intent')
        key=secrets.token_hex(16)if method=='POST'else''
        record=['I',step,method,path,request_fingerprint,key]
        # Validate on an isolated state before touching the file.
        old=dict(self.intents)
        try:self.apply(record)
        finally:self.intents=old
        self.append(record);self.apply(record)
        return dict(self.intents[step])
    def acknowledge(self,step,saved):
        self.require_active()
        record=['A',step,str(len(saved))]
        for name,value in sorted(saved.items()):record.extend((name,value))
        old={name:dict(value)for name,value in self.saved_values.items()}
        try:self.apply(record);strings(record)
        finally:self.saved_values=old
        self.append(record);self.apply(record)
    def close(self):
        if self.owned:
            if self.tainted:
                os.close(self.fd);self.fd=None;self.owned=False
                return # Retain this lock after failed journal IO; manual reconciliation is required.
            try:self.require_active()
            except BaseException:
                os.close(self.fd);self.fd=None;self.owned=False;raise
            os.close(self.fd);self.fd=None;self.owned=False
            self.lock.unlink()
    def __enter__(self):return self
    def __exit__(self,*args):self.close()

def journal_values(value):
    if not isinstance(value, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k,v in value.items()):
        raise JournalRefusal('Saved/fingerprint values must be exact string fields')
    return dict(value)

def journal_acknowledge(job, step, saved):
    job.acknowledge(step,journal_values(saved))

def journal_acknowledged(job, step):
    return job.acknowledged(step)

def journal_begin(job, step, method, path, request_fingerprint):
    return job.begin(step,method,path,request_fingerprint)

def journal_fingerprint(value):
    return fingerprint(journal_values(value))

def journal_saved(job, step):
    return job.saved(step)

def json_string(value):
    return json.dumps(value,ensure_ascii=False,allow_nan=False,separators=(",",":"))

def not_value(value):
    if not isinstance(value, bool): raise RuntimeError("Expected a Boolean")
    return not value

def open_journal(path, base, workspace, slug, job, input_fingerprint, writes, mode):
    return Journal(path,base,workspace,slug,job,input_fingerprint,writes,mode)

def optional(name, fallback):
    value = os.environ.get(name)
    return fallback if value is None or value == "" else value

def parse_json(value):
    return json.loads(value)

def positive_id(value):
    if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 9223372036854775807: raise RuntimeError("Use a positive record ID")
    return value

def print_value(value):
    print(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False))

def read_file_snapshot(path, action):
    rule = SPEC['requests'][action].get('file')
    if not rule or rule['name'] != 'file': raise RuntimeError('Use the current declared file input')
    data = Path(path).read_bytes()
    if not data or len(data) > int(rule['maximum_bytes']): raise RuntimeError('The selected file is empty or exceeds this endpoint file limit')
    name = Path(path).name
    if not name or any(c in name for c in '\r\n\0'): raise RuntimeError('Use a filename without header control characters')
    return FileSnapshot(name, data)


def request_upload(name, params, file, key):
    route = SPEC['requests'][name]
    if route['method'] != 'POST' or not route.get('file') or not key: raise RuntimeError('Bind one declared upload and its persisted create key')
    boundary = 'ExhibitDayGuide' + secrets.token_hex(24)
    while boundary.encode('ascii') in file.data: boundary = 'ExhibitDayGuide' + secrets.token_hex(24)
    quoted = file.name.replace('\\', '\\\\').replace('"', '\\"')
    data = ('--' + boundary + '\r\nContent-Disposition: form-data; name="file"; filename="' + quoted + '"\r\nContent-Type: application/octet-stream\r\n\r\n').encode('utf-8') + file.data + ('\r\n--' + boundary + '--\r\n').encode('ascii')
    headers = {'Authorization': 'Bearer ' + API_KEY, 'Accept': 'application/json', 'Idempotency-Key': key, 'Content-Type': 'multipart/form-data; boundary=' + boundary}
    query = urllib.parse.urlencode(params or {})
    url = BASE + route['path'] + ('?' + query if query else '')
    try: status, raw, response_headers = transport('POST', url, headers, data)
    except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException): raise ApiError(0, None, uncertain=True)
    parsed = None
    try: parsed = decode_json(raw.decode('utf-8'))
    except (ValueError, UnicodeError): pass
    if status != 200: raise ApiError(status, parsed, uncertain=status >= 500)
    if not isinstance(parsed, dict): raise RuntimeError('Upload returned no usable JSON receipt; reconcile before retrying')
    return {'status': status, 'body': parsed, 'headers': {k.lower(): v for k,v in response_headers.items()}, 'raw': raw}


def require_condition(value, message):
    if value is not True: raise RuntimeError(message)

def required(name):
    value = os.environ.get(name)
    if value is None or not value.strip(): raise RuntimeError("Set " + name)
    return value

def response_status(value):
    return str(value["status"])

def text(value):
    if value is None: return ""
    if isinstance(value, str): return value
    if isinstance(value, bool): return "true" if value else "false"
    if isinstance(value, int): return str(value)
    raise RuntimeError("Expected a scalar response value")


def main():
    invoice_service_id = positive_id(required("EXHIBITDAY_BOOTH_SERVICE_ID"))
    invoice_cost_json = required("EXHIBITDAY_COST_JSON")
    invoice_status = required("EXHIBITDAY_PAYMENT_STATUS_ID")
    invoice_file = read_file_snapshot(required("EXHIBITDAY_INVOICE_PATH"), "upload_invoice")
    invoice_due = optional("EXHIBITDAY_PAYMENT_DUE_DATE", "")
    invoice_next_due = optional("EXHIBITDAY_NEXT_PAYMENT_DUE_DATE", "")
    invoice_notes = optional("EXHIBITDAY_PAYMENT_NOTES", "")
    require_condition(either(not_value(is_present(invoice_next_due)), equal(invoice_status, "2")), "Supply a next partial payment due date only with payment status 2 (Partially Paid).")
    invoice_workspace_response = call("workspace_binding", {}, None, None)
    require_condition(equal(response_status(invoice_workspace_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
    invoice_workspace = invoice_workspace_response["body"]
    invoice_workspace_id = positive_id(text(field(invoice_workspace, "id")))
    invoice_choices_response = call("payment_choices", {}, None, None)
    require_condition(equal(response_status(invoice_choices_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
    invoice_choices = invoice_choices_response["body"]
    invoice_status_known = False
    for invoice_choice in items(items(field(invoice_choices, "list_data"))):
        if equal(text(field(invoice_choice, "id")), invoice_status):
            invoice_status_known = True
    require_condition(invoice_status_known, "Choose a current payment status ID from the reference lookup.")
    invoice_centers_response = call("cost_center_choices", {}, None, None)
    require_condition(equal(response_status(invoice_centers_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
    invoice_before_response = call("service_before", {"id": invoice_service_id, "$include_record_revision": "true"}, None, None)
    require_condition(equal(response_status(invoice_before_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
    invoice_before = invoice_before_response["body"]
    require_condition(equal(text(field(invoice_before, "id")), invoice_service_id), "The initial service read returned another ID.")
    invoice_journal_path = required("EXHIBITDAY_JOURNAL")
    invoice_job_id = required("EXHIBITDAY_JOB_ID")
    invoice_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume")
    invoice_job = open_journal(invoice_journal_path, "https://api.exhibitday.com/v1", invoice_workspace_id, "vendor-invoices-payment", invoice_job_id, journal_fingerprint({"workflow_contract_sha256": "01ABA03B7D433469D925465D8FD301DE7C64672D4E250956A70F0AC49F7E1652", "inputs": journal_fingerprint({"service_id": invoice_service_id, "cost_json": invoice_cost_json, "payment_status_id": invoice_status, "payment_due_date": invoice_due, "next_payment_due_date": invoice_next_due, "payment_notes": invoice_notes, "filename": file_name(invoice_file), "file_length": file_length(invoice_file), "file_sha256": file_sha256(invoice_file)})}), [["save_payment", "PATCH", "/v1/events/booth_services"], ["upload_invoice", "POST", "/v1/events/booth_services/invoice_attachment"]], invoice_job_mode)
    try:
        if not_value(journal_acknowledged(invoice_job, "save_payment")):
            require_condition(equal(field(invoice_before, "invoice_attachment"), None), "This service already has an invoice. Stop before changing payment details; explicitly review a replacement separately.")
            invoice_old_revision = text(field(invoice_before, "record_revision"))
            require_condition(is_present(invoice_old_revision), "Retrieve the current service revision before changing payment details.")
            invoice_patch = {"id": invoice_service_id, "payment_status_id": invoice_status, "expected_revision": invoice_old_revision}
            invoice_patch_query = {"cost": invoice_cost_json}
            if is_present(invoice_due):
                invoice_patch_query["payment_due_date"] = invoice_due
            if is_present(invoice_next_due):
                invoice_patch_query["next_payment_due_date"] = invoice_next_due
            if is_present(invoice_notes):
                invoice_patch_query["payment_notes"] = invoice_notes
            journal_begin(invoice_job, "save_payment", "PATCH", "/v1/events/booth_services", journal_fingerprint({"inputs": journal_fingerprint({"service_id": invoice_service_id, "cost_json": invoice_cost_json, "payment_status_id": invoice_status, "payment_due_date": invoice_due, "next_payment_due_date": invoice_next_due, "payment_notes": invoice_notes, "filename": file_name(invoice_file), "file_length": file_length(invoice_file), "file_sha256": file_sha256(invoice_file)}), "expected_revision": invoice_old_revision}))
            invoice_payment_response = call("save_payment", invoice_patch_query, invoice_patch, None)
            require_condition(equal(response_status(invoice_payment_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
            invoice_payment_receipt = invoice_payment_response["body"]
            require_condition(equal(text(field(invoice_payment_receipt, "status_code")), "200"), "The payment save response must have status_code 200.")
            invoice_saved_revision = text(field(invoice_payment_receipt, "record_revision"))
            require_condition(is_present(invoice_saved_revision), "The checked payment save needs the returned record revision.")
            journal_acknowledge(invoice_job, "save_payment", {"service_id": invoice_service_id, "record_revision": invoice_saved_revision})
        invoice_payment_saved = journal_saved(invoice_job, "save_payment")
        require_condition(equal(text(field(invoice_payment_saved, "service_id")), invoice_service_id), "The confirmed payment save belongs to another service.")
        invoice_after_payment_response = call("service_after_payment", {"id": invoice_service_id, "$include_record_revision": "true"}, None, None)
        require_condition(equal(response_status(invoice_after_payment_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
        invoice_after_payment = invoice_after_payment_response["body"]
        require_condition(equal(text(field(invoice_after_payment, "id")), invoice_service_id), "Payment readback returned another service.")
        require_condition(equal(text(field(invoice_after_payment, "payment_status_id")), invoice_status), "The current payment status differs; do not automatically restore it.")
        if not_value(journal_acknowledged(invoice_job, "upload_invoice")):
            require_condition(equal(field(invoice_after_payment, "invoice_attachment"), None), "The invoice slot became occupied; do not replace it or repeat the payment update.")
            require_condition(equal(text(field(invoice_after_payment, "record_revision")), text(field(invoice_payment_saved, "record_revision"))), "The service changed after the payment save. Review it before attaching an invoice.")
            invoice_upload_intent = journal_begin(invoice_job, "upload_invoice", "POST", "/v1/events/booth_services/invoice_attachment", journal_fingerprint({"inputs": journal_fingerprint({"service_id": invoice_service_id, "cost_json": invoice_cost_json, "payment_status_id": invoice_status, "payment_due_date": invoice_due, "next_payment_due_date": invoice_next_due, "payment_notes": invoice_notes, "filename": file_name(invoice_file), "file_length": file_length(invoice_file), "file_sha256": file_sha256(invoice_file)}), "payment_snapshot": json_string({"cost": json_string(field(invoice_after_payment, "cost")), "payment_status_id": text(field(invoice_after_payment, "payment_status_id")), "payment_due_date": json_string(field(invoice_after_payment, "payment_due_date")), "next_payment_due_date": json_string(field(invoice_after_payment, "next_payment_due_date")), "payment_notes": json_string(field(invoice_after_payment, "payment_notes"))})}))
            invoice_upload_response = request_upload("upload_invoice", {"booth_service_id": invoice_service_id}, invoice_file, text(field(invoice_upload_intent, "idempotency_key")))
            require_condition(equal(response_status(invoice_upload_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
            invoice_upload_body = invoice_upload_response["body"]
            invoice_upload_row = field(invoice_upload_body, "invoice_attachment")
            invoice_attachment_id = positive_id(text(field(invoice_upload_row, "id")))
            require_condition(is_present(text(field(invoice_upload_row, "filename"))), "The uploaded invoice receipt needs its actual stored filename.")
            journal_acknowledge(invoice_job, "upload_invoice", {"service_id": invoice_service_id, "attachment_id": invoice_attachment_id, "invoice_json": json_string(invoice_upload_row), "payment_snapshot": json_string({"cost": json_string(field(invoice_after_payment, "cost")), "payment_status_id": text(field(invoice_after_payment, "payment_status_id")), "payment_due_date": json_string(field(invoice_after_payment, "payment_due_date")), "next_payment_due_date": json_string(field(invoice_after_payment, "next_payment_due_date")), "payment_notes": json_string(field(invoice_after_payment, "payment_notes"))})})
        invoice_saved = journal_saved(invoice_job, "upload_invoice")
        require_condition(equal(text(field(invoice_saved, "service_id")), invoice_service_id), "The saved invoice belongs to another service.")
        invoice_final_response = call("service_readback", {"id": invoice_service_id}, None, None)
        require_condition(equal(response_status(invoice_final_response), "200"), "Expected the documented HTTP 200 response; stop and review any other outcome.")
        invoice_final = invoice_final_response["body"]
        require_condition(equal(text(field(invoice_final, "id")), invoice_service_id), "Final readback returned another service.")
        require_condition(deep_equal({"cost": json_string(field(invoice_final, "cost")), "payment_status_id": text(field(invoice_final, "payment_status_id")), "payment_due_date": json_string(field(invoice_final, "payment_due_date")), "next_payment_due_date": json_string(field(invoice_final, "next_payment_due_date")), "payment_notes": json_string(field(invoice_final, "payment_notes"))}, parse_json(text(field(invoice_saved, "payment_snapshot")))), "The current cost and payment details differ from those saved before the invoice upload; review them without retrying either write.")
        require_condition(deep_equal(field(invoice_final, "invoice_attachment"), parse_json(text(field(invoice_saved, "invoice_json")))), "The invoice has changed or disappeared; do not upload a replacement.")
        print_value({"service_id": invoice_service_id, "invoice_attachment_id": text(field(invoice_saved, "attachment_id")), "payment_status_id": text(field(invoice_final, "payment_status_id"))})
    finally:
        invoice_job.close()


if __name__ == "__main__":
    main()

EXHIBITDAY_PY

Example response

{
  "id": 45678,
  "event_id": 12345,
  "event_name": "Northwind Summit 2030",
  "booth_service_type_id": 1,
  "booth_service_type": "Electrical",
  "acquisition_status_id": 2,
  "acquisition_status": "Already Reserved",
  "description": "Electrical service",
  "notes": null,
  "reserve_by_date": null,
  "order_date": null,
  "order_confirmation_number": null,
  "vendor_name": "Northwind Venue Services",
  "vendor_point_of_contact": null,
  "vendor_phone": null,
  "vendor_email": null,
  "vendor_website_url": null,
  "payment_status_id": 3,
  "payment_status": {
    "id": 3,
    "name": "Not Paid Yet"
  },
  "payment_due_date": null,
  "next_payment_due_date": null,
  "payment_notes": null,
  "invoice_attachment": {
    "id": 56789,
    "filename": "vendor-invoice.pdf",
    "attachment_created_timestamp": "2030-01-03T12:00:00Z"
  },
  "cost": {
    "amount": 125.50,
    "cost_center_breakdown": [
      {
        "cost_center_id": null,
        "cost_center": "Not Specified",
        "charge": 125.50
      }
    ]
  }
}
Note: Confirmed vendor payment details and invoice. The final service read shows the saved cost, payment status and the invoice you uploaded. The update and the upload were separate requests.

Things to keep in mind

  • The payment update can succeed even if the upload fails. Check both before deciding what to do next.
  • A blank payment due date or notes input leaves that value as it is. Unless the status is Partially Paid (2), saving a status clears the next payment date.
  • This program adds an invoice to an empty slot. To replace an existing invoice, use PATCH /v1/events/booth_services/invoice_attachment.

If a run stops

  • Keep the journal private. It records which changes the program attempted and confirmed.
  • To continue a run with no unresolved save, use EXHIBITDAY_JOB_MODE=resume with the same job ID, journal path and inputs.
  • If a write has an uncertain outcome, check the affected records in ExhibitDay before making another change. The program stops and leaves the pending step in the journal.
  • Run one copy per journal. If a crash leaves a .lock file, make sure no copy is running or can start with that journal before removing the lock file.