feat(sales): update opportunity product and overview flows

This commit is contained in:
2026-03-04 18:44:29 -06:00
parent e04a1ad746
commit 762edd8eb7
6 changed files with 1088 additions and 229 deletions
+18 -3
View File
@@ -34,6 +34,12 @@
}
onMount(() => {
checkMobile();
console.log("[OpportunityLoad] Description values:", {
description: (opportunity as Record<string, unknown> | null)?.description,
notes: opportunity?.notes ?? null,
name: opportunity?.name ?? null,
opportunityId,
});
window.addEventListener("resize", checkMobile);
return () => window.removeEventListener("resize", checkMobile);
});
@@ -56,7 +62,9 @@
function guardedSetTab(tab: Tab) {
if (activeTab === tab) return;
if (productsEditing) {
if (!confirm('You have unsaved product changes. Discard and switch tabs?')) {
if (
!confirm("You have unsaved product changes. Discard and switch tabs?")
) {
return;
}
productsEditing = false;
@@ -76,12 +84,18 @@
localProductSequence = e.detail;
}
function handleProductsChanged(e: CustomEvent<PageData["products"]>) {
products = e.detail;
}
// Mobile nav state
let mobileActiveTab: Tab | null = null;
function selectMobileTab(tab: Tab) {
if (productsEditing) {
if (!confirm('You have unsaved product changes. Discard and switch tabs?')) {
if (
!confirm("You have unsaved product changes. Discard and switch tabs?")
) {
return;
}
productsEditing = false;
@@ -92,7 +106,7 @@
function mobileBack() {
if (productsEditing) {
if (!confirm('You have unsaved product changes. Discard and go back?')) {
if (!confirm("You have unsaved product changes. Discard and go back?")) {
return;
}
productsEditing = false;
@@ -277,6 +291,7 @@
initialProductId={pendingProductId}
bind:isEditing={productsEditing}
on:sequenceSaved={handleSequenceSaved}
on:productsChanged={handleProductsChanged}
/>
{:else if activeTab === "Notes"}
<NotesTab
@@ -21,6 +21,10 @@
$: contactPhone =
matchedContact?.phone ?? opportunity?.site?.phoneNumber ?? null;
$: contactEmail = matchedContact?.email ?? null;
$: closedByDisplay = formatClosedBy(opportunity?.closedBy);
$: if (opportunity?.closedBy != null) {
console.log("[OpportunitySidebar] closedBy raw:", opportunity.closedBy);
}
function formatPhone(phone: string): string {
const digits = phone.replace(/\D/g, "");
@@ -32,6 +36,14 @@
}
return phone;
}
function formatClosedBy(
closedBy: SalesOpportunity["closedBy"] | undefined,
): string | null {
if (!closedBy) return null;
if (typeof closedBy === "string") return closedBy;
return closedBy.name ?? closedBy.identifier ?? String(closedBy.id ?? "");
}
</script>
<div
@@ -250,7 +262,7 @@
{/if}
<!-- ── Description ── -->
{#if opportunity.notes}
{#if opportunity.description}
<div class="opp-desc-section">
<div class="opp-desc-header">
<svg
@@ -273,7 +285,7 @@
<span class="opp-desc-label">Description</span>
</div>
<div class="opp-desc-card">
<p class="opp-desc-text">{opportunity.notes}</p>
<p class="opp-desc-text">{opportunity.description}</p>
</div>
</div>
{/if}
@@ -296,8 +308,8 @@
{#if opportunity.campaign}
<span class="opp-footer-item">{opportunity.campaign}</span>
{/if}
{#if opportunity.closedBy}
<span class="opp-footer-item">Closed by {opportunity.closedBy}</span>
{#if closedByDisplay}
<span class="opp-footer-item">Closed by {closedByDisplay}</span>
{/if}
{#if opportunity.cwLastUpdated}
<span class="opp-footer-item"
@@ -108,9 +108,20 @@
highlight?: boolean;
}[];
$: isClosedOpportunity = (() => {
if (!opportunity) return false;
const statusText = `${opportunity.status?.name ?? ""} ${opportunity.type?.name ?? ""}`.toLowerCase();
return (
!!opportunity.closedFlag ||
!!opportunity.closedDate ||
statusText.includes("won") ||
statusText.includes("lost")
);
})();
// Days until expected close
$: daysUntilClose = (() => {
if (!opportunity?.expectedCloseDate || opportunity?.closedFlag) return null;
if (!opportunity?.expectedCloseDate || isClosedOpportunity) return null;
const diff = Math.ceil(
(new Date(opportunity.expectedCloseDate).getTime() - Date.now()) /
(1000 * 60 * 60 * 24),
@@ -118,6 +129,16 @@
return diff;
})();
$: closeOutcomeLabel = (() => {
const opp = opportunity;
if (!isClosedOpportunity || !opp) return null;
const outcomeText =
`${opp.status?.name ?? ""} ${opp.type?.name ?? ""}`.toLowerCase();
if (outcomeText.includes("won")) return "WON";
if (outcomeText.includes("lost")) return "LOST";
return "CLOSED";
})();
// Age in days
$: ageDays = (() => {
if (!opportunity?.createdAt) return null;
@@ -230,18 +251,30 @@
</div>
{/if}
</div>
{#if daysUntilClose !== null}
{#if closeOutcomeLabel || daysUntilClose !== null}
<div
class="ov-close-countdown"
class:overdue={daysUntilClose < 0}
class:soon={daysUntilClose >= 0 && daysUntilClose <= 14}
class:overdue={!closeOutcomeLabel &&
daysUntilClose !== null &&
daysUntilClose < 0}
class:soon={!closeOutcomeLabel &&
daysUntilClose !== null &&
daysUntilClose >= 0 &&
daysUntilClose <= 14}
>
<span class="ov-close-number">{Math.abs(daysUntilClose)}</span>
<span class="ov-close-unit">
{daysUntilClose < 0
? `day${Math.abs(daysUntilClose) !== 1 ? "s" : ""} overdue`
: `day${daysUntilClose !== 1 ? "s" : ""} to close`}
</span>
{#if closeOutcomeLabel}
<span class="ov-close-number">{closeOutcomeLabel}</span>
{#if closeOutcomeLabel !== "WON" && closeOutcomeLabel !== "LOST"}
<span class="ov-close-unit">Closed opportunity</span>
{/if}
{:else if daysUntilClose !== null}
<span class="ov-close-number">{Math.abs(daysUntilClose)}</span>
<span class="ov-close-unit">
{daysUntilClose < 0
? `day${Math.abs(daysUntilClose) !== 1 ? "s" : ""} overdue`
: `day${daysUntilClose !== 1 ? "s" : ""} to close`}
</span>
{/if}
</div>
{/if}
</div>
@@ -11,6 +11,10 @@
import type { CatalogItem } from "$lib/optima-api/modules/procurement";
import type {
AddProductBody,
AddLaborBody,
CancelOpportunityProductBody,
LaborCustomerType,
LaborStyle,
SpecialOrderBody,
} from "$lib/optima-api/modules/sales";
@@ -20,7 +24,10 @@
export let productSequence: number[] | null = null;
export let initialProductId: number | null = null;
const dispatch = createEventDispatcher<{ sequenceSaved: number[] }>();
const dispatch = createEventDispatcher<{
sequenceSaved: number[];
productsChanged: OpportunityProduct[];
}>();
let showAddProductModal = false;
@@ -78,6 +85,7 @@
);
if (result?.data) {
products = result.data;
dispatch("productsChanged", products);
}
} catch (err) {
console.error("[Products] Failed to refresh:", err);
@@ -89,17 +97,19 @@
const items = Array.isArray(incoming) ? incoming : [incoming];
if (items.length === 0) return;
const laborItems = items.filter((item) => item.identifier === "LABOR");
const specialOrderItems = items.filter(
(item) => item.identifier === "SPECIAL-ORDER",
);
const standardItems = items.filter(
(item) => item.identifier !== "SPECIAL-ORDER",
(item) =>
item.identifier !== "SPECIAL-ORDER" && item.identifier !== "LABOR",
);
isAddingProduct = true;
addProductError = "";
try {
// Add standard catalog/labor items through generic endpoint
// Add standard catalog items through generic endpoint
if (standardItems.length > 0) {
await Promise.all(
standardItems.map((item) =>
@@ -112,6 +122,43 @@
);
}
if (laborItems.length > 0) {
const payload: AddLaborBody[] = laborItems.map((item) => {
const laborStyle = (item.laborStyle ?? "field") as LaborStyle;
const customerType = (item.customerType ??
"corporate") as LaborCustomerType;
const hours =
typeof item.hours === "number"
? item.hours
: item.quantity && item.quantity > 0
? item.quantity
: 1;
const ppu = typeof item.ppu === "number" ? item.ppu : item.price;
const cpu = typeof item.cpu === "number" ? item.cpu : item.cost;
const rate = typeof item.rate === "number" ? item.rate : ppu;
return {
laborStyle,
customerType,
hours,
taxable: item.taxableFlag,
rate,
ppu,
cpu,
description: item.description,
customerDescription: item.customerDescription,
procurementNotes: item.procurementNotes,
productNarrative: item.productNarrative,
};
});
await Promise.all(
payload.map((body) =>
optima.sales.addLabor(accessToken!, opportunityId, body),
),
);
}
// Add special-order items through dedicated endpoint
if (specialOrderItems.length > 0) {
const payload: SpecialOrderBody[] = specialOrderItems.map((item) => ({
@@ -154,6 +201,15 @@
// ── Edit mode state ──
export let isEditing = false;
let showActionMenu = false;
let isSavingEdit = false;
let editSaveError = "";
let showCancelModal = false;
let isSavingCancellation = false;
let cancellationSaveError = "";
let cancellationForm = {
quantityCancelled: "0",
cancellationReason: "",
};
let editForm: {
unitPrice: string;
unitCost: string;
@@ -186,21 +242,109 @@
procurementNotes: selectedProduct.procurementNotes ?? "",
};
isEditing = true;
editSaveError = "";
showActionMenu = false;
}
function cancelEdit() {
isEditing = false;
editSaveError = "";
}
function hasCancellation(p: OpportunityProduct): boolean {
return !!(
p.cancelled ||
p.cancellationType ||
(p.quantityCancelled ?? 0) > 0
);
}
function maxCancellationQty(p: OpportunityProduct): number {
const qty = Math.floor(p.quantity ?? 0);
return qty > 0 ? qty : 0;
}
function openCancellationModal() {
if (!selectedProduct) return;
const maxQty = maxCancellationQty(selectedProduct);
const initialQty = Math.min(
Math.max(
selectedProduct.quantityCancelled ??
(selectedProduct.cancellationType === "full" ? maxQty : 0),
0,
),
maxQty,
);
cancellationForm = {
quantityCancelled: String(initialQty),
cancellationReason: selectedProduct.cancelledReason ?? "",
};
cancellationSaveError = "";
showActionMenu = false;
showCancelModal = true;
}
function closeCancellationModal() {
if (isSavingCancellation) return;
showCancelModal = false;
cancellationSaveError = "";
}
async function saveCancellation() {
if (!selectedProduct || !accessToken || isSavingCancellation) return;
const maxQty = maxCancellationQty(selectedProduct);
const parsedQty = Number.parseInt(cancellationForm.quantityCancelled, 10);
const quantityCancelled = Number.isFinite(parsedQty)
? Math.min(Math.max(parsedQty, 0), maxQty)
: 0;
const reason = cancellationForm.cancellationReason.trim();
const payload: CancelOpportunityProductBody = {
quantityCancelled,
cancellationReason: quantityCancelled > 0 ? reason || null : null,
};
isSavingCancellation = true;
cancellationSaveError = "";
try {
await optima.sales.cancelProduct(
accessToken,
opportunityId,
selectedProduct.id,
payload,
);
await refreshProducts();
selectedProduct =
products.find((p) => p.id === selectedProduct?.id) ?? null;
showCancelModal = false;
cancellationSaveError = "";
} catch (err) {
console.error("[CancelProduct] Failed:", err);
cancellationSaveError =
err instanceof Error ? err.message : "Failed to update cancellation";
} finally {
isSavingCancellation = false;
}
}
async function saveEdit() {
if (!selectedProduct || !accessToken) return;
if (!selectedProduct || !accessToken || isSavingEdit) return;
const qty = parseFloat(editForm.quantity) || selectedProduct.quantity || 1;
const up = parseFloat(editForm.unitPrice);
const uc = parseFloat(editForm.unitCost);
const updates: Record<string, unknown> = {
const updates: {
quantity: number;
productDescription: string;
customerDescription: string | null;
productNarrative: string | null;
procurementNotes: string | null;
unitPrice?: number;
unitCost?: number;
} = {
quantity: qty,
productDescription: editForm.description,
customerDescription: editForm.customerDescription || null,
@@ -209,20 +353,38 @@
};
if (!isNaN(up)) {
updates.revenue = up * qty;
updates.unitPrice = up;
}
if (!isNaN(uc)) {
updates.cost = uc * qty;
updates.unitCost = uc;
}
// TODO: Wire up the actual API call once the endpoint exists
// await optima.sales.updateProduct(accessToken, opportunityId, selectedProduct.id, updates);
console.log("[EditProduct] Would save:", {
productId: selectedProduct.id,
updates,
});
console.log(
"[EditProduct] Description payload:",
updates.productDescription,
);
isEditing = false;
isSavingEdit = true;
editSaveError = "";
try {
await optima.sales.editProduct(
accessToken,
opportunityId,
selectedProduct.id,
updates,
);
await refreshProducts();
selectedProduct =
products.find((p) => p.id === selectedProduct?.id) ?? null;
isEditing = false;
editSaveError = "";
} catch (err) {
console.error("[EditProduct] Failed:", err);
editSaveError =
err instanceof Error ? err.message : "Failed to update product";
} finally {
isSavingEdit = false;
}
}
// ── Unsaved changes guard ──
@@ -381,6 +543,19 @@
return "negative";
}
function marginBarWidthPct(revenue?: number, margin?: number): number {
const cost = (revenue ?? 0) - (margin ?? 0);
if (!cost || cost <= 0) return 0;
const pct = ((margin ?? 0) / cost) * 100;
return Math.min(Math.abs(pct), 100);
}
function isNegativeMargin(revenue?: number, margin?: number): boolean {
const cost = (revenue ?? 0) - (margin ?? 0);
if (!cost || cost <= 0) return false;
return ((margin ?? 0) / cost) * 100 < 0;
}
function checkForChanges() {
hasChanges = activeProducts.some((p, i) => p.id !== originalOrderIds[i]);
}
@@ -517,6 +692,8 @@
showActionMenu = false;
}
isClosing = false;
showCancelModal = false;
cancellationSaveError = "";
selectedProduct = p;
showPanel = true;
}
@@ -529,6 +706,8 @@
}
isEditing = false;
showActionMenu = false;
showCancelModal = false;
cancellationSaveError = "";
isClosing = true;
setTimeout(() => {
selectedProduct = null;
@@ -539,6 +718,10 @@
function handleKeydown(e: KeyboardEvent) {
if (e.key === "Escape") {
if (showCancelModal) {
closeCancellationModal();
return;
}
if (showActionMenu) {
showActionMenu = false;
return;
@@ -1024,12 +1207,13 @@
p.revenue,
p.margin,
)}"
style="width: {Math.min(
Math.max(
((p.margin ?? 0) / ((p.cost ?? 0) || 1)) * 100,
0,
),
100,
class:from-right={isNegativeMargin(
p.revenue,
p.margin,
)}
style="width: {marginBarWidthPct(
p.revenue,
p.margin,
)}%"
></div>
</div>
@@ -1280,6 +1464,7 @@
on:click={cancelEdit}
type="button"
title="Discard changes"
disabled={isSavingEdit}
>
Cancel
</button>
@@ -1288,10 +1473,25 @@
on:click={saveEdit}
type="button"
title="Save changes"
disabled={isSavingEdit}
>
Save
{isSavingEdit ? "Saving..." : "Save"}
</button>
{:else}
<button
class="detail-action-btn cancel-state-btn"
class:active={hasCancellation(selectedProduct)}
on:click={openCancellationModal}
type="button"
title={hasCancellation(selectedProduct)
? "Edit cancellation"
: "Cancel product"}
disabled={maxCancellationQty(selectedProduct) <= 0}
>
{hasCancellation(selectedProduct)
? "Edit Cancellation"
: "Cancel"}
</button>
<div class="detail-menu-wrap">
<button
class="detail-menu-btn"
@@ -1364,6 +1564,10 @@
</div>
</div>
{#if isEditing && editSaveError}
<div class="detail-inline-error">{editSaveError}</div>
{/if}
<!-- Cancelled alert (hidden during edit) -->
{#if !isEditing && (selectedProduct.cancelled || selectedProduct.cancellationType || (selectedProduct.quantityCancelled != null && selectedProduct.quantityCancelled > 0))}
<div
@@ -1602,14 +1806,13 @@
selectedProduct.revenue,
selectedProduct.margin,
)}"
style="width: {Math.min(
Math.max(
((selectedProduct.margin ?? 0) /
((selectedProduct.cost ?? 0) || 1)) *
100,
0,
),
100,
class:from-right={isNegativeMargin(
selectedProduct.revenue,
selectedProduct.margin,
)}
style="width: {marginBarWidthPct(
selectedProduct.revenue,
selectedProduct.margin,
)}%"
></div>
</div>
@@ -1910,9 +2113,101 @@
{/if}
</div>
{#if showCancelModal && selectedProduct}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div class="cancel-modal-overlay" on:click={closeCancellationModal}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div class="cancel-modal" on:click|stopPropagation>
<div class="cancel-modal-header">
<h4>
{hasCancellation(selectedProduct)
? "Edit Cancellation"
: "Cancel Product"}
</h4>
<button
class="cancel-modal-close"
type="button"
on:click={closeCancellationModal}
aria-label="Close cancellation modal"
disabled={isSavingCancellation}
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
width="16"
height="16"
>
<path d="M18 6L6 18M6 6l12 12" />
</svg>
</button>
</div>
<p class="cancel-modal-copy">
Set cancelled quantity between 0 and {maxCancellationQty(
selectedProduct,
)}.
</p>
{#if cancellationSaveError}
<div class="cancel-modal-error">{cancellationSaveError}</div>
{/if}
<div class="cancel-modal-field">
<label for="cancel-qty">Qty Cancelled</label>
<input
id="cancel-qty"
class="edit-input"
type="number"
min="0"
max={maxCancellationQty(selectedProduct)}
step="1"
bind:value={cancellationForm.quantityCancelled}
disabled={isSavingCancellation}
/>
</div>
<div class="cancel-modal-field">
<label for="cancel-reason">Reason</label>
<textarea
id="cancel-reason"
class="edit-textarea"
rows="3"
placeholder="Optional cancellation reason"
bind:value={cancellationForm.cancellationReason}
disabled={isSavingCancellation}
></textarea>
</div>
<div class="cancel-modal-actions">
<button
class="detail-action-btn cancel-btn"
type="button"
on:click={closeCancellationModal}
disabled={isSavingCancellation}
>
Close
</button>
<button
class="detail-action-btn save-btn"
type="button"
on:click={saveCancellation}
disabled={isSavingCancellation}
>
{isSavingCancellation ? "Saving..." : "Save Cancellation"}
</button>
</div>
</div>
</div>
{/if}
<AddProductModal
bind:isOpen={showAddProductModal}
accessToken={accessToken ?? ""}
{opportunityId}
onSelect={handleProductSelected}
/>
@@ -2573,6 +2868,10 @@
transition: width 0.4s ease;
}
.card-margin-fill.from-right {
margin-left: auto;
}
.card-margin-fill.healthy {
background: #22c55e;
}
@@ -2888,12 +3187,19 @@
border-radius: 6px;
font-size: 12px;
font-weight: 600;
white-space: nowrap;
flex-shrink: 0;
cursor: pointer;
transition:
background 0.15s,
color 0.15s;
}
.detail-action-btn:disabled {
opacity: 0.65;
cursor: not-allowed;
}
.cancel-btn {
background: transparent;
color: var(--text-secondary);
@@ -2904,6 +3210,26 @@
color: var(--text-primary);
}
.cancel-state-btn {
background: transparent;
color: var(--text-secondary);
}
.cancel-state-btn:hover {
background: rgba(239, 68, 68, 0.12);
color: #ef4444;
}
.cancel-state-btn.active {
background: rgba(245, 158, 11, 0.14);
color: #d97706;
}
.cancel-state-btn.active:hover {
background: rgba(245, 158, 11, 0.2);
color: #d97706;
}
.save-btn {
background: var(--accent, #6366f1);
color: #fff;
@@ -2913,6 +3239,108 @@
background: color-mix(in srgb, var(--accent, #6366f1) 85%, #000);
}
.detail-inline-error {
margin: 10px 18px 0;
padding: 8px 10px;
border-radius: 8px;
border: 1px solid rgba(220, 38, 38, 0.25);
background: rgba(220, 38, 38, 0.08);
color: #ef4444;
font-size: 12px;
font-weight: 500;
}
.cancel-modal-overlay {
position: fixed;
inset: 0;
z-index: 60;
background: rgba(0, 0, 0, 0.45);
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.cancel-modal {
width: min(480px, calc(100vw - 40px));
border-radius: 12px;
border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.1));
background: var(--bg-surface, #1c1c22);
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45);
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.cancel-modal-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.cancel-modal-header h4 {
margin: 0;
font-size: 15px;
font-weight: 700;
color: var(--text-primary);
}
.cancel-modal-close {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: none;
border-radius: 8px;
background: transparent;
color: var(--text-secondary);
cursor: pointer;
}
.cancel-modal-close:hover {
background: var(--bg-hover, rgba(255, 255, 255, 0.06));
color: var(--text-primary);
}
.cancel-modal-copy {
margin: 0;
color: var(--text-secondary);
font-size: 12px;
line-height: 1.4;
}
.cancel-modal-error {
padding: 8px 10px;
border-radius: 8px;
border: 1px solid rgba(220, 38, 38, 0.25);
background: rgba(220, 38, 38, 0.08);
color: #ef4444;
font-size: 12px;
font-weight: 500;
}
.cancel-modal-field {
display: flex;
flex-direction: column;
gap: 6px;
}
.cancel-modal-field label {
color: var(--text-secondary);
font-size: 12px;
font-weight: 600;
}
.cancel-modal-actions {
margin-top: 4px;
display: flex;
justify-content: flex-end;
gap: 8px;
}
/* Edit inputs */
.edit-input {
width: 100%;
@@ -3209,6 +3637,10 @@
transition: width 0.4s ease;
}
.detail-margin-fill.from-right {
margin-left: auto;
}
.detail-margin-fill.healthy {
background: #22c55e;
}