Update Collateral Stock After a Delivery or Recount

Record a stock delivery or recount for Collateral at a Storage Location.

Example use case

A delivery contains 120 brochures. A later recount shows there were 118.

What you'll end up with

One stock adjustment at the selected Storage Location, with the received count or your corrected count after a recount.

Before you start

Have a workspace API key that can edit manual inventory, an Active Collateral item you own, and a Storage Location in your workspace.

Good to know

The program records the delivery first. If you supply a recount quantity, it corrects the same adjustment in a separate save.

At a glance

Time to try

About 10 minutes

Effect on your data

Creates and updates

Endpoints

4

The program records one stock adjustment and corrects it when you supply a recount quantity. It writes a private local journal.

How it works

  1. Choose an Active Collateral item and a Storage Location in your workspace. Supply the quantity received and, if you have one, the corrected count.
  2. The program records the delivery. With a recount quantity, it reads the saved revision and corrects that same adjustment.
  3. It verifies the saved increase and prints the adjustment ID and quantity.

Record and verify the stock adjustment

These requests show a delivery of 120 and a recount of 118. Without a recount quantity, the program skips the revision read and correction in Steps 3 and 4, then verifies the received quantity in Step 5.

Step 1: Confirm the workspace

Check where the key will make changes so you can confirm the workspace.

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

Example response (shortened)

{
  "id": 98765
}

Check: Confirm id is the workspace you intended to use.

Step 2: Record the stock delivery

Create one adjustment for the 120 brochures received at the selected location.

curl -X POST "https://api.exhibitday.com/v1/assets/inventory_adjustments" -H "Authorization: Bearer YOUR_API_KEY" -H "Idempotency-Key: YOUR_PERSISTED_ADJUSTMENT_KEY" -H "Content-Type: application/json" --data-binary "{\"asset_id\":1234,\"storage_location_id\":2345,\"quantity\":120,\"is_increase\":true,\"description\":\"Brochures received for Annual Expo\"}"

Example response (shortened)

{
  "id": 3456,
  "asset_id": 1234,
  "storage_location_id": 2345,
  "quantity_adjustment": 120,
  "quantity": 120,
  "is_increase": true,
  "description": "Brochures received for Annual Expo"
}

Check: Confirm the item, location and increase. Keep the returned adjustment id.

Step 3: Read the adjustment and its revision

Read the saved adjustment so the correction can check for intervening changes.

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

Example response (shortened)

{
  "id": 3456,
  "asset_id": 1234,
  "storage_location_id": 2345,
  "quantity_adjustment": 120,
  "quantity": 120,
  "is_increase": true,
  "description": "Brochures received for Annual Expo",
  "record_revision": "COPY_ADJUSTMENT_REVISION_FROM_YOUR_READ"
}

Check: Confirm the same adjustment, Asset and location. Keep its record_revision for the PATCH.

Step 4: Correct the increase after a recount

Set the same adjustment's quantity to 118 using the revision from your read.

curl -X PATCH "https://api.exhibitday.com/v1/assets/inventory_adjustments" -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" --data-binary "{\"id\":3456,\"quantity\":118,\"expected_revision\":\"COPY_ADJUSTMENT_REVISION_FROM_YOUR_READ\"}"

Example response (shortened)

{
  "status_code": 200,
  "status": "OK",
  "message": "Inventory Adjustment updated.",
  "errors": [],
  "record_revision": "NEW_ADJUSTMENT_REVISION"
}

Check: Look for the returned record_revision. The PATCH identifies the adjustment by id and leaves the Asset and location out.

Step 5: Verify the corrected stock movement

Read the adjustment normally to confirm the saved increase.

curl -X GET "https://api.exhibitday.com/v1/assets/inventory_adjustments/info?id=3456" -H "Authorization: Bearer YOUR_API_KEY"

Example response (shortened)

{
  "id": 3456,
  "asset_id": 1234,
  "storage_location_id": 2345,
  "quantity_adjustment": 118,
  "quantity": 118,
  "is_increase": true,
  "description": "Brochures received for Annual Expo"
}

Check: Confirm the same ID, item and location with an increase of 118. This is a stock movement. Use availability for the stock balance.

Try it

Before running the example

VariableWhat to put in itRequired?
EXHIBITDAY_API_KEYYour workspace API key.Yes
EXHIBITDAY_ASSET_IDThe ID of an Active Collateral item in your workspace.Yes
EXHIBITDAY_STORAGE_LOCATION_IDThe ID of the Storage Location where you received the stock.Yes
EXHIBITDAY_RECEIVED_QUANTITYThe number of items received, a whole number greater than zero.Yes
EXHIBITDAY_RECOUNT_QUANTITYThe corrected count after a recount, a whole number greater than zero. Leave it unset to skip the correction.No
EXHIBITDAY_JOB_IDA stable ID for this logical change.Yes
EXHIBITDAY_JOURNALA private local path for this job's journal.Yes
EXHIBITDAY_JOB_MODEUse new for a genuinely new job or resume with the existing journal. The default is resume.No

Bash

export EXHIBITDAY_API_KEY='YOUR_API_KEY'
export EXHIBITDAY_ASSET_ID='1234'
export EXHIBITDAY_STORAGE_LOCATION_ID='2345'
export EXHIBITDAY_RECEIVED_QUANTITY='120'
export EXHIBITDAY_RECOUNT_QUANTITY='118'
export EXHIBITDAY_JOB_ID='brochure-delivery-01'
export EXHIBITDAY_JOURNAL='/private/path/brochure-delivery-01.json'
export EXHIBITDAY_JOB_MODE='new'

PowerShell

$env:EXHIBITDAY_API_KEY = 'YOUR_API_KEY'
$env:EXHIBITDAY_ASSET_ID = '1234'
$env:EXHIBITDAY_STORAGE_LOCATION_ID = '2345'
$env:EXHIBITDAY_RECEIVED_QUANTITY = '120'
$env:EXHIBITDAY_RECOUNT_QUANTITY = '118'
$env:EXHIBITDAY_JOB_ID = 'brochure-delivery-01'
$env:EXHIBITDAY_JOURNAL = 'C:\private\path\brochure-delivery-01.json'
$env:EXHIBITDAY_JOB_MODE = 'new'

Use your own Collateral and Storage Location IDs and quantities. Then copy the complete example program below in your language and run it. For a new job, choose a new private journal path and stable job ID. To continue that job, use the same values and set EXHIBITDAY_JOB_MODE=resume.

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\"},\"create_adjustment\":{\"method\":\"POST\",\"path\":\"/assets/inventory_adjustments\"},\"read_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/info\"},\"correct_count\":{\"method\":\"PATCH\",\"path\":\"/assets/inventory_adjustments\"},\"verify_adjustment\":{\"method\":\"GET\",\"path\":\"/assets/inventory_adjustments/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("Persist a logical 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 both(left,right):
    return left and right

def bounded_whole_number(value, name, maximum):
    if not re.fullmatch(r"0|[1-9][0-9]*", value) or len(value)>len(maximum) or (len(value)==len(maximum) and value>maximum):
        raise RuntimeError(name+" must be a whole number from 0 through "+maximum)
    return 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_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 logical job")
            if mode=="new" and self.path.exists():raise JournalRefusal("A journal already exists; use resume for the same logical 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 acknowledged 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 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 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():
    inventory_asset_id = positive_id(required("EXHIBITDAY_ASSET_ID"))
    inventory_location_id = positive_id(required("EXHIBITDAY_STORAGE_LOCATION_ID"))
    inventory_journal_path = required("EXHIBITDAY_JOURNAL")
    inventory_job_id = required("EXHIBITDAY_JOB_ID")
    inventory_job_mode = optional("EXHIBITDAY_JOB_MODE", "resume")
    require_condition(either(equal(inventory_job_mode, "new"), equal(inventory_job_mode, "resume")), "Use exact new or resume for EXHIBITDAY_JOB_MODE.")
    inventory_received = bounded_whole_number(required("EXHIBITDAY_RECEIVED_QUANTITY"), "EXHIBITDAY_RECEIVED_QUANTITY", "2147483647")
    require_condition(not_value(equal(inventory_received, "0")), "EXHIBITDAY_RECEIVED_QUANTITY must be greater than zero.")
    inventory_recount = optional("EXHIBITDAY_RECOUNT_QUANTITY", "")
    inventory_expected = inventory_received
    if not_value(equal(inventory_recount, "")):
        inventory_recount = bounded_whole_number(inventory_recount, "EXHIBITDAY_RECOUNT_QUANTITY", "2147483647")
        require_condition(not_value(equal(inventory_recount, "0")), "EXHIBITDAY_RECOUNT_QUANTITY must be greater than zero.")
        inventory_expected = inventory_recount
    inventory_workspace_response = call("workspace_binding", {}, None, None)
    require_condition(equal(response_status(inventory_workspace_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.")
    inventory_workspace = inventory_workspace_response["body"]
    inventory_workspace_id = positive_id(text(field(inventory_workspace, "id")))
    inventory_input_fingerprint = journal_fingerprint({"workflow_contract_sha256": "F9CCD36E69D6E5A76E22B460D9FB853A89937E942238AAD7DF5A63BE8EA9F49D", "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "create_quantity": inventory_received, "correct_quantity": inventory_recount})
    inventory_job = open_journal(inventory_journal_path, "https://api.exhibitday.com/v1", inventory_workspace_id, "collateral-inventory-storage", inventory_job_id, inventory_input_fingerprint, [["create_adjustment", "POST", "/v1/assets/inventory_adjustments"], ["correct_count", "PATCH", "/v1/assets/inventory_adjustments"]], inventory_job_mode)
    try:
        require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), journal_acknowledged(inventory_job, "create_adjustment")), "A correction is acknowledged before its create. Stop and reconcile the journal.")
        require_condition(either(not_value(journal_acknowledged(inventory_job, "correct_count")), not_value(equal(inventory_recount, ""))), "This journal records a correction without a recount quantity. Stop and reconcile.")
        inventory_adjustment_id = ""
        if journal_acknowledged(inventory_job, "create_adjustment"):
            inventory_created_saved = journal_saved(inventory_job, "create_adjustment")
            inventory_adjustment_id = positive_id(text(field(inventory_created_saved, "id")))
            require_condition(both(equal(text(field(inventory_created_saved, "asset_id")), inventory_asset_id), equal(text(field(inventory_created_saved, "storage_location_id")), inventory_location_id)), "The saved adjustment belongs to different inventory or storage; do not create a replacement.")
        else:
            inventory_create_fingerprint = journal_fingerprint({"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": "true", "description": "Brochures received for Annual Expo"})
            inventory_create_intent = journal_begin(inventory_job, "create_adjustment", "POST", "/v1/assets/inventory_adjustments", inventory_create_fingerprint)
            inventory_create_response = call("create_adjustment", {}, {"asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_received, "is_increase": True, "description": "Brochures received for Annual Expo"}, text(field(inventory_create_intent, "idempotency_key")))
            require_condition(equal(response_status(inventory_create_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.")
            inventory_created = inventory_create_response["body"]
            inventory_adjustment_id = positive_id(text(field(inventory_created, "id")))
            require_condition(both(both(equal(text(field(inventory_created, "id")), inventory_adjustment_id), equal(text(field(inventory_created, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_created, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_created, "quantity_adjustment")), inventory_received), equal(text(field(inventory_created, "quantity")), inventory_received)), equal(field(inventory_created, "is_increase"), True)))), "The create acknowledgement differs from this item, location or stock increase. Keep pending state and reconcile.")
            journal_acknowledge(inventory_job, "create_adjustment", {"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id})
        if not_value(equal(inventory_recount, "")):
            inventory_read_response = call("read_adjustment", {"id": inventory_adjustment_id, "$include_record_revision": "true"}, None, None)
            require_condition(equal(response_status(inventory_read_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.")
            inventory_current = inventory_read_response["body"]
            if journal_acknowledged(inventory_job, "correct_count"):
                inventory_corrected_saved = journal_saved(inventory_job, "correct_count")
                require_condition(both(equal(text(field(inventory_corrected_saved, "id")), inventory_adjustment_id), both(equal(text(field(inventory_corrected_saved, "asset_id")), inventory_asset_id), both(equal(text(field(inventory_corrected_saved, "storage_location_id")), inventory_location_id), equal(text(field(inventory_corrected_saved, "quantity")), inventory_recount)))), "The acknowledged correction differs from this record or quantity; stop and reconcile.")
                require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_recount), equal(text(field(inventory_current, "quantity")), inventory_recount)), equal(field(inventory_current, "is_increase"), True)))), "The acknowledged adjustment is now missing, rebound or changed; do not silently restore it.")
            else:
                require_condition(both(both(equal(text(field(inventory_current, "id")), inventory_adjustment_id), equal(text(field(inventory_current, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_current, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_current, "quantity_adjustment")), inventory_received), equal(text(field(inventory_current, "quantity")), inventory_received)), equal(field(inventory_current, "is_increase"), True)))), "The saved adjustment is no longer the expected stock increase. Review it before any correction.")
                inventory_revision = text(field(inventory_current, "record_revision"))
                require_condition(is_present(inventory_revision), "The inventory read must return its actual record_revision before correction.")
                inventory_patch = {"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision}
                inventory_patch_fingerprint = journal_fingerprint({"id": inventory_adjustment_id, "quantity": inventory_recount, "expected_revision": inventory_revision})
                journal_begin(inventory_job, "correct_count", "PATCH", "/v1/assets/inventory_adjustments", inventory_patch_fingerprint)
                inventory_patch_response = call("correct_count", {}, inventory_patch, None)
                require_condition(equal(response_status(inventory_patch_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.")
                inventory_patch_receipt = inventory_patch_response["body"]
                inventory_after_revision = text(field(inventory_patch_receipt, "record_revision"))
                require_condition(is_present(inventory_after_revision), "A checked correction acknowledgement requires its returned record_revision.")
                journal_acknowledge(inventory_job, "correct_count", {"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_recount, "record_revision": inventory_after_revision})
        inventory_verify_response = call("verify_adjustment", {"id": inventory_adjustment_id}, None, None)
        require_condition(equal(response_status(inventory_verify_response), "200"), "Expected the documented HTTP200 response. Preserve any pending intent and reconcile another outcome.")
        inventory_verified = inventory_verify_response["body"]
        require_condition(both(both(equal(text(field(inventory_verified, "id")), inventory_adjustment_id), equal(text(field(inventory_verified, "asset_id")), inventory_asset_id)), both(equal(text(field(inventory_verified, "storage_location_id")), inventory_location_id), both(both(equal(text(field(inventory_verified, "quantity_adjustment")), inventory_expected), equal(text(field(inventory_verified, "quantity")), inventory_expected)), equal(field(inventory_verified, "is_increase"), True)))), "The final adjustment does not match the acknowledged record, location and stock increase. Reconcile; do not add another adjustment or undo it automatically.")
        print_value({"id": inventory_adjustment_id, "asset_id": inventory_asset_id, "storage_location_id": inventory_location_id, "quantity": inventory_expected})
    finally:
        inventory_job.close()


if __name__ == "__main__":
    main()

EXHIBITDAY_PY

Example response

{
  "id": 3456,
  "asset_id": 1234,
  "asset_name": "Annual Expo brochures",
  "storage_location_id": 2345,
  "storage_location_name": "Main Storage",
  "effective_date": "2030-01-02",
  "return_date": null,
  "quantity_adjustment": 118,
  "quantity": 118,
  "is_increase": true,
  "is_quantity_editable": true,
  "description": "Brochures received for Annual Expo",
  "shipping_logistics_id": 1,
  "is_flagged": false,
  "is_starred": false,
  "is_checked": false,
  "inventory_adjustment_created_timestamp": "2030-01-02T12:00:00Z"
}
Note: The adjustment as read after the correction. It increases stock by 118 instead of 120. Use availability to check the stock balance.

Things to keep in mind

  • The create uses today's date in the workspace time zone. To use a different date, review the POST date options and supply effective_date. The correction leaves the saved date in place.
  • New manual adjustments have no scheduled reversal. A PATCH that changes an older adjustment clears its scheduled reversal. An unchanged adjustment keeps it. Check the saved return date before correcting an older adjustment.
  • Use Asset availability for a dated stock balance and Collateral transactions for the supporting movements. Read every page you need. Inventory can be negative.
  • To delete an adjustment only if no one has changed it since your read, send its record_revision as expected_revision with the DELETE request. A changed adjustment returns HTTP 409 record_changed and nothing is deleted.
  • Creating or deleting a Storage Location is separate. When a location still holds Assets or inventory, review the transfer options before deleting it.

If a run stops

  • Keep the journal private. It records what the program tried to save and which save it confirmed.
  • To continue a run with no unresolved save, use EXHIBITDAY_JOB_MODE=resume with the same job ID, journal path and inputs.
  • Use the same quantities when resuming. A resumed run skips acknowledged writes and checks the same adjustment.
  • If a save stops with a lost response, check the saved adjustment and inventory in ExhibitDay before running the program again.
  • If you still need a change after checking the old run, use EXHIBITDAY_JOB_MODE=new with a new job ID and journal path.
  • Run only one copy per journal.
  • If a crash leaves a .lock file, make sure no copy using that journal is running or can start. Then remove the lock file and keep the journal.