Compare commits

...

5 Commits

6 changed files with 1239 additions and 24 deletions
+6
View File
@@ -0,0 +1,6 @@
# The contents of the local user agent crontab
# Used to maintain and document the automated tasks for this system
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# m h dom mon dow command
4 4-23 * * * . /home/npsagent/.config/servicem8-webhooks.env; cd /opt/webhooks && flock -n /tmp/servicem8-quote-template.lock ./poll_and_apply_quote_templates.sh --hours 6 >> /opt/webhooks/logs/cron-driver.log 2>&1
+108 -10
View File
@@ -115,7 +115,7 @@ def build_quote_description_text(description: str, job: Dict[str, Any]) -> str:
def build_job_update_payload(description: str, job: Dict[str, Any]) -> dict:
quote_description = build_quote_description_text(description, job)
return {"job_description": quote_description} if quote_description else {}
return {"work_done_description": quote_description} if quote_description else {}
def retrieve_job(session: requests.Session, job_uuid: str) -> Dict[str, Any]:
@@ -131,7 +131,56 @@ def retrieve_job(session: requests.Session, job_uuid: str) -> Dict[str, Any]:
def update_job_description(session: requests.Session, job_uuid: str, payload: dict) -> None:
response = session.post(f"{BASE_URL}/job/{job_uuid}.json", json=payload, timeout=REQUEST_TIMEOUT)
if not response.ok:
raise RuntimeError(f"Job description update failed: HTTP {response.status_code} :: {response.text[:1000]}")
raise RuntimeError(f"Job quote description update failed: HTTP {response.status_code} :: {response.text[:1000]}")
def extract_company_name(job: Dict[str, Any]) -> str:
related = job.get("related")
if isinstance(related, dict):
company = related.get("company")
if isinstance(company, dict):
company_name = clean_text(company.get("name"))
if company_name:
return company_name
company = job.get("company")
if isinstance(company, dict):
company_name = clean_text(company.get("name"))
if company_name:
return company_name
return first_text(job.get("company_name"), job.get("customer_name"))
def upsert_job_metadata(conn: sqlite3.Connection, *, job_uuid: str, job: Dict[str, Any], source: str) -> None:
job_uuid = clean_text(job_uuid or job.get("uuid"))
if not job_uuid:
return
now = utc_now()
conn.execute(
"""
INSERT INTO job_metadata (
job_uuid, generated_job_id, job_address, company_name, raw_json,
first_seen_at, last_seen_at, source
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(job_uuid) DO UPDATE SET
generated_job_id = excluded.generated_job_id,
job_address = excluded.job_address,
company_name = excluded.company_name,
raw_json = excluded.raw_json,
last_seen_at = excluded.last_seen_at,
source = excluded.source
""",
(
job_uuid,
clean_text(job.get("generated_job_id")),
format_job_address(job),
extract_company_name(job),
json.dumps(job, ensure_ascii=False, sort_keys=True),
now,
now,
source,
),
)
conn.commit()
def create_job_material(session: requests.Session, payload: dict) -> str:
@@ -187,6 +236,21 @@ def get_conn(db_path: Path = POLL_DB_PATH) -> sqlite3.Connection:
def init_apply_tables(conn: sqlite3.Connection) -> None:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS job_metadata (
job_uuid TEXT PRIMARY KEY,
generated_job_id TEXT,
job_address TEXT,
company_name TEXT,
raw_json TEXT NOT NULL,
first_seen_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL,
source TEXT NOT NULL
)
"""
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_job_metadata_generated_job_id ON job_metadata(generated_job_id)")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS quote_template_apply_runs (
@@ -467,6 +531,8 @@ def main() -> int:
quote_description_source = clean_text(quote["description"])
job_details = retrieve_job(session, job_uuid) if quote_description_source else {}
if job_details:
upsert_job_metadata(conn, job_uuid=job_uuid, job=job_details, source=mode)
job_update_payload = build_job_update_payload(quote_description_source, job_details)
job_update_record_payload = {
"endpoint": f"/job/{job_uuid}.json",
@@ -475,13 +541,44 @@ def main() -> int:
"job_address": format_job_address(job_details) if job_details else "",
}
job_update_row = {
"kind": "job_description",
"kind": "work_done_description",
"source_question": "Description of Works to be Quoted",
"name": job_update_payload.get("job_description", ""),
"name": job_update_payload.get("work_done_description", ""),
}
if not args.apply:
remote_existing_rows = list_remote_job_materials(session, job_uuid)
remote_existing_blocks_apply = bool(remote_existing_rows)
if remote_existing_blocks_apply:
remote_active_count = sum(1 for remote_row in remote_existing_rows if is_active_remote_job_material(remote_row))
reason = (
f"Remote ServiceM8 job already has {len(remote_existing_rows)} jobMaterial row(s) "
f"({remote_active_count} active); apply would be blocked before updates or creates"
)
incident_id = record_remote_existing_incident(
conn,
form_response_uuid=form_response_uuid,
job_uuid=job_uuid,
apply_run_id=run_id,
desired_count=len(desired_rows),
remote_rows=remote_existing_rows,
action="dry_run_would_block",
reason=reason,
)
result["remote_existing"] = {
"incident_id": incident_id,
"action": "would_block_remote_existing",
"remote_count": len(remote_existing_rows),
"remote_active_count": remote_active_count,
"reason": reason,
}
if job_update_payload:
job_update_action = (
"would_update_work_done_description_if_remote_empty"
if remote_existing_blocks_apply
else "would_update_work_done_description"
)
record_apply_row(
conn,
run_id=run_id,
@@ -490,13 +587,14 @@ def main() -> int:
row_index=0,
row=job_update_row,
api_payload=job_update_record_payload,
action="would_update_job_description",
action=job_update_action,
)
result["job_update"] = {"action": "would_update_job_description", **job_update_record_payload}
result["job_update"] = {"action": job_update_action, **job_update_record_payload}
else:
result["job_update"] = {"action": "skipped", "reason": "Quote description is empty"}
for idx, row in enumerate(desired_rows, start=1):
api_payload = build_payload(job_uuid, row)
row_action = "would_create_if_remote_empty" if remote_existing_blocks_apply else "would_create"
record_apply_row(
conn,
run_id=run_id,
@@ -505,9 +603,9 @@ def main() -> int:
row_index=idx,
row=row,
api_payload=api_payload,
action="would_create",
action=row_action,
)
result["rows"].append({"action": "would_create", "kind": row.get("kind"), "payload": api_payload})
result["rows"].append({"action": row_action, "kind": row.get("kind"), "payload": api_payload})
finish_apply_run(conn, run_id, status="dry-run", created_count=0)
conn.execute(
"UPDATE quote_template_form_responses SET process_status = ? WHERE form_response_uuid = ?",
@@ -568,9 +666,9 @@ def main() -> int:
row_index=0,
row=job_update_row,
api_payload=job_update_record_payload,
action="updated_job_description",
action="updated_work_done_description",
)
result["job_update"] = {"action": "updated_job_description", **job_update_record_payload}
result["job_update"] = {"action": "updated_work_done_description", **job_update_record_payload}
else:
result["job_update"] = {"action": "skipped", "reason": "Quote description is empty"}
+440
View File
@@ -0,0 +1,440 @@
# List all Job Allocations
#### Filtering
This endpoint supports result filtering. For more information on how to filter this request, [go here](/docs/filtering).
#### OAuth Scope
This endpoint requires the following OAuth scope **read_schedule**.
# OpenAPI definition
```json
{
"openapi": "3.1.0",
"info": {
"title": "ServiceM8 API",
"description": "Move your app forward with the ServiceM8 API\n\n\n\n## Limits and Throttling\nTo ensure continuous quality of service, API usage can be subject to throttling. The throttle will be applied once an API consumer reaches a certain \nthreshold in terms of a maximum number of requests per minute. Most clients will never hit this threshold, but those that do, will get met by a \nHTTP 429 Too Many Requests response code. \n \nThere is a limit of 180 requests per minute, if you reach this you will receive a HTTP 429 with a text body of \"Number of allowed API requests per minute exceeded\".\nThere is a limit of 20000 requests per day, if you reach this you will receive a HTTP 429 with a text body of \"Number of allowed API requests per day exceeded\".\n\nWe encourage all API developers to anticipate this error, and take appropriate measures like e.g. using a cached value from a previous call, or passing on a message to the end user that gets subjected to this behaviour (if any).\n\nLimits are per Addon per account.\n",
"termsOfService": "https://www.servicem8.com/terms-of-service",
"version": "1.0.0"
},
"servers": [
{
"url": "https://api.servicem8.com/api_1.0"
}
],
"security": [
{
"apiKey": []
},
{
"oauth2": []
}
],
"paths": {
"/joballocation.json": {
"get": {
"tags": [
"Job Allocations"
],
"operationId": "listJobAllocations",
"summary": "List all Job Allocations",
"description": "\n\t\t\t\n#### Filtering\nThis endpoint supports result filtering. For more information on how to filter this request, [go here](/docs/filtering).\n\t\t\t\n\t\t\t\n#### OAuth Scope\nThis endpoint requires the following OAuth scope **read_schedule**.\n\n\t\t\t",
"security": [
{
"apiKey": []
},
{
"oauth2": [
"read_schedule"
]
}
],
"responses": {
"200": {
"description": "An array of Job Allocations",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/JobAllocation"
}
},
"examples": {
"success": {
"value": [
{
"uuid": "123e4567-aa11-4415-ac38-23f94bc904db",
"active": 1,
"edit_date": "2026-03-01 12:00:00",
"job_uuid": "123e4567-ef33-4570-9929-23f945326d1b",
"queue_uuid": "123e4567-e495-4a8d-a253-23f9408ba0db",
"staff_uuid": "123e4567-e0d8-481f-b4bb-23f944e9c86b",
"allocation_date": "2026-03-01 12:00:00",
"allocation_window_uuid": "123e4567-0f0c-48b9-8570-23f94fcc00db",
"allocated_by_staff_uuid": "123e4567-ab70-4071-8066-23f94537066b",
"allocated_timestamp": "2026-03-01 12:00:00",
"expiry_timestamp": "2026-03-01 12:00:00",
"read_timestamp": "2026-03-01 12:00:00",
"completion_timestamp": "2026-03-01 12:00:00",
"estimated_duration": "string",
"revised_duration": "string",
"sort_priority": "string",
"requires_acceptance": "string",
"acceptance_status": "string",
"acceptance_timestamp": "2026-03-01 12:00:00"
}
]
}
}
}
}
},
"400": {
"description": "Bad Request - The request is malformed or contains invalid parameters",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
},
"examples": {
"badRequest": {
"value": {
"errorCode": "1000",
"message": "An error occurred completing your request"
}
}
}
}
}
},
"401": {
"description": "Unauthorized - Authentication credentials are missing or invalid",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AuthenticationError"
},
"examples": {
"unauthorized": {
"value": {
"errorCode": "401",
"message": "Authentication failed. Please check your API key or OAuth token."
}
}
}
}
}
},
"403": {
"description": "Forbidden - You don't have permission to access this resource",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ForbiddenError"
},
"examples": {
"forbidden": {
"value": {
"errorCode": "403",
"message": "Access forbidden. You don't have permission to access this resource."
}
}
}
}
}
},
"429": {
"description": "Too Many Requests - You have exceeded the rate limit",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RateLimitError"
},
"examples": {
"rateLimitMinute": {
"value": {
"errorCode": 429,
"message": "Number of allowed API requests per minute exceeded"
}
},
"rateLimitDay": {
"value": {
"errorCode": 429,
"message": "Number of allowed API requests per day exceeded"
}
}
}
}
}
},
"500": {
"description": "Internal Server Error - An unexpected error occurred on the server",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
},
"examples": {
"serverError": {
"value": {
"errorCode": 500,
"message": "An unexpected error occurred. Please try again later."
}
}
}
}
}
}
}
}
}
},
"components": {
"securitySchemes": {
"apiKey": {
"type": "apiKey",
"name": "X-Api-Key",
"in": "header"
},
"oauth2": {
"type": "oauth2",
"flows": {
"authorizationCode": {
"authorizationUrl": "https://api.servicem8.com/oauth/authorize",
"tokenUrl": "https://api.servicem8.com/oauth/access_token",
"scopes": {
"staff_locations": "Access to real-time GPS information about staff",
"staff_activity": "Access to clock on, lunch break and clock off information about staff",
"publish_sms": "Access to send SMS messages to customers and/or staff on your behalf. Note sending SMS messages will incur account charges.",
"publish_email": "Access to send Email messages to customers and/or staff on your behalf",
"vendor": "Access to basic account information",
"vendor_logo": "Access to account logo",
"vendor_email": "Access to account holder email address",
"read_locations": "Read-only access to Location Endpoint",
"manage_locations": "Full access to Location Endpoint",
"read_staff": "Read-only access to Staff Endpoint",
"manage_staff": "Full access to Staff Endpoint",
"read_customers": "Read-only access to Company Endpoint",
"manage_customers": "Full access to Company Endpoint",
"read_customer_contacts": "Read-only access to CompanyContact Endpoint",
"manage_customer_contacts": "Full access to CompanyContact Endpoint",
"read_jobs": "Read-only access to Job Endpoint",
"manage_jobs": "Full access to Job Endpoint",
"create_jobs": "Ability to create jobs on behalf of account. Note creating jobs may incur account charges.",
"read_job_contacts": "Read-only access to JobContact Endpoint",
"manage_job_contacts": "Full access to JobContact Endpoint",
"read_job_materials": "Read-only access to JobMaterials Endpoint",
"manage_job_materials": "Full access to JobMaterials Endpoint",
"read_job_categories": "Read-only access to Categories Endpoint",
"manage_job_categories": "Full access to Categories Endpoint",
"read_job_queues": "Read-only access to Job Queues Endpoint",
"manage_job_queues": "Full access to Job Queues Endpoint",
"read_tasks": "Read-only access to Tasks Endpoint",
"manage_tasks": "Full access to Tasks Endpoint",
"read_schedule": "Read-only access to JobActivity Endpoint",
"manage_schedule": "Full access to JobActivity Endpoint",
"read_inventory": "Read-only access to Materials Endpoint",
"manage_inventory": "Full access to Materials Endpoint",
"read_job_notes": "Read-only access to job notes",
"publish_job_notes": "Ability to add new job notes",
"read_job_photos": "Read-only access to job photos",
"publish_job_photos": "Ability to add new job photos",
"read_attachments": "Read-only access to Attachments Endpoint",
"manage_attachments": "Full access to Attachments Endpoint",
"read_inbox": "Read-only access to inbox messages",
"read_messages": "Read-only access to staff messages",
"manage_notifications": "Ability to read notifications and mark as read",
"manage_templates": "Full-access to email, sms and document templates",
"manage_badges": "Full-access to create/modify job badges",
"read_assets": "Read-only access to Assets Endpoint",
"manage_assets": "Full access to Assets Endpoint",
"read_knowledge_base": "Read-only access to Knowledge Base Endpoint",
"manage_knowledge_base": "Full access to Knowledge Base Endpoint"
}
}
}
}
},
"schemas": {
"Error": {
"type": "object",
"properties": {
"errorCode": {
"type": "number",
"format": "int32",
"example": "1000"
},
"message": {
"type": "string",
"example": "An error occurred completing your request"
}
}
},
"RateLimitError": {
"type": "object",
"properties": {
"errorCode": {
"type": "number",
"format": "int32",
"example": "429"
},
"message": {
"type": "string",
"example": "Number of allowed API requests per minute exceeded"
}
}
},
"AuthenticationError": {
"type": "object",
"properties": {
"errorCode": {
"type": "number",
"format": "int32",
"example": "401"
},
"message": {
"type": "string",
"example": "Authentication failed. Please check your API key or OAuth token."
}
}
},
"ForbiddenError": {
"type": "object",
"properties": {
"errorCode": {
"type": "number",
"format": "int32",
"example": "403"
},
"message": {
"type": "string",
"example": "Access forbidden. You don't have permission to access this resource."
}
}
},
"JobAllocation": {
"type": "object",
"properties": {
"job_uuid": {
"description": "The UUID of the job that this allocation relates to.",
"format": "uuid",
"example": "123e4567-796e-43d3-89b8-23f942b7f0ab",
"type": "string"
},
"queue_uuid": {
"description": "DEPRECATED"
},
"staff_uuid": {
"description": "The UUID of the staff member this job is allocated to.",
"format": "uuid",
"example": "123e4567-4525-400b-ab3e-23f94473c62b",
"type": "string"
},
"allocation_date": {
"description": "The minimum start date for a job allocation to be completed by a staff member. Setting this date will ensure the job allocation appears in the future on staff schedules.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"allocation_window_uuid": {
"description": "The UUID of the allocation window that defines when the job should be completed (e.g. Urgent, Early Morning, During Business Hours).",
"format": "uuid",
"example": "123e4567-7fd1-45f3-8068-23f945565e9b",
"type": "string"
},
"allocated_by_staff_uuid": {
"description": "The UUID of the staff member who allocated the job.",
"format": "uuid",
"example": "123e4567-c873-4cca-91e7-23f943de293b",
"type": "string"
},
"allocated_timestamp": {
"description": "The timestamp when the job was allocated.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"expiry_timestamp": {
"description": "The timestamp when the job allocation expires.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"read_timestamp": {
"description": "The timestamp when the job allocation was read by the staff member.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"completion_timestamp": {
"description": "The timestamp when the job allocation was marked as completed.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"estimated_duration": {
"description": "DEPRECATED"
},
"revised_duration": {
"description": "DEPRECATED"
},
"sort_priority": {
"description": "The sort priority for displaying this job allocation.",
"type": "string"
},
"requires_acceptance": {
"description": "DEPRECATED"
},
"acceptance_status": {
"description": "DEPRECATED"
},
"acceptance_timestamp": {
"description": "DEPRECATED"
},
"uuid": {
"format": "uuid",
"description": "Unique identifier for this record",
"example": "123e4567-8160-4f2d-951a-23f94c5382cb",
"type": "string"
},
"active": {
"enum": [
0,
1
],
"type": "integer",
"default": 1,
"description": "Record active/deleted flag. Valid values are [0,1]"
},
"edit_date": {
"example": "2026-03-01 12:00:00",
"readOnly": true,
"description": "Timestamp at which record was last modified"
}
}
}
}
},
"x-speakeasy-retries": {
"strategy": "backoff",
"backoff": {
"initialInterval": 500,
"maxInterval": 60000,
"maxElapsedTime": 3600000,
"exponent": 1.5
},
"statusCodes": [
"5XX",
"429"
],
"retryConnectionErrors": true
},
"tags": [
{
"name": "Job Allocations",
"description": "Operations related to Job Allocations"
}
]
}
```
+468
View File
@@ -0,0 +1,468 @@
# List all Staff Members
#### Filtering
This endpoint supports result filtering. For more information on how to filter this request, [go here](/docs/filtering).
#### OAuth Scope
This endpoint requires the following OAuth scope **read_staff**.
# OpenAPI definition
```json
{
"openapi": "3.1.0",
"info": {
"title": "ServiceM8 API",
"description": "Move your app forward with the ServiceM8 API\n\n\n\n## Limits and Throttling\nTo ensure continuous quality of service, API usage can be subject to throttling. The throttle will be applied once an API consumer reaches a certain \nthreshold in terms of a maximum number of requests per minute. Most clients will never hit this threshold, but those that do, will get met by a \nHTTP 429 Too Many Requests response code. \n \nThere is a limit of 180 requests per minute, if you reach this you will receive a HTTP 429 with a text body of \"Number of allowed API requests per minute exceeded\".\nThere is a limit of 20000 requests per day, if you reach this you will receive a HTTP 429 with a text body of \"Number of allowed API requests per day exceeded\".\n\nWe encourage all API developers to anticipate this error, and take appropriate measures like e.g. using a cached value from a previous call, or passing on a message to the end user that gets subjected to this behaviour (if any).\n\nLimits are per Addon per account.\n",
"termsOfService": "https://www.servicem8.com/terms-of-service",
"version": "1.0.0"
},
"servers": [
{
"url": "https://api.servicem8.com/api_1.0"
}
],
"security": [
{
"apiKey": []
},
{
"oauth2": []
}
],
"paths": {
"/staff.json": {
"get": {
"tags": [
"Staff Members"
],
"operationId": "listStaffMembers",
"summary": "List all Staff Members",
"description": "\n\t\t\t\n#### Filtering\nThis endpoint supports result filtering. For more information on how to filter this request, [go here](/docs/filtering).\n\t\t\t\n\t\t\t\n#### OAuth Scope\nThis endpoint requires the following OAuth scope **read_staff**.\n\n\t\t\t",
"security": [
{
"apiKey": []
},
{
"oauth2": [
"read_staff"
]
}
],
"responses": {
"200": {
"description": "An array of Staff Members",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Staff"
}
},
"examples": {
"success": {
"value": [
{
"first": "string",
"last": "string",
"email": "string",
"mobile": "string",
"lng": "number",
"lat": "number",
"geo_timestamp": "2026-03-01 12:00:00",
"job_title": "string",
"navigating_to_job_uuid": "123e4567-ed86-4242-b22f-23f949021d4b",
"navigating_timestamp": "2026-03-01 12:00:00",
"navigating_expiry_timestamp": "2026-03-01 12:00:00",
"color": "string",
"custom_icon_url": "string",
"status_message": "string",
"status_message_timestamp": "2026-03-01 12:00:00",
"hide_from_schedule": "string",
"uuid": "123e4567-ce52-4b1f-8564-23f94e82d3cb",
"active": 1,
"edit_date": "2026-03-01 12:00:00",
"can_receive_push_notification": "string",
"security_role_uuid": "123e4567-873a-46dc-b21b-23f9497ac49b",
"labour_material_uuid": "123e4567-bd3b-4d18-af43-23f941752a7b"
}
]
}
}
}
}
},
"400": {
"description": "Bad Request - The request is malformed or contains invalid parameters",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
},
"examples": {
"badRequest": {
"value": {
"errorCode": "1000",
"message": "An error occurred completing your request"
}
}
}
}
}
},
"401": {
"description": "Unauthorized - Authentication credentials are missing or invalid",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AuthenticationError"
},
"examples": {
"unauthorized": {
"value": {
"errorCode": "401",
"message": "Authentication failed. Please check your API key or OAuth token."
}
}
}
}
}
},
"403": {
"description": "Forbidden - You don't have permission to access this resource",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ForbiddenError"
},
"examples": {
"forbidden": {
"value": {
"errorCode": "403",
"message": "Access forbidden. You don't have permission to access this resource."
}
}
}
}
}
},
"429": {
"description": "Too Many Requests - You have exceeded the rate limit",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RateLimitError"
},
"examples": {
"rateLimitMinute": {
"value": {
"errorCode": 429,
"message": "Number of allowed API requests per minute exceeded"
}
},
"rateLimitDay": {
"value": {
"errorCode": 429,
"message": "Number of allowed API requests per day exceeded"
}
}
}
}
}
},
"500": {
"description": "Internal Server Error - An unexpected error occurred on the server",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
},
"examples": {
"serverError": {
"value": {
"errorCode": 500,
"message": "An unexpected error occurred. Please try again later."
}
}
}
}
}
}
}
}
}
},
"components": {
"securitySchemes": {
"apiKey": {
"type": "apiKey",
"name": "X-Api-Key",
"in": "header"
},
"oauth2": {
"type": "oauth2",
"flows": {
"authorizationCode": {
"authorizationUrl": "https://api.servicem8.com/oauth/authorize",
"tokenUrl": "https://api.servicem8.com/oauth/access_token",
"scopes": {
"staff_locations": "Access to real-time GPS information about staff",
"staff_activity": "Access to clock on, lunch break and clock off information about staff",
"publish_sms": "Access to send SMS messages to customers and/or staff on your behalf. Note sending SMS messages will incur account charges.",
"publish_email": "Access to send Email messages to customers and/or staff on your behalf",
"vendor": "Access to basic account information",
"vendor_logo": "Access to account logo",
"vendor_email": "Access to account holder email address",
"read_locations": "Read-only access to Location Endpoint",
"manage_locations": "Full access to Location Endpoint",
"read_staff": "Read-only access to Staff Endpoint",
"manage_staff": "Full access to Staff Endpoint",
"read_customers": "Read-only access to Company Endpoint",
"manage_customers": "Full access to Company Endpoint",
"read_customer_contacts": "Read-only access to CompanyContact Endpoint",
"manage_customer_contacts": "Full access to CompanyContact Endpoint",
"read_jobs": "Read-only access to Job Endpoint",
"manage_jobs": "Full access to Job Endpoint",
"create_jobs": "Ability to create jobs on behalf of account. Note creating jobs may incur account charges.",
"read_job_contacts": "Read-only access to JobContact Endpoint",
"manage_job_contacts": "Full access to JobContact Endpoint",
"read_job_materials": "Read-only access to JobMaterials Endpoint",
"manage_job_materials": "Full access to JobMaterials Endpoint",
"read_job_categories": "Read-only access to Categories Endpoint",
"manage_job_categories": "Full access to Categories Endpoint",
"read_job_queues": "Read-only access to Job Queues Endpoint",
"manage_job_queues": "Full access to Job Queues Endpoint",
"read_tasks": "Read-only access to Tasks Endpoint",
"manage_tasks": "Full access to Tasks Endpoint",
"read_schedule": "Read-only access to JobActivity Endpoint",
"manage_schedule": "Full access to JobActivity Endpoint",
"read_inventory": "Read-only access to Materials Endpoint",
"manage_inventory": "Full access to Materials Endpoint",
"read_job_notes": "Read-only access to job notes",
"publish_job_notes": "Ability to add new job notes",
"read_job_photos": "Read-only access to job photos",
"publish_job_photos": "Ability to add new job photos",
"read_attachments": "Read-only access to Attachments Endpoint",
"manage_attachments": "Full access to Attachments Endpoint",
"read_inbox": "Read-only access to inbox messages",
"read_messages": "Read-only access to staff messages",
"manage_notifications": "Ability to read notifications and mark as read",
"manage_templates": "Full-access to email, sms and document templates",
"manage_badges": "Full-access to create/modify job badges",
"read_assets": "Read-only access to Assets Endpoint",
"manage_assets": "Full access to Assets Endpoint",
"read_knowledge_base": "Read-only access to Knowledge Base Endpoint",
"manage_knowledge_base": "Full access to Knowledge Base Endpoint"
}
}
}
}
},
"schemas": {
"Error": {
"type": "object",
"properties": {
"errorCode": {
"type": "number",
"format": "int32",
"example": "1000"
},
"message": {
"type": "string",
"example": "An error occurred completing your request"
}
}
},
"RateLimitError": {
"type": "object",
"properties": {
"errorCode": {
"type": "number",
"format": "int32",
"example": "429"
},
"message": {
"type": "string",
"example": "Number of allowed API requests per minute exceeded"
}
}
},
"AuthenticationError": {
"type": "object",
"properties": {
"errorCode": {
"type": "number",
"format": "int32",
"example": "401"
},
"message": {
"type": "string",
"example": "Authentication failed. Please check your API key or OAuth token."
}
}
},
"ForbiddenError": {
"type": "object",
"properties": {
"errorCode": {
"type": "number",
"format": "int32",
"example": "403"
},
"message": {
"type": "string",
"example": "Access forbidden. You don't have permission to access this resource."
}
}
},
"Staff": {
"type": "object",
"properties": {
"first": {
"description": "Staff First Name",
"type": "string",
"maxLength": 30
},
"last": {
"description": "Staff Last Name",
"type": "string",
"maxLength": 30
},
"email": {
"description": "Staff Email Address. This is also your login name.",
"format": "email",
"type": "string"
},
"mobile": {
"description": "Mobile phone number of the staff member. Used for SMS communications and identification when calling.",
"type": "string"
},
"lng": {
"description": "Longitude coordinate of the staff member's current or last known location. Used for tracking staff locations and calculating routes and travel distances.",
"type": "number",
"format": "float"
},
"lat": {
"description": "Latitude coordinate of the staff member's current or last known location. Used for tracking staff locations and calculating routes and travel distances.",
"type": "number",
"format": "float"
},
"geo_timestamp": {
"description": "The date and time when the staff member's geographic location (lat/lng) was last updated. Format is YYYY-MM-DD HH:MM:SS. Used to determine how recent the location data is.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"job_title": {
"description": "The staff member's job title or role within the organization. Used for organizational purposes and displayed in various places throughout the system.",
"type": "string"
},
"navigating_to_job_uuid": {
"description": "UUID of the job the staff member is currently navigating to. Used to track which job a staff member is traveling toward.",
"format": "uuid",
"example": "123e4567-11b0-4089-8ab2-23f9484d54ab",
"type": "string"
},
"navigating_timestamp": {
"description": "The date and time when the staff member started navigating to a job. Format is YYYY-MM-DD HH:MM:SS. Used to track when navigation began.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"navigating_expiry_timestamp": {
"description": "The date and time when navigation to a job is expected to complete or expire. Format is YYYY-MM-DD HH:MM:SS. Used to determine if navigation is still active.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"color": {
"description": "The color assigned to this staff member, represented as a hex color code. Used for visual identification in the schedule, dispatch board, and other interfaces.",
"type": "string"
},
"custom_icon_url": {
"description": "DEPRECATED"
},
"status_message": {
"description": "Short message summarising the staff's current status.",
"type": "string"
},
"status_message_timestamp": {
"description": "The date and time when the staff member's status message was last updated. Format is YYYY-MM-DD HH:MM:SS. Used to determine how recent the status message is.",
"example": "2026-03-01 12:00:00",
"type": "string"
},
"hide_from_schedule": {
"description": "Boolean flag controlling whether this staff member appears in the schedule view. When true (1), the staff member is hidden from the schedule. When false (0), they appear normally in scheduling interfaces.. Valid values are [0,1]",
"type": "integer",
"enum": [
0,
1
]
},
"uuid": {
"format": "uuid",
"description": "Unique identifier for this record",
"example": "123e4567-9fa9-46c2-9e1d-23f94b3418fb",
"type": "string"
},
"active": {
"enum": [
0,
1
],
"type": "integer",
"default": 1,
"description": "Record active/deleted flag. Valid values are [0,1]"
},
"edit_date": {
"example": "2026-03-01 12:00:00",
"readOnly": true,
"description": "Timestamp at which record was last modified"
},
"can_receive_push_notification": {
"type": "string"
},
"security_role_uuid": {
"format": "uuid",
"example": "123e4567-4ff4-4f95-8521-23f9452e9a2b",
"type": "string"
},
"labour_material_uuid": {
"format": "uuid",
"example": "123e4567-5c47-4d54-b8e7-23f94882c18b",
"type": "string"
}
},
"required": [
"first",
"last",
"email"
]
}
}
},
"x-speakeasy-retries": {
"strategy": "backoff",
"backoff": {
"initialInterval": 500,
"maxInterval": 60000,
"maxElapsedTime": 3600000,
"exponent": 1.5
},
"statusCodes": [
"5XX",
"429"
],
"retryConnectionErrors": true
},
"tags": [
{
"name": "Staff Members",
"description": "Operations related to Staff Members"
}
]
}
```
+139
View File
@@ -144,6 +144,21 @@ def init_db(db_path: Path) -> None:
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS job_metadata (
job_uuid TEXT PRIMARY KEY,
generated_job_id TEXT,
job_address TEXT,
company_name TEXT,
raw_json TEXT NOT NULL,
first_seen_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL,
source TEXT NOT NULL
)
"""
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_job_metadata_generated_job_id ON job_metadata(generated_job_id)")
conn.commit()
@@ -205,6 +220,109 @@ def fetch_form_responses(
return response.status_code, data, filter_expr
def retrieve_job(
*,
api_key: str,
base_url: str,
job_uuid: str,
timeout: int,
) -> Dict[str, Any]:
response = requests.get(
f"{base_url.rstrip('/')}/job/{job_uuid}.json",
headers={"X-Api-Key": api_key, "Accept": "application/json"},
timeout=timeout,
)
if not response.ok:
raise RuntimeError(f"Job retrieve failed for {job_uuid}: HTTP {response.status_code}: {response.text[:1000]}")
data = response.json()
if not isinstance(data, dict):
raise RuntimeError(f"Job retrieve expected object response, got {type(data).__name__}")
return data
def clean_text(value: Any) -> str:
if value is None:
return ""
return str(value).replace("\r\n", "\n").replace("\r", "\n").strip()
def first_text(*values: Any) -> str:
for value in values:
text = clean_text(value)
if text:
return text
return ""
def format_job_address(job: Dict[str, Any]) -> str:
direct = first_text(
job.get("job_address"),
job.get("site_address"),
job.get("address"),
job.get("location_address"),
job.get("billing_address"),
)
if direct:
return direct
parts = [
first_text(job.get("street"), job.get("street_address"), job.get("address_1"), job.get("address1")),
first_text(job.get("suburb"), job.get("city")),
first_text(job.get("state")),
first_text(job.get("postcode"), job.get("postal_code"), job.get("zip")),
]
return " ".join(part for part in parts if part)
def extract_company_name(job: Dict[str, Any]) -> str:
related = job.get("related")
if isinstance(related, dict):
company = related.get("company")
if isinstance(company, dict):
company_name = clean_text(company.get("name"))
if company_name:
return company_name
company = job.get("company")
if isinstance(company, dict):
company_name = clean_text(company.get("name"))
if company_name:
return company_name
return first_text(job.get("company_name"), job.get("customer_name"))
def upsert_job_metadata(conn: sqlite3.Connection, *, job_uuid: str, job: Dict[str, Any], now: str, source: str) -> None:
job_uuid = clean_text(job_uuid or job.get("uuid"))
if not job_uuid:
return
values = (
job_uuid,
clean_text(job.get("generated_job_id")),
format_job_address(job),
extract_company_name(job),
json.dumps(job, ensure_ascii=False, sort_keys=True),
now,
now,
source,
)
conn.execute(
"""
INSERT INTO job_metadata (
job_uuid, generated_job_id, job_address, company_name, raw_json,
first_seen_at, last_seen_at, source
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(job_uuid) DO UPDATE SET
generated_job_id = excluded.generated_job_id,
job_address = excluded.job_address,
company_name = excluded.company_name,
raw_json = excluded.raw_json,
last_seen_at = excluded.last_seen_at,
source = excluded.source
""",
values,
)
def insert_or_update_raw(
conn: sqlite3.Connection,
row: Dict[str, Any],
@@ -457,6 +575,7 @@ def main() -> int:
inserted = updated = quote_matches = newly_queued = 0
now = utc_now()
fetched_job_uuids = set()
if conn is not None:
for row in rows:
was_inserted, is_quote = insert_or_update_raw(
@@ -469,6 +588,26 @@ def main() -> int:
updated += 0 if was_inserted else 1
if is_quote:
quote_matches += 1
job_uuid = clean_text(row.get("regarding_object_uuid"))
if job_uuid and job_uuid not in fetched_job_uuids:
try:
job = retrieve_job(
api_key=api_key,
base_url=args.base_url,
job_uuid=job_uuid,
timeout=args.timeout,
)
upsert_job_metadata(conn, job_uuid=job_uuid, job=job, now=now, source="formresponse_poll")
fetched_job_uuids.add(job_uuid)
except Exception as exc:
# Polling/parsing should still proceed if job metadata enrichment fails.
print(
json.dumps(
{"warning": "job_metadata_fetch_failed", "job_uuid": job_uuid, "error": str(exc)},
ensure_ascii=False,
),
file=sys.stderr,
)
if parse_and_store_quote_response(
conn,
row,
+78 -14
View File
@@ -68,6 +68,7 @@ def html_page(title: str, body: str) -> HTMLResponse:
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
pre { white-space: pre-wrap; word-break: break-word; background: #0f172a; color: #e2e8f0; padding: 14px; border-radius: 10px; overflow-x: auto; }
.pill { display: inline-block; padding: 2px 8px; border-radius: 999px; background: #e0f2fe; color: #075985; font-size: 0.85rem; margin: 2px 4px 2px 0; }
.job-id { font-weight: 700; color: #111827; }
.section { margin: 24px 0; }
.toolbar { background: white; border: 1px solid #e5e7eb; border-radius: 10px; padding: 12px; margin-bottom: 16px; }
input[type='text'] { padding: 8px; width: 280px; max-width: 100%; }
@@ -139,6 +140,63 @@ def link_with_params(path, **params):
return f"{path}?{urlencode(filtered)}" if filtered else path
def resolve_generated_job_id(job_uuid: str) -> str:
job_uuid = str(job_uuid or "").strip()
if not job_uuid:
return ""
try:
with closing(get_poll_conn()) as conn:
row = conn.execute(
"select generated_job_id from job_metadata where job_uuid = ?",
(job_uuid,),
).fetchone()
if row and row["generated_job_id"]:
return str(row["generated_job_id"])
except sqlite3.Error:
pass
try:
with closing(get_conn()) as conn:
row = conn.execute(
"""
with jobs as (
select
json_extract(payload_json, '$.data.uuid') as job_uuid,
json_extract(payload_json, '$.data.generated_job_id') as generated_job_id,
received_at
from webhook_events
where json_extract(payload_json, '$.data.generated_job_id') is not null
union all
select
json_extract(payload_json, '$.related.job.uuid') as job_uuid,
json_extract(payload_json, '$.related.job.generated_job_id') as generated_job_id,
received_at
from webhook_form_responses
where json_extract(payload_json, '$.related.job.generated_job_id') is not null
)
select generated_job_id
from jobs
where job_uuid = ?
and generated_job_id is not null
order by received_at desc
limit 1
""",
(job_uuid,),
).fetchone()
if row and row["generated_job_id"]:
return str(row["generated_job_id"])
except sqlite3.Error:
pass
return ""
def job_id_html(job_uuid: str) -> str:
generated_job_id = resolve_generated_job_id(job_uuid)
return f"<span class='job-id'>{escape(generated_job_id)}</span>" if generated_job_id else ""
@app.get("/health")
def health():
return {"ok": True, "db_path": DB_PATH, "state_db_path": STATE_DB_PATH, "poll_db_path": POLL_DB_PATH}
@@ -459,6 +517,7 @@ def list_generated_materials(page: int = Query(1, ge=1)):
table_rows.append(
f"<tr>"
f"<td><a href='/generated-materials/{row['id']}'>{row['id']}</a></td>"
f"<td>{job_id_html(row['job_uuid'])}</td>"
f"<td>{escape(row['job_uuid'] or '')}</td>"
f"<td>{escape(row['form_response_uuid'] or '')}</td>"
f"<td>{escape(row['job_material_uuid'] or '')}</td>"
@@ -470,8 +529,8 @@ def list_generated_materials(page: int = Query(1, ge=1)):
body = f"""
<table>
<thead><tr><th>ID</th><th>Job UUID</th><th>Form response UUID</th><th>Job material UUID</th><th>Kind</th><th>Source question</th><th>Updated</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='7'>No rows found.</td></tr>"}</tbody>
<thead><tr><th>ID</th><th>Job ID</th><th>Job UUID</th><th>Form response UUID</th><th>Job material UUID</th><th>Kind</th><th>Source question</th><th>Updated</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='8'>No rows found.</td></tr>"}</tbody>
</table>
<div class='pagination'>
{f"<a href='{link_with_params('/generated-materials', page=page-1)}'>← Prev</a>" if page > 1 else ''}
@@ -495,6 +554,7 @@ def generated_material_detail(row_id: int):
body = f"""
<div class='card summary-grid'>
<div><strong>ID</strong></div><div>{row['id']}</div>
<div><strong>Job ID</strong></div><div>{job_id_html(row['job_uuid'])}</div>
<div><strong>Job UUID</strong></div><div>{escape(row['job_uuid'] or '')}</div>
<div><strong>Form response UUID</strong></div><div>{escape(row['form_response_uuid'] or '')}</div>
<div><strong>Job material UUID</strong></div><div>{escape(row['job_material_uuid'] or '')}</div>
@@ -585,15 +645,15 @@ def list_remote_existing_incidents(page: int = Query(1, ge=1)):
f"<tr><td><a href='/poll/remote-existing-incidents/{row['id']}'>{row['id']}</a></td>"
f"<td>{escape(row['detected_at'] or '')}</td><td>{escape(row['action'] or '')}</td>"
f"<td><a href='/poll/quote-template/{escape(row['form_response_uuid'])}'>{escape(row['form_response_uuid'])}</a></td>"
f"<td>{escape(row['job_uuid'] or '')}</td><td>{run_link}</td>"
f"<td>{job_id_html(row['job_uuid'])}</td><td>{escape(row['job_uuid'] or '')}</td><td>{run_link}</td>"
f"<td>{row['desired_count']}</td><td>{row['remote_count']}</td><td>{row['remote_active_count']}</td>"
f"<td>{escape((row['reason'] or '')[:180])}</td></tr>"
)
body = f"""
<table>
<thead><tr><th>ID</th><th>Detected</th><th>Action</th><th>Form response UUID</th><th>Job UUID</th><th>Apply run</th><th>Desired</th><th>Remote rows</th><th>Active</th><th>Reason</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='10'>No remote-existing incidents found.</td></tr>"}</tbody>
<thead><tr><th>ID</th><th>Detected</th><th>Action</th><th>Form response UUID</th><th>Job ID</th><th>Job UUID</th><th>Apply run</th><th>Desired</th><th>Remote rows</th><th>Active</th><th>Reason</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='11'>No remote-existing incidents found.</td></tr>"}</tbody>
</table>
<div class='pagination'>
{f"<a href='{link_with_params('/poll/remote-existing-incidents', page=page-1)}'>← Prev</a>" if page > 1 else ''}
@@ -631,6 +691,7 @@ def remote_existing_incident_detail(incident_id: int):
<div><strong>Detected</strong></div><div>{escape(row['detected_at'] or '')}</div>
<div><strong>Action</strong></div><div>{escape(row['action'] or '')}</div>
<div><strong>Form response UUID</strong></div><div><a href='/poll/quote-template/{escape(row['form_response_uuid'])}'>{escape(row['form_response_uuid'])}</a></div>
<div><strong>Job ID</strong></div><div>{job_id_html(row['job_uuid'])}</div>
<div><strong>Job UUID</strong></div><div>{escape(row['job_uuid'] or '')}</div>
<div><strong>Apply run</strong></div><div>{run_link}</div>
<div><strong>Desired rows</strong></div><div>{row['desired_count']}</div>
@@ -668,14 +729,14 @@ def list_apply_runs(page: int = Query(1, ge=1)):
f"<tr><td><a href='/poll/apply-runs/{row['id']}'>{row['id']}</a></td>"
f"<td>{escape(row['mode'] or '')}</td><td>{escape(row['status'] or '')}</td>"
f"<td><a href='/poll/quote-template/{escape(row['form_response_uuid'])}'>{escape(row['form_response_uuid'])}</a></td>"
f"<td>{escape(row['job_uuid'] or '')}</td><td>{escape(row['started_at'] or '')}</td><td>{escape(row['finished_at'] or '')}</td>"
f"<td>{job_id_html(row['job_uuid'])}</td><td>{escape(row['job_uuid'] or '')}</td><td>{escape(row['started_at'] or '')}</td><td>{escape(row['finished_at'] or '')}</td>"
f"<td>{row['desired_count']}</td><td>{row['created_count']}</td><td>{escape((row['error'] or '')[:160])}</td></tr>"
)
body = f"""
<table>
<thead><tr><th>ID</th><th>Mode</th><th>Status</th><th>Form response UUID</th><th>Job UUID</th><th>Started</th><th>Finished</th><th>Desired</th><th>Created</th><th>Error</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='10'>No apply runs found yet.</td></tr>"}</tbody>
<thead><tr><th>ID</th><th>Mode</th><th>Status</th><th>Form response UUID</th><th>Job ID</th><th>Job UUID</th><th>Started</th><th>Finished</th><th>Desired</th><th>Created</th><th>Error</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='11'>No apply runs found yet.</td></tr>"}</tbody>
</table>
<div class='pagination'>
{f"<a href='{link_with_params('/poll/apply-runs', page=page-1)}'>← Prev</a>" if page > 1 else ''}
@@ -727,6 +788,7 @@ def apply_run_detail(run_id: int):
<div><strong>Mode</strong></div><div>{escape(run['mode'] or '')}</div>
<div><strong>Status</strong></div><div>{escape(run['status'] or '')}</div>
<div><strong>Form response UUID</strong></div><div><a href='/poll/quote-template/{escape(run['form_response_uuid'])}'>{escape(run['form_response_uuid'])}</a></div>
<div><strong>Job ID</strong></div><div>{job_id_html(run['job_uuid'])}</div>
<div><strong>Job UUID</strong></div><div>{escape(run['job_uuid'] or '')}</div>
<div><strong>Started</strong></div><div>{escape(run['started_at'] or '')}</div>
<div><strong>Finished</strong></div><div>{escape(run['finished_at'] or '')}</div>
@@ -816,7 +878,7 @@ def list_polled_form_responses(q: str = Query(""), quote_only: int = Query(0), p
f"<tr><td><a href='/poll/form-responses/{escape(row['uuid'])}'>{escape(row['uuid'])}</a></td>"
f"<td>{escape(row['timestamp'] or '')}</td><td>{escape(row['edit_date'] or '')}</td>"
f"<td>{escape(row['form_uuid'] or '')}<br>{quote_pill}</td>"
f"<td>{escape(row['regarding_object'] or '')}</td><td>{escape(row['regarding_object_uuid'] or '')}</td>"
f"<td>{escape(row['regarding_object'] or '')}</td><td>{job_id_html(row['regarding_object_uuid'])}</td><td>{escape(row['regarding_object_uuid'] or '')}</td>"
f"<td>{escape(row['parse_status'] or '')}</td><td>{row['seen_count']}</td><td>{escape(row['last_seen_at'] or '')}</td></tr>"
)
@@ -830,8 +892,8 @@ def list_polled_form_responses(q: str = Query(""), quote_only: int = Query(0), p
</form>
</div>
<table>
<thead><tr><th>UUID</th><th>Timestamp</th><th>Edit date</th><th>Form UUID</th><th>Regarding</th><th>Object UUID</th><th>Parse</th><th>Seen</th><th>Last seen</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='9'>No rows found.</td></tr>"}</tbody>
<thead><tr><th>UUID</th><th>Timestamp</th><th>Edit date</th><th>Form UUID</th><th>Regarding</th><th>Job ID</th><th>Object UUID</th><th>Parse</th><th>Seen</th><th>Last seen</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='10'>No rows found.</td></tr>"}</tbody>
</table>
<div class='pagination'>
{f"<a href='{link_with_params('/poll/form-responses', q=q, quote_only=quote_only, page=page-1)}'>← Prev</a>" if page > 1 else ''}
@@ -871,6 +933,7 @@ def polled_form_response_detail(form_response_uuid: str):
<div><strong>Edit date</strong></div><div>{escape(row['edit_date'] or '')}</div>
<div><strong>Form UUID</strong></div><div>{escape(row['form_uuid'] or '')}</div>
<div><strong>Regarding object</strong></div><div>{escape(row['regarding_object'] or '')}</div>
<div><strong>Job ID</strong></div><div>{job_id_html(row['regarding_object_uuid'])}</div>
<div><strong>Regarding UUID</strong></div><div>{escape(row['regarding_object_uuid'] or '')}</div>
<div><strong>First seen</strong></div><div>{escape(row['first_seen_at'] or '')}</div>
<div><strong>Last seen</strong></div><div>{escape(row['last_seen_at'] or '')}</div>
@@ -911,15 +974,15 @@ def list_polled_quote_templates(page: int = Query(1, ge=1)):
material_count = "?"
table_rows.append(
f"<tr><td><a href='/poll/quote-template/{escape(row['form_response_uuid'])}'>{escape(row['form_response_uuid'])}</a></td>"
f"<td>{escape(row['discovered_at'] or '')}</td><td>{escape(row['job_uuid'] or '')}</td>"
f"<td>{escape(row['discovered_at'] or '')}</td><td>{job_id_html(row['job_uuid'])}</td><td>{escape(row['job_uuid'] or '')}</td>"
f"<td>{escape(row['description'] or '')}</td><td>{material_count}</td>"
f"<td>{escape(row['queued_at'] or '')}</td><td>{escape(row['process_status'] or '')}</td></tr>"
)
body = f"""
<table>
<thead><tr><th>Form response UUID</th><th>Discovered</th><th>Job UUID</th><th>Description</th><th>Rows</th><th>Queued</th><th>Status</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='7'>No quote template rows found.</td></tr>"}</tbody>
<thead><tr><th>Form response UUID</th><th>Discovered</th><th>Job ID</th><th>Job UUID</th><th>Description</th><th>Rows</th><th>Queued</th><th>Status</th></tr></thead>
<tbody>{''.join(table_rows) or "<tr><td colspan='8'>No quote template rows found.</td></tr>"}</tbody>
</table>
<div class='pagination'>
{f"<a href='{link_with_params('/poll/quote-template', page=page-1)}'>← Prev</a>" if page > 1 else ''}
@@ -979,6 +1042,7 @@ def polled_quote_template_detail(form_response_uuid: str):
<div class='card summary-grid'>
<div><strong>Form response UUID</strong></div><div>{escape(row['form_response_uuid'])}</div>
<div><strong>Discovered</strong></div><div>{escape(row['discovered_at'] or '')}</div>
<div><strong>Job ID</strong></div><div>{job_id_html(row['job_uuid'])}</div>
<div><strong>Job UUID</strong></div><div>{escape(row['job_uuid'] or '')}</div>
<div><strong>Form UUID</strong></div><div>{escape(row['form_uuid'] or '')}</div>
<div><strong>Author</strong></div><div>{escape(row['author_name'] or '')}</div>