A screen and an export should answer the same question. I built a small independent Python module that interprets conditions once, freezes a selection and lets pages and summaries read that selection.
The implementation uses fixed synthetic rows rather than company records. The viewer below displays evidence saved by actual local example runs; it does not execute Python, query a database or operate a production service in the browser.
Constrain the input before defining behavior
The input is an already-read collection of at most one thousand synthetic rows plus company, status and search conditions. Identifiers use a bounded ASCII format, ticks are nonnegative safe integers and quantities are integers from one to ninety-nine. Booleans are rejected even though Python normally treats them as integers. Unknown query keys and unsupported states fail explicitly.
These constraints are an experimental contract rather than a universal ERP schema. A real server must select company scope and readable fields from an authenticated context. Passing a company string to this function does not authorize access to that company. The caller is trusted to provide an authorized read, and that assumption is part of the published implementation rather than an implied feature.
Let several operations consume one selection
make_snapshot normalizes the conditions, applies a case-insensitive ID substring search and sorts selected rows by tick and identifier. It copies only four permitted fields into immutable tuples. Additional source fields, such as internal notes, are excluded from every returned projection. page, export_rows and summary consume the same Snapshot instead of interpreting conditions again.
Concatenating all pages must exactly equal the complete export result. The summary totals quantities, not sales or accounting money, and export_rows returns Python values rather than generating or delivering a file. I document those limits because a function name can easily imply a finished product workflow. Output formats and financial units need their own explicit contract when this model is integrated.
Fingerprint both conditions and selected contents
The caller supplies a revision number describing its data boundary. The fingerprint also includes company, conditions and projected contents, so accidentally reusing that number does not conceal changed data. An existing Snapshot remains unchanged when its source array is edited or cleared. Continuing an earlier selection and refreshing to current data therefore remain distinct actions.
A cursor encodes that fingerprint and the last row’s tick and identifier as base64 JSON. A different selection or nonexistent position is rejected. This is neither signing nor encryption: a caller who knows a valid position can construct another cursor within the same snapshot. A test deliberately demonstrates that fact. Record authorization and any required cursor signatures remain server responsibilities, not properties provided by an opaque-looking string.
Explore the implementation
Complete independent synthetic implementation
"""Independent synthetic read snapshot. No database/auth service or signed cursors.
The company query must be chosen from trusted server context, never client authority.
"""
from dataclasses import dataclass
import json,hashlib,base64,re
def ident(v):return isinstance(v,str) and re.fullmatch('[A-Za-z0-9_-]{1,40}',v) is not None
def packed(v):return json.dumps(v,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False)
@dataclass(frozen=True)
class Snapshot:
company_id:str
status:str
query:str
revision:int
fingerprint:str
rows:tuple
def make_snapshot(records,query,revision):
if not isinstance(records,list) or len(records)>1000 or not isinstance(query,dict) or set(query)-{'company_id','status','q'} or not ident(query.get('company_id')) or type(revision) is not int or not 0<=revision<=9007199254740991:raise ValueError('Invalid snapshot input')
status=query.get('status','all');q=query.get('q','')
if status not in ['all','draft','sent'] or not isinstance(q,str) or len(q)>40:raise ValueError('Invalid query')
q=q.casefold();seen=set();selected=[]
for row in records:
if not isinstance(row,dict) or not ident(row.get('company_id')) or not ident(row.get('id')) or type(row.get('tick')) is not int or not 0<=row['tick']<=9007199254740991 or type(row.get('quantity')) is not int or not 1<=row['quantity']<=99 or row.get('status') not in ['draft','sent']:raise ValueError('Invalid synthetic record')
identity=(row['company_id'],row['id'])
if identity in seen:raise ValueError('Duplicate scoped record')
seen.add(identity)
if row['company_id']!=query['company_id'] or status!='all' and row['status']!=status or q not in row['id'].casefold():continue
selected.append((row['tick'],row['id'],row['quantity'],row['status']))
rows=tuple(sorted(selected,key=lambda r:(r[0],r[1])))
fingerprint=hashlib.sha256(packed([query['company_id'],status,q,revision,rows]).encode('utf-8')).hexdigest()
return Snapshot(query['company_id'],status,q,revision,fingerprint,rows)
def export_rows(snapshot):return [{'id':r[1],'tick':r[0],'quantity':r[2],'status':r[3]} for r in snapshot.rows]
def summary(snapshot):return {'count':len(snapshot.rows),'quantity':sum(r[2] for r in snapshot.rows),'revision':snapshot.revision,'snapshot':snapshot.fingerprint}
def page(snapshot,limit=2,cursor=None):
if type(limit) is not int or not 1<=limit<=50:raise ValueError('Page limit')
start=0
if cursor is not None:
if not isinstance(cursor,str) or len(cursor)>500:raise ValueError('Invalid cursor')
try:
value=json.loads(base64.b64decode(cursor+'='*((-len(cursor))%4),altchars=b'-_',validate=True).decode('utf-8'))
except (ValueError,UnicodeError):raise ValueError('Invalid cursor') from None
if not isinstance(value,dict) or set(value)!= {'snapshot','after'} or value['snapshot']!=snapshot.fingerprint or not isinstance(value['after'],list) or len(value['after'])!=2:raise ValueError('Cursor snapshot mismatch')
key=value['after']
if type(key[0]) is not int or not ident(key[1]):raise ValueError('Invalid cursor key')
matches=[i for i,r in enumerate(snapshot.rows) if (r[0],r[1])==tuple(key)]
if not matches:raise ValueError('Unknown cursor position')
start=matches[0]+1
chunk=snapshot.rows[start:start+limit];next_cursor=None
if chunk and start+len(chunk)<len(snapshot.rows):next_cursor=base64.urlsafe_b64encode(packed({'snapshot':snapshot.fingerprint,'after':list(chunk[-1][:2])}).encode('utf-8')).decode('ascii').rstrip('=')
return {'rows':[{'id':r[1],'tick':r[0],'quantity':r[2],'status':r[3]} for r in chunk],'next_cursor':next_cursor,'revision':snapshot.revision,'snapshot':snapshot.fingerprint}
def synthetic_records():return [{'company_id':'A','id':'S01','tick':1,'quantity':6,'status':'draft'},{'company_id':'A','id':'S02','tick':1,'quantity':4,'status':'sent'},{'company_id':'A','id':'S03','tick':2,'quantity':3,'status':'draft'},{'company_id':'B','id':'S01','tick':1,'quantity':9,'status':'draft'}]Separate verified evidence from missing integration
Fourteen local tests passed, and the downloaded package was extracted into a fresh directory and tested again. Checks cover equal-tick ordering, every page against full output, field projection, empty results, invalid inputs, invalid cursors and preservation after source changes. The selector below presents three fixed records from actual local runs; it neither reads a visitor’s company data nor creates a new database task.
An immutable copy cannot repair an input that was already assembled from inconsistent database reads. A production store needing a consistent boundary must implement that read first. This module has no persistent snapshot service, expiry policy, authentication, generated export file or rendered-browser verification. The small code’s passing tests are evidence for its contract, not an operational guarantee for an entire service.
Choose the integration policy before reuse
Start by deciding whether the workflow needs the latest moving list or continuation of one comparable read. Then choose the authorized read boundary, retention period, large-result strategy and output format. Copying the code without resolving these decisions can merely move the original ambiguity elsewhere. I would establish those responsibilities before connecting a screen.
The ZIP includes complete implementation, tests, a synthetic example runner, recorded results and reuse guidance. It is independent of an actual company’s interface or data. After changes, rerun page-to-export equivalence and preservation of earlier snapshots before claiming the contract still holds. The useful deliverable is evidence that several outputs answer one question, as well as the code that produces them.