import { logActivity, startActivity } from "@olenbetong/appframe-core"; import { DataProviderHandlerAPI } from "@olenbetong/appframe-data"; import Giai from "./utils/Giai"; export type AddElementSource = "manual" | "camera-barcode" | "loading-list" | "hid-barcode" | "hid-rfid"; export type ElementDetails = { Domain: string; PrimKey: string; Created: Date; ProjectID: string; ProjectName: string; ProjectDomain: string; ElementID: string; DisplayName: string; GiaiUri: string; }; const elementsDataHandler = new DataProviderHandlerAPI({ dataSourceId: "aviw_Fleet_DeliveryTickets_ElementsLookup", fields: [ { name: "PrimKey", type: "string" }, { name: "Created", type: "datetime" }, { name: "Domain", type: "string" }, { name: "ProjectID", type: "string" }, { name: "ProjectName", type: "string" }, { name: "ProjectDomain", type: "string" }, { name: "ElementID", type: "string" }, { name: "DisplayName", type: "string" }, { name: "GiaiUri", type: "string" }, ], }); const elementDetailsCache = new Map(); export type ElementFilter = { projectId: string; elementId: string; }; export type GetElementContext = { filter?: string | ElementFilter; mode?: AddElementSource; method?: "cache" | "database"; result?: null | ElementDetails; }; export async function getElement(id: string | ElementFilter, context: GetElementContext): Promise { let details: ElementDetails; context.filter = id; if (typeof id === "string" && elementDetailsCache.has(id)) { details = elementDetailsCache.get(id) as ElementDetails; context.method = "cache"; context.result = details; logActivity("GetElement", context); } else { context.method = "database"; let logActivity = startActivity("GetElement", context); let whereClause: string; if (typeof id === "string") { let uri = Giai.fromString(id); whereClause = `[GiaiUri] = '${uri.toEpcPureIdentityUri()}'`; } else { whereClause = `[ProjectID] = '${id.projectId}' AND [ElementID] = '${id.elementId}'`; } let result = await elementsDataHandler.retrieve({ whereClause, }); if (!result.length) { context.result = null; logActivity(); throw Error(`Element not found`); } details = result[0]; context.result = details; logActivity(); if (typeof id === "string") { elementDetailsCache.set(id, details); } } return details; }