Add special-order product flow for sales opportunities
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
import { createRoute } from "../../../modules/api-utils/createRoute";
|
||||
import { opportunities } from "../../../managers/opportunities";
|
||||
import { procurement } from "../../../managers/procurement";
|
||||
import { apiResponse } from "../../../modules/api-utils/apiResponse";
|
||||
import { ContentfulStatusCode } from "hono/utils/http-status";
|
||||
import { authMiddleware } from "../../middleware/authorization";
|
||||
import { z } from "zod";
|
||||
|
||||
const specialOrderItemSchema = z
|
||||
.object({
|
||||
desc: z.string().min(1),
|
||||
customerDesc: z.string().min(1).optional(),
|
||||
qty: z.number().positive().optional(),
|
||||
price: z.number(),
|
||||
cost: z.number().optional(),
|
||||
taxable: z.boolean().optional(),
|
||||
taxableFlag: z.boolean().optional(),
|
||||
procurementNotes: z.string().optional(),
|
||||
productNarrative: z.string().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const addSpecialOrderSchema = z.union([
|
||||
specialOrderItemSchema,
|
||||
z
|
||||
.array(specialOrderItemSchema)
|
||||
.min(1, "At least one special-order product is required"),
|
||||
]);
|
||||
|
||||
/* POST /v1/sales/opportunities/:identifier/products/special-order */
|
||||
export default createRoute(
|
||||
"post",
|
||||
["/opportunities/:identifier/products/special-order"],
|
||||
async (c) => {
|
||||
const identifier = c.req.param("identifier");
|
||||
const body = await c.req.json();
|
||||
|
||||
const validated = addSpecialOrderSchema.parse(body);
|
||||
const inputItems = Array.isArray(validated) ? validated : [validated];
|
||||
const specialOrderCatalogItem =
|
||||
await procurement.fetchItem("SPECIAL ORDER");
|
||||
|
||||
const makeCustomField = (
|
||||
caption: string,
|
||||
value: string,
|
||||
fieldId: number,
|
||||
) => ({
|
||||
id: fieldId,
|
||||
caption,
|
||||
type: "Text",
|
||||
entryMethod: "EntryField",
|
||||
value,
|
||||
});
|
||||
|
||||
const normalizedItems = inputItems.map((item) => ({
|
||||
...(item.procurementNotes || item.productNarrative
|
||||
? {
|
||||
customFields: [
|
||||
...(item.procurementNotes
|
||||
? [
|
||||
makeCustomField(
|
||||
"Procurement Notes",
|
||||
item.procurementNotes,
|
||||
29,
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...(item.productNarrative
|
||||
? [
|
||||
makeCustomField(
|
||||
"Product Narrative",
|
||||
item.productNarrative,
|
||||
46,
|
||||
),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
catalogItem: { id: specialOrderCatalogItem.cwCatalogId },
|
||||
description: item.desc,
|
||||
customerDescription: item.customerDesc,
|
||||
quantity: item.qty ?? 1,
|
||||
price: item.price,
|
||||
cost: item.cost,
|
||||
taxableFlag:
|
||||
item.taxable ??
|
||||
item.taxableFlag ??
|
||||
specialOrderCatalogItem.salesTaxable,
|
||||
dropshipFlag: false,
|
||||
billableOption: "Billable",
|
||||
}));
|
||||
|
||||
const opportunity = await opportunities.fetchRecord(identifier);
|
||||
const created = await opportunity.addProcurementProducts(normalizedItems);
|
||||
|
||||
const serialized = created.map((item: any) => {
|
||||
const fields = Array.isArray(item?.customFields) ? item.customFields : [];
|
||||
const procurementNotes =
|
||||
fields.find((f: any) => f?.id === 29)?.value ?? null;
|
||||
const productNarrative =
|
||||
fields.find((f: any) => f?.id === 46)?.value ?? null;
|
||||
|
||||
return {
|
||||
id: item?.id ?? null,
|
||||
forecastDetailId: item?.forecastDetailId ?? null,
|
||||
description: item?.description ?? null,
|
||||
productDescription: item?.description ?? null,
|
||||
customerDescription: item?.customerDescription ?? null,
|
||||
quantity: item?.quantity ?? null,
|
||||
price: item?.price ?? null,
|
||||
revenue: item?.price ?? null,
|
||||
cost: item?.cost ?? null,
|
||||
taxableFlag: item?.taxableFlag ?? null,
|
||||
specialOrderFlag: item?.specialOrderFlag ?? null,
|
||||
procurementNotes,
|
||||
productNarrative,
|
||||
};
|
||||
});
|
||||
|
||||
const isBatch = Array.isArray(body);
|
||||
const response = apiResponse.created(
|
||||
isBatch
|
||||
? `${created.length} special-order product(s) added successfully!`
|
||||
: "Special-order product added successfully!",
|
||||
isBatch ? serialized : serialized[0]!,
|
||||
);
|
||||
|
||||
return c.json(response, response.status as ContentfulStatusCode);
|
||||
},
|
||||
authMiddleware({
|
||||
permissions: ["sales.opportunity.product.add.specialOrder"],
|
||||
}),
|
||||
);
|
||||
+20
-52
@@ -24,7 +24,6 @@ export default createRoute(
|
||||
"get",
|
||||
["/opportunities/:identifier"],
|
||||
async (c) => {
|
||||
const t0 = performance.now();
|
||||
const identifier = c.req.param("identifier");
|
||||
const includeParam = c.req.query("include") ?? "";
|
||||
const includes = new Set(
|
||||
@@ -80,24 +79,14 @@ export default createRoute(
|
||||
// Check Redis first — if the background refresh has kept the keys warm,
|
||||
// skip the CW calls entirely. Only fetch-and-cache on a miss.
|
||||
const cwOppId = dbRecord.cwOpportunityId;
|
||||
const _pw0 = performance.now();
|
||||
const _wrapPw = (label: string, p: Promise<any>) =>
|
||||
p
|
||||
.then((r) => {
|
||||
console.log(
|
||||
`[PERF:prewarm] ${label}: ${(performance.now() - _pw0).toFixed(0)}ms`,
|
||||
);
|
||||
return r;
|
||||
})
|
||||
.catch(() => {});
|
||||
const _ignoreErrors = (p: Promise<any>) => p.catch(() => {});
|
||||
|
||||
const prewarmPromises: Promise<any>[] = [];
|
||||
if (dbRecord.companyCwId && dbRecord.siteCwId) {
|
||||
const compId = dbRecord.companyCwId,
|
||||
siteId = dbRecord.siteCwId;
|
||||
prewarmPromises.push(
|
||||
_wrapPw(
|
||||
"site",
|
||||
_ignoreErrors(
|
||||
getCachedSite(compId, siteId).then(
|
||||
(c) => c ?? fetchAndCacheSite(compId, siteId),
|
||||
),
|
||||
@@ -106,8 +95,7 @@ export default createRoute(
|
||||
}
|
||||
if (includes.has("notes") && subTtl)
|
||||
prewarmPromises.push(
|
||||
_wrapPw(
|
||||
"notes",
|
||||
_ignoreErrors(
|
||||
getCachedNotes(cwOppId).then(
|
||||
(c) => c ?? fetchAndCacheNotes(cwOppId, subTtl),
|
||||
),
|
||||
@@ -115,8 +103,7 @@ export default createRoute(
|
||||
);
|
||||
if (includes.has("contacts") && subTtl)
|
||||
prewarmPromises.push(
|
||||
_wrapPw(
|
||||
"contacts",
|
||||
_ignoreErrors(
|
||||
getCachedContacts(cwOppId).then(
|
||||
(c) => c ?? fetchAndCacheContacts(cwOppId, subTtl),
|
||||
),
|
||||
@@ -124,8 +111,7 @@ export default createRoute(
|
||||
);
|
||||
if (includes.has("products") && prodTtl)
|
||||
prewarmPromises.push(
|
||||
_wrapPw(
|
||||
"products",
|
||||
_ignoreErrors(
|
||||
getCachedProducts(cwOppId).then(
|
||||
(c) => c ?? fetchAndCacheProducts(cwOppId, prodTtl),
|
||||
),
|
||||
@@ -138,46 +124,25 @@ export default createRoute(
|
||||
opportunities.fetchItem(identifier),
|
||||
...prewarmPromises,
|
||||
]);
|
||||
const t1 = performance.now();
|
||||
console.log(`[PERF] fetchItem + prewarm: ${(t1 - t0).toFixed(0)}ms`);
|
||||
|
||||
// Sub-resources now hit warm Redis cache (near-instant)
|
||||
const _st = performance.now();
|
||||
const _wrapTimed = (label: string, p: Promise<any>) =>
|
||||
p.then((r) => {
|
||||
console.log(
|
||||
`[PERF:sub] ${label}: ${(performance.now() - _st).toFixed(0)}ms`,
|
||||
);
|
||||
return r;
|
||||
});
|
||||
|
||||
const subResourcePromises: Record<string, Promise<any>> = {
|
||||
_site: _wrapTimed("site", item.fetchSite()),
|
||||
_site: item.fetchSite(),
|
||||
};
|
||||
if (includes.has("notes")) {
|
||||
subResourcePromises.notes = _wrapTimed("notes", item.fetchNotes());
|
||||
subResourcePromises.notes = item.fetchNotes();
|
||||
}
|
||||
if (includes.has("contacts")) {
|
||||
subResourcePromises.contacts = _wrapTimed(
|
||||
"contacts",
|
||||
item.fetchContacts(),
|
||||
);
|
||||
subResourcePromises.contacts = item.fetchContacts();
|
||||
}
|
||||
if (includes.has("products")) {
|
||||
subResourcePromises.products = _wrapTimed(
|
||||
"products",
|
||||
item
|
||||
.fetchProducts()
|
||||
.then((products) => products.map((p) => p.toJson())),
|
||||
);
|
||||
subResourcePromises.products = item
|
||||
.fetchProducts()
|
||||
.then((products) => products.map((p) => p.toJson()));
|
||||
}
|
||||
|
||||
const keys = Object.keys(subResourcePromises);
|
||||
const results = await Promise.all(keys.map((k) => subResourcePromises[k]));
|
||||
const t2 = performance.now();
|
||||
console.log(
|
||||
`[PERF] sub-resources (${keys.join(",")}): ${(t2 - t1).toFixed(0)}ms`,
|
||||
);
|
||||
|
||||
// Apply toJson after site is hydrated (side-effect from fetchSite)
|
||||
const gatedData = await processObjectValuePerms(
|
||||
@@ -185,8 +150,8 @@ export default createRoute(
|
||||
"obj.opportunity",
|
||||
c.get("user"),
|
||||
);
|
||||
const t3 = performance.now();
|
||||
console.log(`[PERF] processObjectValuePerms: ${(t3 - t2).toFixed(0)}ms`);
|
||||
|
||||
const originalOpportunityNoteText = (gatedData as any).notes;
|
||||
|
||||
// Attach sub-resources (skip the internal _site key)
|
||||
keys.forEach((k, i) => {
|
||||
@@ -195,14 +160,17 @@ export default createRoute(
|
||||
}
|
||||
});
|
||||
|
||||
if (includes.has("notes")) {
|
||||
(gatedData as any).opportunityNoteText =
|
||||
typeof originalOpportunityNoteText === "string"
|
||||
? originalOpportunityNoteText
|
||||
: null;
|
||||
}
|
||||
|
||||
const response = apiResponse.successful(
|
||||
"Opportunity fetched successfully!",
|
||||
gatedData,
|
||||
);
|
||||
|
||||
console.log(
|
||||
`[PERF] total handler: ${(performance.now() - t0).toFixed(0)}ms (includes=${includeParam || "none"})`,
|
||||
);
|
||||
return c.json(response, response.status as ContentfulStatusCode);
|
||||
},
|
||||
authMiddleware({ permissions: ["sales.opportunity.fetch"] }),
|
||||
|
||||
@@ -5,6 +5,7 @@ import { default as fetch } from "./[id]/fetch";
|
||||
import { default as refresh } from "./[id]/refresh";
|
||||
import { default as products } from "./[id]/products";
|
||||
import { default as addProduct } from "./[id]/addProduct";
|
||||
import { default as addSpecialOrderProduct } from "./[id]/addSpecialOrderProduct";
|
||||
import { default as resequenceProducts } from "./[id]/resequenceProducts";
|
||||
import { default as notes } from "./[id]/notes";
|
||||
import { default as fetchNote } from "./[id]/fetchNote";
|
||||
@@ -15,6 +16,7 @@ import { default as contacts } from "./[id]/contacts";
|
||||
|
||||
export {
|
||||
addProduct,
|
||||
addSpecialOrderProduct,
|
||||
count,
|
||||
fetch,
|
||||
fetchAll,
|
||||
|
||||
Reference in New Issue
Block a user