Search API documentation

Type to search the API docs.

Update an Annual Budget and Compare It with Spending

Update a saved fiscal year's budget plan, then compare it with actual spending.

Example use case

Finance sends revised spending targets and asks for an updated view of this year's trade-show costs.

What you'll end up with

A verified budget update for one saved fiscal year, plus the Event costs, Misc. Annual Expenses and Cost Center totals for that period.

Before you start

Have a workspace API key with budget and cost access, and choose an existing year in a workspace you can use for testing.

Good to know

A fiscal year can start in one calendar year and end in the next. Use the dates the API returns.

At a glance

Time to try

About 15 minutes

Effect on your data

Updates records

Endpoints

8

The program updates the planned Event count, Exhibit and Sponsorship amounts and notes for one saved year. It reads actual costs and writes a private local journal.

How it works

  1. Confirm the workspace, its fiscal settings and the year you intend to report.
  2. Read the saved budget and use its revision to update the plan.
  3. Read all the report pages for that year and confirm the budget totals and saved values.

Update the budget and read the spending reports

Use the same saved fiscal year from your test workspace in each request. The examples use 2030.

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 which workspace owns the budget.

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 intended workspace.

Step 2: Read the fiscal settings

Check the workspace settings before selecting a fiscal year.

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

Check: Note workspace_currency_code and workspace_fiscal_year_start_month. Use them to read the reports.

Step 3: Find the budget year

Look up the workspace's available budget years.

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

Example response (shortened)

[
  {
    "id": "2030",
    "value": "2030"
  }
]

Check: Choose a year that also has a saved Annual Budget row.

Step 4: Read the saved plan and revision

Fetch the row for that year before changing the plan.

curl -X GET "https://api.exhibitday.com/v1/financials/annual_budgets?filter_by_budget_year=2030&%24include_record_revision=true&%24limit=2&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "list_data": [
    {
      "budget_year": 2030,
      "fiscal_start_date": "2029-07-01",
      "fiscal_end_date": "2030-06-30",
      "record_revision": "COPY_BUDGET_REVISION_FROM_YOUR_READ"
    }
  ]
}

Check: Expect one saved row and keep its record_revision. If the year has no saved row, the program stops. To set it up, use ExhibitDay or send the PATCH without expected_revision.

Step 5: Update the plan

Send the new planned values with the saved revision. This example plans for 12 Events and shows how ExhibitDay rounds amounts to cents. ExhibitDay saves 20000.13 and 5000.01.

curl -X PATCH "https://api.exhibitday.com/v1/financials/annual_budgets" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"budget_year\":2030,\"planned_num_events\":12,\"planned_exhibit_amount\":20000.125,\"planned_sponsorship_amount\":5000.005,\"notes\":\"Revised after the spring planning meeting.\",\"expected_revision\":\"COPY_BUDGET_REVISION_FROM_YOUR_READ\"}"

Example response (shortened)

{
  "record_revision": "NEW_BUDGET_REVISION"
}

Check: If the year changed after your read, the API returns record_changed (HTTP 409) and saves nothing. Read the year again before deciding whether to update it. A successful update changes the plan while actual costs come from the underlying records.

Step 6: Read the year's Event costs

Use the same fiscal budget year to get the Event cost detail.

curl -X GET "https://api.exhibitday.com/v1/financials/event_costs?filter_by_budget_year=2030&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY"

Check: Read all pages. Use these details to explain the reported total.

Step 7: Read Misc. Annual Expenses

Get the Misc. Annual Expenses for the selected year.

curl -X GET "https://api.exhibitday.com/v1/financials/misc_annual_expense_costs?filter_by_budget_year=2030&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY"

Check: Read all pages. Each row shows its planned amount and its actual cost.

Step 8: Read the Cost Center breakdown

Get spending grouped by Cost Center for the same year.

curl -X GET "https://api.exhibitday.com/v1/financials/cost_center_breakdown?filter_by_budget_year=2030&%24limit=100&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY"

Check: Leave out the Cost Center filter to include every center, including Not Specified.

Step 9: Verify the updated budget

Read the saved budget again and compare the plan and actual totals.

curl -X GET "https://api.exhibitday.com/v1/financials/annual_budgets?filter_by_budget_year=2030&%24limit=2&%24offset=0" -H "Authorization: Bearer YOUR_API_KEY"

See the complete example response below.

Check: Confirm the fiscal dates and saved values. Use the detail reports to explain the total and avoid counting the same spending twice.

Try it

Before running the example

VariableWhat to put in itRequired?
EXHIBITDAY_API_KEYYour workspace API key.Yes
EXHIBITDAY_BUDGET_YEARThe ending year of a saved fiscal budget.Yes
EXHIBITDAY_PLANNED_NUM_EVENTSThe new planned Event count.Yes
EXHIBITDAY_PLANNED_EXHIBIT_AMOUNTThe planned Exhibit amount in workspace currency.Yes
EXHIBITDAY_PLANNED_SPONSORSHIP_AMOUNTThe planned Sponsorship amount in workspace currency.Yes
EXHIBITDAY_BUDGET_NOTESPlain-text Budget Notes. They replace the current notes; reads return them as HTML.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_PAGE_SIZEReport rows per page. Defaults to 100.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_BUDGET_YEAR='2030'
export EXHIBITDAY_PLANNED_NUM_EVENTS='12'
export EXHIBITDAY_PLANNED_EXHIBIT_AMOUNT='20000.125'
export EXHIBITDAY_PLANNED_SPONSORSHIP_AMOUNT='5000.005'
export EXHIBITDAY_BUDGET_NOTES='Revised after the spring planning meeting.'
export EXHIBITDAY_JOB_ID='annual-budgets-spending-01'
export EXHIBITDAY_JOURNAL='annual-budgets-spending-01.json'
export EXHIBITDAY_JOB_MODE='new'

PowerShell

$env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY'
$env:EXHIBITDAY_BUDGET_YEAR = '2030'
$env:EXHIBITDAY_PLANNED_NUM_EVENTS = '12'
$env:EXHIBITDAY_PLANNED_EXHIBIT_AMOUNT = '20000.125'
$env:EXHIBITDAY_PLANNED_SPONSORSHIP_AMOUNT = '5000.005'
$env:EXHIBITDAY_BUDGET_NOTES = 'Revised after the spring planning meeting.'
$env:EXHIBITDAY_JOB_ID = 'annual-budgets-spending-01'
$env:EXHIBITDAY_JOURNAL = 'annual-budgets-spending-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\"},\"workspace_calendar\":{\"method\":\"GET\",\"path\":\"/workspace_settings\"},\"budget_years\":{\"method\":\"GET\",\"path\":\"/references/budget_years\"},\"annual_before\":{\"method\":\"GET\",\"path\":\"/financials/annual_budgets\"},\"update_plan\":{\"method\":\"PATCH\",\"path\":\"/financials/annual_budgets\"},\"event_cost_pages\":{\"method\":\"GET\",\"path\":\"/financials/event_costs\"},\"annual_misc_pages\":{\"method\":\"GET\",\"path\":\"/financials/misc_annual_expense_costs\"},\"center_pages\":{\"method\":\"GET\",\"path\":\"/financials/cost_center_breakdown\"},\"annual_readback\":{\"method\":\"GET\",\"path\":\"/financials/annual_budgets\"}}}")
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 add_offset(offset, received):
    result = int(offset) + received
    if received <= 0 or result > 2147483647: raise RuntimeError("Cannot advance this int32 offset; reconcile the query")
    return str(result)

def both(left,right):
    return left and right

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

def count(value):
    return len(items(value))

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]

def is_empty(value):
    return count(value) == 0

def is_present(value):
    return value is not None and 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 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 page_size(value):
    if not re.fullmatch(r"[1-9][0-9]*", value) or int(value) > 2147483647: raise RuntimeError("Page size must be a positive int32")
    return 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 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 single(value):
    rows=items(value)
    if len(rows)!=1: raise RuntimeError('Expected exactly one selected record')
    return rows[0]

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():
    annual_year = positive_id(required("EXHIBITDAY_BUDGET_YEAR"))
    annual_page_size = page_size(optional("EXHIBITDAY_PAGE_SIZE", "100"))
    annual_workspace_response = call("workspace_binding", {}, None, None)
    require_condition(equal(response_status(annual_workspace_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
    annual_workspace = annual_workspace_response["body"]
    annual_workspace_id = positive_id(text(field(annual_workspace, "id")))
    annual_settings_response = call("workspace_calendar", {}, None, None)
    require_condition(equal(response_status(annual_settings_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
    annual_settings = annual_settings_response["body"]
    annual_currency = text(field(annual_settings, "workspace_currency_code"))
    annual_symbol = text(field(annual_settings, "workspace_currency_symbol"))
    annual_fiscal_month = text(field(annual_settings, "workspace_fiscal_year_start_month"))
    require_condition(is_present(annual_currency), "Confirm the actual workspace currency before comparing money.")
    annual_years_response = call("budget_years", {}, None, None)
    require_condition(equal(response_status(annual_years_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
    annual_current_response = call("annual_before", {"filter_by_budget_year": annual_year, "$include_record_revision": "true", "$limit": "2", "$offset": "0"}, None, None)
    require_condition(equal(response_status(annual_current_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
    annual_current_page = annual_current_response["body"]
    annual_current_rows = items(field(annual_current_page, "list_data"))
    require_condition(both(equal(text(field(annual_current_page, "records_found")), text(count(annual_current_rows))), equal(field(annual_current_page, "has_more"), False)), "Read the complete result for the selected year. Missing, duplicate or extra rows need review; this program does not set up or choose another budget.")
    require_condition(is_present(text(field(annual_current_page, "total_records"))), "The Annual report needs its current collection wrapper.")
    annual_current_row = single(annual_current_rows)
    require_condition(equal(text(field(annual_current_row, "budget_year")), annual_year), "The Annual row belongs to another budget year.")
    annual_id = positive_id(text(field(annual_current_row, "id")))
    annual_current_revision = text(field(annual_current_row, "record_revision"))
    require_condition(is_present(annual_current_revision), "The actual selected-year read must provide its revision; never construct one from displayed totals or Notes.")
    print_value({"budget_year": annual_year, "workspace_currency_code": annual_currency, "workspace_currency_symbol": annual_symbol, "workspace_fiscal_year_start_month": annual_fiscal_month, "fiscal_start_date": text(field(annual_current_row, "fiscal_start_date")), "fiscal_end_date": text(field(annual_current_row, "fiscal_end_date"))})
    annual_planned_count = required("EXHIBITDAY_PLANNED_NUM_EVENTS")
    annual_exhibit = required("EXHIBITDAY_PLANNED_EXHIBIT_AMOUNT")
    annual_sponsorship = required("EXHIBITDAY_PLANNED_SPONSORSHIP_AMOUNT")
    annual_notes = required("EXHIBITDAY_BUDGET_NOTES")
    annual_journal_path = required("EXHIBITDAY_JOURNAL")
    annual_job_id = required("EXHIBITDAY_JOB_ID")
    annual_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume")
    annual_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "45AF86C41CD65DE7F641F9AAB6E4C4CB8A74C7791F1239F3640EFABEA75F0BC6", "budget_year": annual_year, "workspace_currency_code": annual_currency, "workspace_currency_symbol": annual_symbol, "workspace_fiscal_year_start_month": annual_fiscal_month, "fiscal_start_date": text(field(annual_current_row, "fiscal_start_date")), "fiscal_end_date": text(field(annual_current_row, "fiscal_end_date")), "planned_num_events": annual_planned_count, "planned_exhibit_amount": annual_exhibit, "planned_sponsorship_amount": annual_sponsorship, "notes": annual_notes, "page_size": annual_page_size})
    annual_job = open_journal(annual_journal_path, "https://api.exhibitday.com/v1", annual_workspace_id, "annual-budgets-spending", annual_job_id, annual_input_fingerprint, [["update_plan", "PATCH", "/v1/financials/annual_budgets"]], annual_job_mode)
    try:
        annual_ack_revision = ""
        if journal_acknowledged(annual_job, "update_plan"):
            annual_saved = journal_saved(annual_job, "update_plan")
            require_condition(both(both(equal(text(field(annual_saved, "id")), annual_id), equal(text(field(annual_saved, "budget_year")), annual_year)), equal(text(field(annual_saved, "record_revision")), annual_current_revision)), "The confirmed year, row or current revision changed. Review current values instead of restoring a saved plan.")
            annual_ack_revision = text(field(annual_saved, "record_revision"))
        else:
            annual_patch = {"budget_year": annual_year, "planned_num_events": annual_planned_count, "planned_exhibit_amount": annual_exhibit, "planned_sponsorship_amount": annual_sponsorship, "notes": annual_notes, "expected_revision": annual_current_revision}
            annual_patch_fingerprint = journal_fingerprint({"budget_year": annual_year, "planned_num_events": annual_planned_count, "planned_exhibit_amount": annual_exhibit, "planned_sponsorship_amount": annual_sponsorship, "notes": annual_notes, "expected_revision": annual_current_revision})
            journal_begin(annual_job, "update_plan", "PATCH", "/v1/financials/annual_budgets", annual_patch_fingerprint)
            annual_patch_response = call("update_plan", {}, annual_patch, None)
            require_condition(equal(response_status(annual_patch_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
            annual_patch_receipt = annual_patch_response["body"]
            annual_ack_revision = text(field(annual_patch_receipt, "record_revision"))
            require_condition(is_present(annual_ack_revision), "The budget save needs its returned revision. Stop and review any uncertain save; never repeat it automatically.")
            journal_acknowledge(annual_job, "update_plan", {"id": annual_id, "budget_year": annual_year, "record_revision": annual_ack_revision})
        annual_confirm_response = call("annual_before", {"filter_by_budget_year": annual_year, "$include_record_revision": "true", "$limit": "2", "$offset": "0"}, None, None)
        require_condition(equal(response_status(annual_confirm_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
        annual_confirm_page = annual_confirm_response["body"]
        annual_confirm_rows = items(field(annual_confirm_page, "list_data"))
        require_condition(both(equal(text(field(annual_confirm_page, "records_found")), text(count(annual_confirm_rows))), equal(field(annual_confirm_page, "has_more"), False)), "Read the complete result for the selected year. Missing, duplicate or extra rows need review; this program does not set up or choose another budget.")
        require_condition(is_present(text(field(annual_confirm_page, "total_records"))), "The Annual report needs its current collection wrapper.")
        annual_confirm_row = single(annual_confirm_rows)
        require_condition(equal(text(field(annual_confirm_row, "budget_year")), annual_year), "The Annual row belongs to another budget year.")
        require_condition(both(both(both(equal(text(field(annual_confirm_row, "id")), annual_id), equal(text(field(annual_confirm_row, "record_revision")), annual_ack_revision)), equal(text(field(annual_confirm_row, "fiscal_start_date")), text(field(annual_current_row, "fiscal_start_date")))), equal(text(field(annual_confirm_row, "fiscal_end_date")), text(field(annual_current_row, "fiscal_end_date")))), "The current budget no longer matches its confirmed revision. Review it; do not repeat or restore the update.")
        annual_event_costs_query = {"filter_by_budget_year": annual_year, "$limit": annual_page_size}
        annual_event_costs_offset = "0"
        while True:
            annual_event_costs_query["$offset"] = annual_event_costs_offset
            annual_event_costs_response = call("event_cost_pages", annual_event_costs_query, None, None)
            require_condition(equal(response_status(annual_event_costs_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
            annual_event_costs_page = annual_event_costs_response["body"]
            annual_event_costs_rows = items(field(annual_event_costs_page, "list_data"))
            require_condition(equal(text(field(annual_event_costs_page, "records_found")), text(count(annual_event_costs_rows))), "records_found differs from the actual detail page rows.")
            require_condition(is_present(text(field(annual_event_costs_page, "total_records"))), "The detail collection needs total_records.")
            require_condition(either(equal(field(annual_event_costs_page, "has_more"), True), equal(field(annual_event_costs_page, "has_more"), False)), "Expected Boolean has_more in the detail wrapper.")
            print_value(annual_event_costs_response["raw"].decode("utf-8"))
            if equal(field(annual_event_costs_page, "has_more"), False):
                break
            require_condition(not_value(is_empty(annual_event_costs_rows)), "An empty detail page has_more=true; stop and review the changing report.")
            annual_event_costs_offset = add_offset(annual_event_costs_offset, count(annual_event_costs_rows))
        annual_misc_query = {"filter_by_budget_year": annual_year, "$limit": annual_page_size}
        annual_misc_offset = "0"
        while True:
            annual_misc_query["$offset"] = annual_misc_offset
            annual_misc_response = call("annual_misc_pages", annual_misc_query, None, None)
            require_condition(equal(response_status(annual_misc_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
            annual_misc_page = annual_misc_response["body"]
            annual_misc_rows = items(field(annual_misc_page, "list_data"))
            require_condition(equal(text(field(annual_misc_page, "records_found")), text(count(annual_misc_rows))), "records_found differs from the actual detail page rows.")
            require_condition(is_present(text(field(annual_misc_page, "total_records"))), "The detail collection needs total_records.")
            require_condition(either(equal(field(annual_misc_page, "has_more"), True), equal(field(annual_misc_page, "has_more"), False)), "Expected Boolean has_more in the detail wrapper.")
            print_value(annual_misc_response["raw"].decode("utf-8"))
            if equal(field(annual_misc_page, "has_more"), False):
                break
            require_condition(not_value(is_empty(annual_misc_rows)), "An empty detail page has_more=true; stop and review the changing report.")
            annual_misc_offset = add_offset(annual_misc_offset, count(annual_misc_rows))
        annual_centers_query = {"filter_by_budget_year": annual_year, "$limit": annual_page_size}
        annual_centers_offset = "0"
        while True:
            annual_centers_query["$offset"] = annual_centers_offset
            annual_centers_response = call("center_pages", annual_centers_query, None, None)
            require_condition(equal(response_status(annual_centers_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
            annual_centers_page = annual_centers_response["body"]
            annual_centers_rows = items(field(annual_centers_page, "list_data"))
            require_condition(equal(text(field(annual_centers_page, "records_found")), text(count(annual_centers_rows))), "records_found differs from the actual detail page rows.")
            require_condition(is_present(text(field(annual_centers_page, "total_records"))), "The detail collection needs total_records.")
            require_condition(either(equal(field(annual_centers_page, "has_more"), True), equal(field(annual_centers_page, "has_more"), False)), "Expected Boolean has_more in the detail wrapper.")
            print_value(annual_centers_response["raw"].decode("utf-8"))
            if equal(field(annual_centers_page, "has_more"), False):
                break
            require_condition(not_value(is_empty(annual_centers_rows)), "An empty detail page has_more=true; stop and review the changing report.")
            annual_centers_offset = add_offset(annual_centers_offset, count(annual_centers_rows))
        annual_final_response = call("annual_readback", {"filter_by_budget_year": annual_year, "$limit": "2", "$offset": "0"}, None, None)
        require_condition(equal(response_status(annual_final_response), "200"), "Expected the documented HTTP 200. Keep the pending step in the journal and review any other outcome before deciding what to do.")
        annual_final_page = annual_final_response["body"]
        annual_final_rows = items(field(annual_final_page, "list_data"))
        require_condition(both(equal(text(field(annual_final_page, "records_found")), text(count(annual_final_rows))), equal(field(annual_final_page, "has_more"), False)), "Read the complete result for the selected year. Missing, duplicate or extra rows need review; this program does not set up or choose another budget.")
        require_condition(is_present(text(field(annual_final_page, "total_records"))), "The Annual report needs its current collection wrapper.")
        annual_final_row = single(annual_final_rows)
        require_condition(equal(text(field(annual_final_row, "budget_year")), annual_year), "The Annual row belongs to another budget year.")
        require_condition(both(both(equal(text(field(annual_final_row, "id")), annual_id), equal(text(field(annual_final_row, "fiscal_start_date")), text(field(annual_current_row, "fiscal_start_date")))), equal(text(field(annual_final_row, "fiscal_end_date")), text(field(annual_current_row, "fiscal_end_date")))), "The final year was rebound to another saved budget.")
        print_value(annual_final_response["raw"].decode("utf-8"))
    finally:
        annual_job.close()


if __name__ == "__main__":
    main()

EXHIBITDAY_PY

Example response

{
  "records_found": 1,
  "total_records": 1,
  "has_more": false,
  "list_data": [
    {
      "id": 12345,
      "budget_year": 2030,
      "fiscal_start_date": "2029-07-01",
      "fiscal_end_date": "2030-06-30",
      "planned_num_events": 12,
      "actual_num_events": 0,
      "planned_exhibit_amount": 20000.13,
      "planned_sponsorship_amount": 5000.01,
      "allocated_event_amount": 0.00,
      "actual_exhibit_amount": 0.00,
      "actual_sponsorship_amount": 0.00,
      "planned_annual_misc_amount": 0.00,
      "actual_annual_misc_amount": 0.00,
      "total_planned_amount": 25000.14,
      "total_actual_amount": 0.00,
      "variance": 25000.14,
      "notes": "Revised after the spring planning meeting.",
      "annual_budget_created_timestamp": "2029-12-01T17:00:00Z",
      "annual_budget_last_update_timestamp": "2030-01-02T17:00:00Z"
    }
  ]
}
Note: Verified Annual Budget for FY2030. The final Annual Budget read after the update and the detail reports. Amounts can change between separate requests.

Things to keep in mind

  • Send amounts without a currency symbol or grouping commas. The API rounds money to two decimal places.
  • Planned Misc. Annual Expenses come from their own records. Update those records separately.
  • Reports can change between requests if someone edits in between. Review any differences before you rely on the comparison.

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.