1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[44849,78027],{66743:function(e,t,n){n.d(t,{Z:function(){return h},c:function(){return x}});var a=n(57437);function r(e,t,n,a){let r;let i=t.find(t=>{var n;return(null===(n=t.family)||void 0===n?void 0:n.name)===e});if("Bare Wire End"===e)r={crimp:"",stripLength:0,extraLength:0};else if("Stripped Wire"==e){let e=n.description.split("mm")[0],t=e?parseFloat(e):0;r={crimp:"",stripLength:t,extraLength:t}}else r=i&&i.definedByCrimp&&a?i.constantsByCrimp.find(e=>e.crimp.MPN===a.MPN)||Error("No wire cutting params found for crimp: ".concat(a.MPN)):i?{crimp:"",stripLength:i.familyStripLength,extraLength:i.familyExtraLength}:Error("No wire cutting params found for family: ".concat(e));return r}function i(e,t,n,a){if("splice"===e.type){let e=null!=n?n:t,r=String(e);if(!a[r])throw Error("Wire gauge ".concat(e,"AWG not found in spliceParams."));return a[r]}throw Error("MidElem type is not currently supported.")}n(2265);var s=n(45197);function o(e,t,n){let a=t.find(t=>t.MPN===e.MPN);if(!e.pinStatus||!Array.isArray(e.pinStatus))return s.k.debug("[Crimp Lookup] Connector has no pinStatus array",{connMPN:e.MPN}),[];if(!a)return s.k.warn("[Crimp Lookup] Connector not found in Sanity CMS",{connMPN:e.MPN,searchedIn:t.length+" connectors"}),[];let r=e.pinStatus.filter(e=>"C"===e.status).map(e=>e.pinID),i=n.filter(e=>r.includes(e.start)||r.includes(e.end));if("crimp"!==a.type)return s.k.debug("[Crimp Lookup] Connector is not crimp type, skipping crimp lookup",{connMPN:e.MPN,actualType:a.type}),[];let o=[];for(let t of i){var l,d;let n=(null===(l=a.crimps)||void 0===l?void 0:l.filter(e=>e.gauges&&Array.isArray(e.gauges)&&e.gauges.includes(t.gauge)))||[];if(0===n.length){s.k.debug("[Crimp Lookup] No compatible crimps for wire gauge",{connMPN:e.MPN,wireGauge:t.gauge,availableCrimps:(null===(d=a.crimps)||void 0===d?void 0:d.length)||0});continue}let r=n[0];if(!r)continue;let i=n.reduce((e,t)=>t.price<e.price?t:e,r);i&&o.push(i)}return o.length>0?s.k.debug("[Crimp Lookup] Found crimps for connector",{connMPN:e.MPN,crimpCount:o.length,crimpMPNs:o.map(e=>e.MPN)}):i.length>
10&&s.k.debug("[Crimp Lookup] No crimps found for any pins",{connMPN:e.MPN,pinMappingCount:i.length}),o}var l=n(45402),d=n(31071),c=n(9105),m=n(34040),p=n(12521);function u(e){let{cutSheetParams:t,orderNumber:n}=e;return(0,a.jsxs)("html",{children:[(0,a.jsxs)("head",{children:[(0,a.jsx)("title",{children:"Cut Sheet"}),(0,a.jsx)("style",{children:'\n body {\n margin: 1cm;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n }\n table {\n width: 100%;\n border-collapse: collapse;\n font-size: 12px;\n }\n th, td {\n border: 1px solid #ddd;\n padding: 8px;\n text-align: center;\n position: relative;\n overflow: visible;\n }\n th {\n background-color: #f3f4f6;\n font-weight: 500;\n }\n .error-row {\n background-color: #fef2f2;\n }\n .termination-info {\n font-size: 10px;\n color: #666;\n display: block;\n }\n .error-icon {\n color: #dc2626;\n margin-left: 4px;\n display: inline-block;\n width: 16px;\n height: 16px;\n vertical-align: middle;\n }\n .error-message {\n display: none;\n position: absolute;\n background: #fff;\n border: 1px solid #ddd;\n padding: 8px;\n padding-left: 16px;\n border-radius: 4px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n max-width: 300px;\n z-index: 9999;\n top: -8px;\n left: 100%;\n margin-left: 8px;\n white-space: normal;\n }\n .error-arrow {\n position: absolute;\n left: -5px;\n top: 10px;\n width: 8px;\n height: 8px;\n margin-left: -4px;\n background: white;\n border-left: 1px solid #ddd;\n border-bottom: 1px solid #ddd;\n transform: rotate(45deg);\n }\n .error-container {\n display: inline-block;\n position: relative;\n vertical-align: middle;\n }\n .error-container:hover .error-message {\n display: block;\n }\n '})]}),(0,a.jsxs)("body",{children:[(0,a.jsxs)("h1",{children:["Order Number: ",n]}),(0,a.jsxs)("table",{children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{children:[(0,a.jsx)("th",{children:"Assy ID"}),(0,a.jsx)("th",{children:"Assy Name"}),(0,a.jsx)("th",{children:"Wire ID"}),(0,a.jsx)("th",{children:"Wire Family"}),(0,a.jsx)("th",{children:"Color"}),(0,a.jsx)("th",{children:"Gauge"}),(0,a.jsx)("th",{children:"Side A"}),(0,a.jsx)("th",{children:"Side B"}),(0,a.jsx)("th",{children:"Length (mm)"}),(0,a.jsx)("th",{children:"Qty"})]})}),(0,a.jsx)("tbody",{children:t.map((e,t)=>(0,a.jsxs)("tr",{className:e.hasError?"error-row":"",children:[(0,a.jsxs)("td",{children:[e.assyID,e.hasError&&e.errorMessage&&(0,a.jsxs)("div",{className:"error-container",children:[(0,a.jsx)(l.Z,{className:"error-icon"}),(0,a.jsx)("div",{className:"error-message",children:(0,a.jsxs)("div",{className:"relative",children:[e.errorMessage,(0,a.jsx)("div",{className:"error-arrow"})]})})]})]}),(0,a.jsx)("td",{className:"text-center",children:e.assyName}),(0,a.jsx)("td",{className:"text-center",children:e.wireID}),(0,a.jsx)("td",{className:"text-center",children:e.wireFamilyName}),(0,a.jsx)("td",{className:"text-center",children:e.color}),(0,a.jsx)("td",{className:"text-center",children:e.gauge}),(0,a.jsxs)("td",{className:"text-center",children:[(0,a.jsxs)("div",{children:["Strip: ",e.sideAStrip,"mm"]}),e.sideAType&&(0,a.jsxs)("span",{className:"termination-info",children:["Type: ",e.sideAType]}),e.sideACrimpMPN&&(0,a.jsxs)("span",{className:"termination-info",children:["Crimp: ",e.sideACrimpMPN]})]}),(0,a.jsxs)("td",{className:"text-center",children:[(0,a.jsxs)("div",{children:["Strip: ",e.sideBStrip,"mm"]}),e.sideBType&&(0,a.jsxs)("span",{className:"termination-info",children:["Type: ",e.sideBType]}),e.sideBCrimpMPN&&(0,a.jsxs)("span",{className:"termination-info",children:["Crimp: ",e.sideBCrimpMPN]})]}),(0,a.jsx)("td",{className:"text-center",children:e.overallLength}),(0,a.jsx)("td",{className:"text-center",children:e.qty})]},t))})]})]})]})}function x(e,t){let n=window.open("","_blank");if(!n)return!1;let r=(0,a.jsx)(u,{cutSheetParams:e,orderNumber:t});n.document.write('\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>Cut Sheet - Order '.concat(t,'</title>\n <style>\n @media screen, print {\n body {\n margin: 1cm;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n -webkit-print-color-adjust: exact;\n print-color-adjust: exact;\n }\n table {\n width: 100%;\n border-collapse: collapse;\n font-size: 12px;\n page-break-inside: auto;\n }\n tr {\n page-break-inside: avoid;\n page-break-after: auto;\n }\n th, td {\n border: 1px solid #ddd;\n padding: 8px;\n text-align: center;\n position: relative;\n overflow: visible;\n word-wrap: break-word;\n }\n th {\n background-color: #f3f4f6;\n font-weight: 500;\n }\n .error-row {\n background-color: #fef2f2;\n }\n .termination-info {\n font-size: 10px;\n color: #666;\n display: block;\n }\n .error-icon {\n color: #dc2626;\n margin-left: 4px;\n display: inline-block;\n width: 16px;\n height: 16px;\n vertical-align: middle;\n }\n .error-message {\n display: none;\n position: absolute;\n background: #fff;\n border: 1px solid #ddd;\n padding: 8px;\n padding-left: 16px;\n border-radius: 4px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n max-width: 300px;\n z-index: 9999;\n top: -8px;\n left: 100%;\n margin-left: 8px;\n white-space: normal;\n }\n .error-arrow {\n position: absolute;\n left: -5px;\n top: 10px;\n width: 8px;\n height: 8px;\n margin-left: -4px;\n background: white;\n border-left: 1px solid #ddd;\n border-bottom: 1px solid #ddd;\n transform: rotate(45deg);\n }\n .error-container {\n display: inline-block;\n position: relative;\n vertical-align: middle;\n }\n .error-container:hover .error-message {\n display: block;\n }\n @page {\n size: auto;\n margin: 1cm;\n }\n }\n </style>\n </head>\n <body>\n <div id="print-root"></div>\n <script>\n // Auto-print once content is loaded\n window.onload = function() {\
1n setTimeout(function() {\n window.print();\n setTimeout(function() {\n window.close();\n }, 500);\n }, 750);\n };\n </script>\n </body>\n </html>\n '));let i=n.document.getElementById("print-root");return!i||((0,m.createRoot)(i).render(r),n.document.close(),!0)}function h(e){let{showWarning:t}=(0,p.pm)(),{orderNumber:n,onRegenerate:m}=e,u=e.cutSheetParams?e.cutSheetParams:function(e,t,n,a){let l=[],d=[],c=!1,m="",p=0,u=0,x=0;for(let y of e){var h,f,g,b;if(!((h=y.internalDesc)&&"leftSide"in h&&"centerLeft"in h))continue;let e=new Map;for(let t of[...y.internalDesc.centerLeft,...y.internalDesc.centerCenter,...y.internalDesc.centerRight])if("splice"===t.type){let n=function(e,t){let n=99;for(let a of t){let t=a.start.slice(0,a.start.indexOf("P")-1),r=a.end.slice(0,a.end.indexOf("P")-1);(t===e||r===e)&&a.gauge<n&&(n=a.gauge)}return n<99?n:22}(t.uniqueID,y.internalDesc.pinMapping);e.set(t.uniqueID,n)}let v=0;for(let h of y.internalDesc.pinMapping){let j,N,w,k,S,C,I,T;v++,c=!1,m="";let E={start:"L"===h.start[0]||"R"===h.start[0]?[...y.internalDesc.leftSide,...y.internalDesc.rightSide].find(e=>h.start.slice(0,h.start.indexOf("P"))===e.uniqueID):"C"===h.start[0]?[...y.internalDesc.centerLeft,...y.internalDesc.centerCenter,...y.internalDesc.centerRight].find(e=>h.start.slice(0,h.start.indexOf("P")-1)===e.uniqueID):void 0,end:"L"===h.end[0]||"R"===h.end[0]?[...y.internalDesc.leftSide,...y.internalDesc.rightSide].find(e=>h.end.slice(0,h.end.indexOf("P"))===e.uniqueID):"C"===h.end[0]?[...y.internalDesc.centerLeft,...y.internalDesc.centerCenter,...y.internalDesc.centerRight].find(e=>h.end.slice(0,h.end.indexOf("P")-1)===e.uniqueID):void 0};if(E.start&&"family"in E.start){if(j=r((null===(g=E.start.family)||void 0===g?void 0:g.name)||"",t,E.start),n&&"crimp"===E.start.type){let e=o(E.start,n,[h]);e.length>0?w=e[0].MPN:(c=!0,m+="No compatible crimp found for Side A connector: ".concat(E.start.MPN,". "))}S=E.start.type,I=E.start.description}else if(E.start)try{let t=E.start,n=e.get(t.uniqueID);j=i(t,h.gauge,n,a),S=t.type,I=t.description}catch(e){s.k.error("Error finding cut params for midElem",{error:e}),j={stripLength:0,extraLength:0},c=!0,m+="Error with Side A mid-element parameters. "}else throw Error("No start connector or midElem found for wire");if(E.end&&"family"in E.end){if(N=r((null===(b=E.end.family)||void 0===b?void 0:b.name)||"",t,E.end),n&&"crimp"===E.end.type){let e=o(E.end,n,[h]);e.length>0?k=e[0].MPN:(c=!0,m+="No compatible crimp found for Side B connector: ".concat(E.end.MPN,". "))}C=E.end.type,T=E.end.description}else if(E.end)try{let t=E.end,n=e.get(t.uniqueID);N=i(t,h.gauge,n,a),C=t.type,T=t.description}catch(e){s.k.error("Error finding cut params for midElem",{error:e}),N={stripLength:0,extraLength:0},c=!0,m+="Error with Side B mid-element parameters. "}else throw Error("No end connector or midElem found for wire");j instanceof Error?(c=!0,m+="Side A error: ".concat(j.message,". "),p=999999,u=99,x=99):N instanceof Error?(c=!0,m+="Side B error: ".concat(N.message,". "),p=999999,u=99,x=99):(p=h.length+j.extraLength+N.extraLength,u=j.stripLength,x=N.stripLength),l.push({assyID:(null===(f=y.id)||void 0===f?void 0:f.toString())||"ERROR",assyName:y.name||y.customerPartNumber||"Unnamed Assembly",wireID:String(v),wireFamilyName:h.wireFamilyName,color:h.color,gauge:h.gauge,sideAStrip:u,sideBStrip:x,overallLength:p,qty:y.quantity,hasError:c,errorMessage:m||void 0,sideACrimpMPN:w,sideBCrimpMPN:k,sideAType:S,sideBType:C,sideAName:I,sideBName:T}),d.push({wireFamilyName:h.wireFamilyName,color:h.color,gauge:h.gauge.toString(),totalLength:p*y.quantity,hasError:c,errorMessage:m||void 0})}}return{cutSheetParams:l,wireBOM:Object.values(d.reduce((e,t)=>{let n="".concat(t.wireFamilyName,"-").concat(t.color,"-").concat(t.gauge);return e[n]?(e[n].totalLength+=t.totalLength,e[n].hasError=e[n].hasError||t.hasError,t.errorMessage&&(e[n].errorMessage=e[n].errorMessage?"".concat(e[n].errorMessage," ").concat(t.errorMessage):t.errorMessage)):e[n]=t,e},{}))}}(e.cartContents,e.allWireCuttingParams,e.allConnectors,e.spliceParamsByGauge).cutSheetParams,h=u.filter(e=>e.hasError),f=new Set;for(let e of h){var g;let t=null===(g=e.errorMessage)||void 0===g?void 0:g.match(/No wire cutting params found for family: (.+?)(?:\.|$)/);t&&f.add(t[1])}let b=[...f].sort(),y=h.length>0;return(0,a.jsxs)("div",{className:"mt-6",children:[y&&(0,a.jsx)("div",{className:"mb-4 bg-mp-danger/10 border border-mp-danger/30 rounded-[4px] p-4",children:(0,a.jsxs)("div",{className:"flex items-start gap-3",children:[(0,a.jsx)(l.Z,{className:"h-6 w-6 text-mp-danger flex-shrink-0 mt-0.5"}),(0,a.jsxs)("div",{className:"flex-1",children:[(0,a.jsxs)("h4",{className:"text-sm font-semibold text-mp-danger",children:["Cut Sheet Has ",h.length," Error",1!==h.length?"s":""]}),b.length>0&&(0,a.jsxs)("div",{className:"mt-2",children:[(0,a.jsx)("p",{className:"text-sm text-mp-danger",children:"Missing wire cutting params for connector families:"}),(0,a.jsx)("ul",{className:"mt-1 list-disc list-inside text-sm text-mp-danger",children:b.map(e=>(0,a.jsx)("li",{className:"font-mono",children:e},e))}),(0,a.jsx)("p",{className:"mt-2 text-xs text-mp-danger",children:"Add these families in Admin â Wire Cutting Params, then click Regenerate."})]})]}),m&&(0,a.jsxs)("button",{onClick:m,className:"px-3 py-1.5 text-sm font-medium text-mp-danger bg-mp-danger/10 rounded-[2px] hover:bg-mp-danger/10 flex items-center gap-1.5",children:[(0,a.jsx)("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,a.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Regenerate"]})]})}),(0,a.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,a.jsx)("h4",{className:"font-medium text-gray-900 dark:text-zinc-100",children:(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)(d.Z,{className:"h-5 w-5 text-gray-400"}),(0,a.jsx)("span",{children:"Cut Sheet"}),y&&(0,a.jsxs)("span",{className:"ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-mp-danger/10 text-mp-danger",children:[h.length," error",1!==h.length?"s":""]})]})}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[m&&(0,a.jsxs)("button",{onClick:m,className:"inline-flex items-center px-3 py-2 border border-gray-300 dark:border-zinc-600 shadow-sm text-sm leading-4 font-medium rounded-[2px] text-gray-700 dark:text-zinc-300 bg-white dark:bg-zinc-900 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-mp-orange",children:[(0,a.jsx)("svg",{className:"h-4 w-4 mr-2",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,a.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Regenerate"]}),(0,a.jsxs)("button",{onClick:()=>{x(u,n)||t("Pop-Ups Blocked","Please allow pop-ups to print the cut sheet.")},className:"inline-flex items-center px-3 py-2 border border-gray-300 dark:border-zinc-600 shadow-sm text-sm leading-4 font-medium rounded-[2px] text-gray-700 dark:text-zinc-300 bg-white dark:bg-zinc-900 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-mp-blue",children:[(0,a.jsx)(c.Z,{className:"h-4 w-4 mr-2"}),"Print Cut Sheet"]})]})]}),(0,a.jsx)("div",{className:"bg-mp-paper rounded-[4px] p-4",children:(0,a.jsx)("div",{className:"overflow-visible",children:(0,a.jsxs)("table",{className:"min-w-full",children:[(0,a.jsx)("thead",{children:(0,a.jsxs)("tr",{className:"text-left text-gray-900 dark:text-zinc-100 border-b border-gray-200 dark:border-zinc-700",children:[(0,a.jsx)("th",{className:"pb-2 w-24 text-center",children:"Assy ID"}),(0,a.jsx)("th",{className:"pb-2 min-w-[150px] max-w-[200px] text-center",children:"Assy Name"}),(0,a.jsx)("th",{className:"pb-2 w-24 text-center",children:"Wire ID"}),(0,a.jsx)("th",{className:"pb-2 w-32 text-center",children:"Wire Family"}),(0,a.jsx)("th",{className:"pb-2 w-24 text-center",children:"Color"}),(0,a.jsx)("th",{className:"pb-2 w-20 text-center",children:"Gauge"}),(0,a.jsx)("th",{className:"pb-2 w-40 text-center",children:"Side A"}),(0,a.jsx)("th",{className:"pb-2 w-40 text-center",children:"Side B"}),(0,a.jsx)("th",{className:"pb-2 w-28 text-center",children:"Length (mm)"}),(0,a.jsx)("th",{className:"pb-2 w-16 text-center",children:"Qty"})]})}),(0,a.jsx)("tbody",{className:"divide-y divide-gray-200",children:u.map((e,t)=>(0,a.jsxs)("tr",{className:"".concat(e.hasError?"bg-mp-danger/10":""),children:[(0,a.jsx)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"),children:(0,a.jsxs)("div",{className:"flex items-center justify-center",children:[(0,a.jsx)("span",{children:e.assyID}),e.hasError&&e.errorMessage&&(0,a.jsxs)("div",{className:"relative inline-block group",children:[(0,a.jsx)(l.Z,{className:"h-5 w-5 text-mp-danger ml-2"}),(0,a.jsx)("div",{className:"invisible group-hover:visible absolute -top-2 left-full ml-2 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-700 rounded-[4px] p-2 pl-4 z-[100] w-64",children:(0,a.jsxs)("div",{className:"relative",children:[e.errorMessage,(0,a.jsx)("div",{className:"absolute w-2 h-2 bg-white dark:bg-zinc-900 border-l border-b border-gray-200 dark:border-zinc-700 transform rotate-45 left-[-5px] top-[10px] -ml-1"})]})})]})]})}),(0,a.jsx)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:e.assyName}),(0,a.jsx)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:e.wireID}),(0,a.jsx)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:e.wireFamilyName}),(0,a.jsx)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:e.color}),(0,a.jsx)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:e.gauge}),(0,a.jsxs)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:[(0,a.jsxs)("div",{children:["Strip: ",e.sideAStrip,"mm"]}),e.sideAType&&(0,a.jsxs)("span",{className:"text-xs text-gray-500",children:["Type: ",e.sideAType]}),e.sideACrimpMPN&&(0,a.jsxs)("span",{className:"text-xs text-gray-500 block",children:["Crimp: ",e.sideACrimpMPN]})]}),(0,a.jsxs)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:[(0,a.jsxs)("div",{children:["Strip: ",e.sideBStrip,"mm"]}),e.sideBType&&(0,a.jsxs)("span",{className:"text-xs text-gray-500",children:["Type: ",e.sideBType]}),e.sideBCrimpMPN&&(0,a.jsxs)("span",{className:"text-xs text-gray-500 block",children:["Crimp: ",e.sideBCrimpMPN]})]}),(0,a.jsx)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:e.overallLength}),(0,a.jsx)("td",{className:"py-2 text-sm ".concat(e.hasError?"text-mp-danger":"text-gray-900 dark:text-zinc-100"," text-center"),children:e.qty})]},t))})]})})})]})}},18896:function(e,t,n){n.d(t,{W:function(){return x}});var a=n(57437),r=n(2265),i=n(12087),s=n(12521),o=n(45197),l=n(67499);let d={queued:{label:"Queued",tone:"active"},running:{label:"Running",tone:"active"}
1,needs_input:{label:"Needs Input",tone:"info"},done:{label:"Done",tone:"positive"},failed:{label:"Failed",tone:"danger"},cancelled:{label:"Cancelled",tone:"danger"}},c={queued:!0,running:!0},m={active:"border-mp-orange/40 bg-mp-orange/10 text-mp-orange",info:"border-mp-blue/40 bg-mp-blue/10 text-mp-blue",positive:"border-mp-positive/40 bg-mp-positive/10 text-mp-positive",warning:"border-mp-warning/40 bg-mp-warning/10 text-mp-warning",danger:"border-mp-danger/40 bg-mp-danger/10 text-mp-danger"};function p(e,t,n){let a=e;if(null==a&&t&&(a=Math.max(0,Math.round(((n?new Date(n).getTime():Date.now())-new Date(t).getTime())/1e3))),null==a)return"â";if(a<60)return"".concat(a,"s");let r=Math.floor(a/60),i=a%60;return i?"".concat(r,"m ").concat(i,"s"):"".concat(r,"m")}function u(e,t){if(!e)return null;let n=new Date(e).getTime();return Number.isNaN(n)?null:Math.max(0,Math.floor((t-n)/1e3))}function x(e){var t,n,x,h,f,g,b,y;let{runsUrl:v,canRun:j,canSend:N,runKind:w,reviseKind:k,hasPriorRunLabel:S,onRunStateChange:C,summaryLinks:I,flush:T=!1}=e,{showError:E,showSuccess:M,showInfo:O}=(0,s.pm)(),[A,F]=(0,r.useState)([]),[D,R]=(0,r.useState)(""),[P,L]=(0,r.useState)(!1),[_,z]=(0,r.useState)(null),[U,q]=(0,r.useState)(0),[B,Z]=(0,r.useState)(()=>Date.now()),H=(0,r.useRef)(!1),W=(0,r.useRef)(null),Q=(0,r.useRef)(null),J=A[0],G=null==J?void 0:J.status,V=!!(G&&c[G]),K="running"===G,Y=(0,r.useCallback)(async()=>{try{var e;let t=await fetch(v,{cache:"no-store"});if(!t.ok){o.k.error("Failed to load agent runs",{runsUrl:v,status:t.status});return}let n=await t.json();F((null!==(e=n.runs)&&void 0!==e?e:[]).map(e=>{var t;return{...e,events:null!==(t=e.events)&&void 0!==t?t:[]}}))}catch(e){o.k.error("Failed to load agent runs",{runsUrl:v,error:e instanceof Error?e.message:String(e)})}},[v]);(0,r.useEffect)(()=>{Y()},[Y,U,j,N]),(0,r.useEffect)(()=>{if(!V)return;let e=window.setInterval(()=>{Y()},3e3);return()=>window.clearInterval(e)},[Y,V]),(0,r.useEffect)(()=>{if(!K)return;let e=()=>Z(Date.now());e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[K]),(0,r.useEffect)(()=>()=>{null!=W.current&&window.clearTimeout(W.current)},[]),(0,r.useEffect)(()=>{if(V){H.current=!0;return}H.current&&(H.current=!1,null==C||C(!1))},[C,V]);let $=(0,r.useCallback)(async(e,t)=>{let n=!!A.some(e=>c[e.status]);z(e);try{let a=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e===k?{kind:e,instruction:t}:{kind:e})}),r=await a.json().catch(()=>({}));if(!a.ok||!1===r.ok){E("Could not start AI run","string"==typeof r.code&&r.code.length>0?r.code:String(a.status));return}e===k?(R(""),n?O("Queued behind the active run"):M("Revision queued")):M("AI run queued"),q(e=>e+1),null!=W.current&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{W.current=null,Y()},2e3),null==C||C(!0)}catch(e){E("Could not start AI run",e instanceof Error?e.message:"Network error")}finally{z(null)}},[Y,C,k,A,v,E,O,M]),X=null!==(t=null==J?void 0:J.events)&&void 0!==t?t:[],ee=(0,r.useMemo)(()=>X.filter(e=>"log"!==e.kind),[X]),et=(0,r.useMemo)(()=>X.filter(e=>"log"===e.kind),[X]),en=(0,r.useMemo)(()=>et.map(e=>e.body).join("\n"),[et]),ea=(0,r.useMemo)(()=>(function(e){if(!e)return"";let t=e.split("\n");return t.length<=200?e:t.slice(-200).join("\n")})(en),[en]),er=!!((null==J?void 0:J.resultMd)&&ee.some(e=>{var t;return e.body.trim()===(null===(t=J.resultMd)||void 0===t?void 0:t.trim())}));(0,r.useLayoutEffect)(()=>{if(!V)return;let e=Q.current;e&&(e.scrollTop=e.scrollHeight)},[ea,V]);let ei=j&&null===_,es=N&&null===_,eo=D.trim(),el=A.length>0?"Re-run AI":"Run AI",ed=J?(b=J.status,y=J.outcome,"done"!==b||null==y||"built"===y?d[b]:"blocked"===y?{label:"Blocked",tone:"warning",title:"Run finished with blockers. It was not marked built."}:{label:"No Quote Suggested",tone:"warning",title:"Run finished. The rulebook says not to quote this."}):null,ec=J?function(e,t){let n="wi_build"===e||"wi_revise"===e,a=n?"Handbook":"Rulebook",r=n?"Operations Handbook":"Quoting Rulebook";return t?{label:a,value:r,title:"".concat(r," used for this run")}:{label:a,value:"â"}}(J.kind,J.rulebookHash):null,em=K?u(null!==(x=null!==(n=null==J?void 0:J.startedAt)&&void 0!==n?n:null==J?void 0:J.createdAt)&&void 0!==x?x:null,B):null,ep=K?u(null!==(h=null==J?void 0:J.heartbeatAt)&&void 0!==h?h:null,B):null;return(0,a.jsxs)("div",{className:T?"flex flex-col border-b admin-border":"flex h-full min-h-[28rem] flex-col rounded-[4px] border admin-border admin-bg-secondary shadow-sm",children:[(0,a.jsx)("div",{className:"border-b admin-border px-4 py-3",children:(0,a.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("h2",{className:"text-sm font-semibold admin-text-primary",children:null!=S?S:"AI Runner"}),I&&I.length>0?(0,a.jsx)("p",{className:"mt-1 text-xs admin-text-muted",children:I.map((e,t)=>(0,a.jsxs)("span",{children:[t>0?" \xb7 ":null,(0,a.jsxs)("a",{href:e.href,className:"underline-offset-2 hover:underline",children:[e.count," ",e.label,1===e.count?"":"s"]})]},e.href))}):null]}),(0,a.jsxs)("button",{type:"button",onClick:()=>void $(w),disabled:!ei,title:V?"AI run in progress":void 0,className:"inline-flex items-center gap-1.5 rounded-[2px] border border-mp-orange px-3 py-1.5 text-sm font-medium text-mp-orange hover:bg-mp-orange/10 disabled:cursor-not-allowed disabled:opacity-50",children:[(0,a.jsx)(i.Z,{className:"h-4 w-4"}),_===w?"Queuing...":el]})]})}),J?(0,a.jsxs)("div",{className:"border-b admin-border px-4 py-3 space-y-2",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsx)("span",{className:"text-sm font-medium admin-text-primary",children:J.kind.replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}),ed?(0,a.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-[2px] border px-2 py-0.5 text-[11px] font-semibold ".concat(m[ed.tone]),title:ed.title,children:[K?(0,a.jsx)("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-current animate-pulse","aria-hidden":"true"}):null,ed.label]}):null]}),(0,a.jsxs)("dl",{className:"grid grid-cols-2 gap-x-3 gap-y-1 text-xs admin-text-muted",children:[K?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{className:"inline",children:"Elapsed "}),(0,a.jsx)("dd",{className:"inline admin-text-secondary",children:p(em,null,null)})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{className:"inline",children:"Heartbeat "}),(0,a.jsx)("dd",{className:"inline ".concat(null!=ep&&ep>120?"text-mp-danger":"admin-text-secondary"),children:null==ep?"â":"".concat(ep,"s ago")})]})]}):"queued"===J.status?(0,a.jsxs)("div",{className:"col-span-2",children:[(0,a.jsx)("dt",{className:"inline",children:"Elapsed "}),(0,a.jsx)("dd",{className:"inline admin-text-secondary",children:"Waiting for runner"})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{className:"inline",children:"Started "}),(0,a.jsx)("dd",{className:"inline admin-text-secondary",children:J.startedAt&&!Number.isNaN(new Date(J.startedAt).getTime())?(0,l.a_)(new Date(J.startedAt),l.Cu):"â"})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{className:"inline",children:"Duration "}),(0,a.jsx)("dd",{className:"inline admin-text-secondary",children:p(J.durationSeconds,J.startedAt,J.completedAt)})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("dt",{className:"inline",children:"Model "}),(0,a.jsx)("dd",{className:"inline admin-text-secondary",children:J.model||"â"})]}),(0,a.jsxs)("div",{className:"col-span-2",children:[(0,a.jsxs)("dt",{className:"inline",children:[null!==(f=null==ec?void 0:ec.label)&&void 0!==f?f:"Rulebook"," "]}),(0,a.jsx)("dd",{className:"inline admin-text-secondary",title:null==ec?void 0:ec.title,children:null!==(g=null==ec?void 0:ec.value)&&void 0!==g?g:"â"})]}),J.executor?(0,a.jsx)("div",{className:"col-span-2",children:(0,a.jsxs)("dd",{className:"inline admin-text-secondary",children:["Runner ",J.executor]})}):null]}),J.failureReason?(0,a.jsx)("pre",{className:"m-0 whitespace-pre-wrap break-words font-mono text-xs text-mp-danger",children:J.failureReason}):null]}):null,(0,a.jsx)("div",{className:T?"max-h-56 space-y-2 overflow-y-auto px-4 py-3":"flex-1 space-y-2 overflow-y-auto px-4 py-3",children:J?(0,a.jsxs)(a.Fragment,{children:[ee.map(e=>{if("user_message"===e.kind)return(0,a.jsx)("div",{className:"ml-8 rounded-[4px] bg-mp-blue/10 px-3 py-2 text-sm admin-text-primary",children:e.body},e.id);if("agent_message"===e.kind)return(0,a.jsx)("div",{className:"mr-8 rounded-[4px] admin-bg-tertiary px-3 py-2 text-sm admin-text-primary whitespace-pre-wrap",children:e.body},e.id);let t=function(e){let t=new Date(e);return Number.isNaN(t.getTime())?"":(0,l.a_)(t,"HH:mm:ss")}(e.createdAt);return(0,a.jsxs)("p",{className:"text-xs admin-text-muted",children:[t?(0,a.jsx)("span",{className:"mr-2 font-mono",children:t}):null,e.body]},e.id)}),J.resultMd&&"done"===J.status&&!er?(0,a.jsx)("div",{className:"text-sm admin-text-secondary whitespace-pre-wrap break-words",children:J.resultMd}):null,V?(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"text-xs font-medium admin-text-muted",children:"Live log"}),(0,a.jsx)("pre",{ref:Q,className:"mt-2 max-h-48 overflow-y-auto rounded-[4px] admin-bg-tertiary p-2 text-[11px] admin-text-muted whitespace-pre-wrap",children:ea})]}):et.length>0?(0,a.jsxs)("div",{children:[(0,a.jsx)("button",{type:"button",onClick:()=>L(e=>!e),className:"text-xs font-medium admin-text-muted hover:admin-text-primary",children:P?"Hide log":"Show log"}),P?(0,a.jsx)("pre",{className:"mt-2 max-h-48 overflow-y-auto rounded-[4px] admin-bg-tertiary p-2 text-[11px] admin-text-muted whitespace-pre-wrap",children:en}):null]}):null]}):(0,a.jsxs)("div",{className:T?"flex flex-col items-center justify-center gap-2 py-2 text-center":"flex h-full min-h-[12rem] flex-col items-center justify-center gap-3 text-center",children:[(0,a.jsx)("p",{className:"text-sm admin-text-muted",children:"No AI runs yet"}),(0,a.jsxs)("button",{type:"button",onClick:()=>void $(w),disabled:!ei,className:"inline-flex items-center gap-1.5 rounded-[2px] bg-mp-orange px-3 py-1.5 text-sm font-medium text-white hover:bg-mp-orange/90 disabled:cursor-not-allowed disabled:opacity-50",children:[(0,a.jsx)(i.Z,{className:"h-4 w-4"}),"Run AI"]})]})}),(0,a.jsxs)("form",{className:"border-t admin-border p-3 space-y-2",onSubmit:e=>{e.preventDefault(),es&&0!==eo.length&&$(k,eo)},children:[(0,a.jsx)("textarea",{value:D,onChange:e=>R(e.target.value),disabled:!es,rows:3,placeholder:es?"Ask for a revision...":"Revisions are not available yet",className:"w-full resize-none rounded-[2px] border admin-border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-mp-blue disabled:admin-bg-tertiary disabled:cursor-not-allowed"}),(0,a.jsx)("div",{className:"flex justify-end",children:(0,a.jsx)("button",{type:"submit",disabled:!es||0===eo.length,className:"rounded-[2px] bg-mp-orange px-3 py-1.5 text-sm font-medium text-white hover:bg-mp-orange/90 disabled:cursor-not-allowed disabled:opacity-50",children:_===k?"Sending...":"Send"})})]})]})}},54793:function(e,t,n){n.d(t,{$:function(){return a}});let a=[{id:"tol-standard",label:"Tolerances â Standard",toleranceTier:"standard",content:"## Tolerance: Standard (bilateral)\n\n| Length | Allowed |\n|---|---|\n| â¤300mm | \xb112.5mm |\
1n| 300â1500mm | \xb125mm |\n| 1500â3000mm | \xb150mm |\n| >3000mm | \xb175mm |\n\nMeasure connector backshell to connector backshell unless drawing specifies otherwise."},{id:"tol-precision",label:"Tolerances â Precision",toleranceTier:"precision",content:"## Tolerance: Precision (bilateral)\n\n| Length | Allowed |\n|---|---|\n| â¤300mm | \xb17.5mm |\n| 300â1500mm | \xb115mm |\n| 1500â3000mm | \xb130mm |\n| >3000mm | \xb150mm |\n\nMeasure connector backshell to connector backshell unless drawing specifies otherwise."},{id:"tol-high",label:"Tolerances â High-Precision",toleranceTier:"high-precision",content:"## Tolerance: High-Precision (bilateral)\n\n| Length | Allowed |\n|---|---|\n| â¤300mm | \xb12.5mm |\n| 300â1500mm | \xb15mm |\n| 1500â3000mm | \xb110mm |\n| >3000mm | \xb125mm |\n\nMeasure connector backshell to connector backshell unless drawing specifies otherwise."}]},30061:function(e,t,n){function a(e,t,n,a){let r=e.indexOf(n);if(r<0)return null;let i=r+a;for(;i>=0&&i<e.length&&!t.has(e[i]);)i+=a;if(i<0||i>=e.length)return null;let s=e.slice();return[s[r],s[i]]=[s[i],s[r]],s}function r(e,t){let n=new Set(t),a=0;return e.map(e=>n.has(e)?t[a++]:e)}n.d(t,{I:function(){return a},J:function(){return r}})},89917:function(e,t,n){n.d(t,{z:function(){return h}});var a=n(57437),r=n(2265),i=n(19967),s=n(87626),o=n(77165),l=n(11454),d=n(47842),c=n(69613);let m=["image/png","image/jpeg","image/jpg","image/gif","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],p=e=>{var t;return["png","jpg","jpeg","gif","webp"].includes((null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"")?(0,a.jsx)(i.Z,{className:"h-5 w-5 text-mp-blue"}):(0,a.jsx)(s.Z,{className:"h-5 w-5 text-gray-500 dark:text-zinc-400"})},u=e=>{try{let t=new URL(e).pathname.split("/").pop()||"file",n=t.split(".");if(n.length>=2){let e=n.slice(0,-1).join("."),t=n[n.length-1];if(36===e.length&&e.includes("-"))return"file.".concat(t)}return t}catch(t){return e.split("/").pop()||"file"}},x=e=>{var t;return["png","jpg","jpeg","gif","webp"].includes((null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"")};function h(e){let{attachmentUrls:t,onAttachmentsChange:n,maxAttachments:i=5,disabled:s=!1}=e,[h,f]=(0,r.useState)(!1),[g,b]=(0,r.useState)(null),[y,v]=(0,r.useState)(!1),[j,N]=(0,r.useState)(null),w=(0,r.useRef)(null),k=t.length<i,S=(0,r.useCallback)(async e=>{if(!k){b("Maximum ".concat(i," attachments allowed"));return}if(e.size>10485760){b("File too large. Maximum size is 10MB");return}if(!m.includes(e.type)){b("File type not allowed. Use images, PDFs, or documents.");return}b(null),f(!0);try{let a=new FormData;a.append("file",e);let r=await fetch("/api/upload",{method:"POST",body:a});if(!r.ok){let e=await r.json();throw Error(e.error||"Upload failed")}let i=await r.json();n([...t,i.url])}catch(e){console.error("Upload error:",e),b(e instanceof Error?e.message:"Upload failed")}finally{f(!1)}},[t,k,i,n]),C=e=>{n(t.filter((t,n)=>n!==e))},I=(0,r.useCallback)(e=>{var t;if(s||!k)return;let n=null===(t=e.clipboardData)||void 0===t?void 0:t.items;if(n){for(let t of Array.from(n))if(t.type.startsWith("image/")){e.preventDefault();let n=t.getAsFile();n&&S(n);return}}},[s,k,S]);return(0,a.jsxs)("div",{className:"space-y-2",onPaste:I,children:[(0,a.jsxs)("label",{className:"block text-xs font-medium admin-text-primary",children:["Attachments (",t.length,"/",i,")"]}),t.length>0&&(0,a.jsx)("div",{className:"flex flex-wrap gap-2",children:t.map((e,t)=>(0,a.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1.5 admin-bg-tertiary border admin-border dark:border-zinc-700 rounded group",children:[x(e)?(0,a.jsxs)("button",{onClick:()=>N(e),className:"flex items-center gap-2 hover:text-mp-orange text-left",title:"Click to view",children:[(0,a.jsx)("img",{src:e,alt:"attachment",className:"h-6 w-6 object-cover rounded"}),(0,a.jsx)("span",{className:"text-xs admin-text-secondary dark:text-zinc-300 max-w-[100px] truncate",children:u(e)})]}):(0,a.jsxs)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 hover:text-mp-orange",children:[p(e),(0,a.jsx)("span",{className:"text-xs admin-text-secondary dark:text-zinc-300 max-w-[100px] truncate",children:u(e)})]}),!s&&(0,a.jsx)("button",{onClick:()=>C(t),className:"p-0.5 text-gray-400 hover:text-mp-danger opacity-100 transition-opacity focus-visible:opacity-100 lg:opacity-0 lg:group-hover:opacity-100",title:"Remove attachment",children:(0,a.jsx)(o.Z,{className:"h-4 w-4"})})]},t))}),k&&!s&&(0,a.jsxs)("div",{onDragOver:e=>{e.preventDefault(),!s&&k&&v(!0)},onDragLeave:e=>{e.preventDefault(),v(!1)},onDrop:e=>{if(e.preventDefault(),v(!1),s||!k)return;let t=e.dataTransfer.files[0];t&&S(t)},onClick:()=>{var e;return null===(e=w.current)||void 0===e?void 0:e.click()},className:"flex items-center justify-center gap-2 px-3 py-3 border-2 border-dashed rounded-[4px] curs
1or-pointer transition-colors ".concat(y?"border-mp-orange bg-mp-orange/10 dark:bg-mp-orange/15":"admin-border dark:border-zinc-600 hover:admin-border hover:admin-bg-tertiary"," ").concat(h?"opacity-50 cursor-wait":""),children:[(0,a.jsx)("input",{ref:w,type:"file",onChange:e=>{var t;let n=null===(t=e.target.files)||void 0===t?void 0:t[0];n&&S(n),e.target.value=""},accept:m.join(","),className:"hidden",disabled:h||s}),h?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-mp-orange"}),(0,a.jsx)("span",{className:"text-xs text-gray-500 dark:text-zinc-400",children:"Uploading..."})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(l.Z,{className:"h-4 w-4 text-gray-400"}),(0,a.jsx)("span",{className:"text-xs text-gray-500 dark:text-zinc-400",children:"Drop, paste, or click to upload"})]})]}),g&&(0,a.jsxs)("div",{className:"flex items-center gap-1 text-xs text-mp-danger",children:[(0,a.jsx)(d.Z,{className:"h-4 w-4"}),g]}),0===t.length&&!k&&(0,a.jsxs)("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-zinc-400",children:[(0,a.jsx)(c.Z,{className:"h-4 w-4"}),"No attachments"]}),j&&(0,a.jsx)("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black bg-opacity-75 p-4",onClick:()=>N(null),children:(0,a.jsxs)("div",{className:"relative max-w-4xl max-h-[90vh] bg-white dark:bg-zinc-900 rounded-[4px] overflow-hidden",onClick:e=>e.stopPropagation(),children:[(0,a.jsxs)("div",{className:"absolute top-0 left-0 right-0 flex items-center justify-between p-3 z-10",children:[(0,a.jsx)("span",{className:"text-white text-sm font-medium truncate max-w-md",children:u(j)}),(0,a.jsx)("button",{onClick:()=>N(null),className:"text-white hover:text-gray-300 p-1",children:(0,a.jsx)(o.Z,{className:"h-6 w-6"})})]}),(0,a.jsx)("img",{src:j,alt:"Preview",className:"max-w-full max-h-[85vh] object-contain"}),(0,a.jsx)("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-center gap-4 p-3",children:(0,a.jsx)("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"text-white text-sm hover:underline flex items-center gap-1",children:"Open full size"})})]})})]})}},44849:function(e,t,n){n.r(t),n.d(t,{WiSetupModal:function(){return ti},default:function(){return to}});var a=n(57437),r=n(2265),i=n(54887),s=n(97082),o=n(18896),l=n(56009),d=n(25604),c=n(12521),m=n(74738),p=n(45197);function u(e){if(null==e||""===e)return null;let t="number"==typeof e?e:parseFloat(String(e));return Number.isFinite(t)&&0!==t?t:null}function x(e){var t,n;let a=u(e.manualOverrideSeconds);if(null!==a)return{source:"manual",perUnitSeconds:a};let r=u(e.quoteEstimatedSeconds);if(null!==r)return{source:"quote",perUnitSeconds:r};let i=(t=e.workStepTimeStandard,n=e.complexity,t?u("simple"===n?t.simpleTime:"complex"===n?t.complexTime:t.mediumTime):null);if(null!==i)return{source:"standard",perUnitSeconds:i};let s=u(e.defaultSecsPerUnit);return null!==s?{source:"catalog",perUnitSeconds:s}:{source:"catalog",perUnitSeconds:0}}var h=n(30061);n(25566);var f=n(93586);function g(e){if(e<=0)return"0m";if(e<1)return"".concat(Math.round(60*e),"s");if(e<60){let t=Math.round(10*e)/10;return"".concat(t%1==0?t.toString():t.toFixed(1),"m")}let t=Math.floor(e/60),n=Math.round(e%60);return n>0?"".concat(t,"h ").concat(n,"m"):"".concat(t,"h")}let b={quote:"From Quote",standard:"From Standard",catalog:"From Catalog",manual:"Manual"},y=new Set(["operationName","operationDescription","complexity","level","estimatedTime","operationQuantity","timeMultiplier","timeMultiplierReason","customInstructions","attachmentUrls","referenceDocUrl","assemblyDrawingUrl","requiredTools","isEnriched","workStepId","libraryOperationId","quoteTimeApplication"]);function v(e){return Array.isArray(e)?e.flatMap(e=>e&&"object"==typeof e&&"id"in e&&"string"==typeof e.id?[{id:e.id}]:[]):[]}let j={GRAPH_CYCLE:"Routing Loops",SS_REQUIRES_QC:"Only QC Can Start With Another Step",TERMINAL_MUST_BE_SINK:"Close Out Must Be Last",KITTING_MUST_BE_SOURCE:"Kitting Must Be First",INVALID_EDGE:"Invalid Dependency",SHOP_WORK_NO_ROUTING:"Shop Work Has No Routing",SEQUENCE_NOT_TOPOLOGICAL:"Order Conflicts With Routing"};var N=n(64784),w=n.n(N),k=n(74497);let S={wire_prep:"prep",cable_prep:"prep",crimp_auto:"terminate",crimp_hand:"terminate",splice_solder:"terminate",insert:"terminate",covering:"build",assembly:"build",label:"build"},C={prep:"#0ea5e9",terminate:"#8b5cf6",build:"#65a30d",qc:"#6b7280"},I={prep:"Prep",terminate:"Terminate",build:"Build",qc:"QC / Support"};function T(e){return e&&S[e]||"qc"}let E=["15%","32%","50%","68%","85%"],M=e=>
1"".concat(e.dependsOnOperationId,"->").concat(e.operationId);function O(e){return e<=0?[]:1===e?[2]:2===e?[1,3]:3===e?[1,2,3]:4===e?[0,1,3,4]:Array.from({length:e},(t,n)=>Math.round(4*n/(e-1)))}function A(e,t){return(0,k.Xl)(e.opCatalogType)-(0,k.Xl)(t.opCatalogType)||e.sequenceNumber-t.sequenceNumber||e.id.localeCompare(t.id)}var F=n(2494),D=n(43836),R=n(87233),P=n(47842),L=n(48217),_=n(12594),z=n(61601),U=n(88401);function q(e){let{buildOrderId:t,salesOrderNumber:n,orderSource:i}=e,s=(0,d.Y)(),{showError:o}=(0,c.pm)(),{effectiveRole:l}=(0,U.N)(),[m,u]=(0,r.useState)([]),[x,h]=(0,r.useState)(!0),[f,g]=(0,r.useState)(null),[b,y]=(0,r.useState)(!1),[v,j]=(0,r.useState)(""),[N,w]=(0,r.useState)(!1),[k,S]=(0,r.useState)(null),[C,I]=(0,r.useState)(""),[T,E]=(0,r.useState)(!1),[M,O]=(0,r.useState)(null),[A,q]=(0,r.useState)(""),B=(0,r.useCallback)(async()=>{try{h(!0),g(null);let e=new URLSearchParams;e.set("buildOrderId",t),e.set("includeResolved","true");let n=await fetch("/api/admin/assembler-notes?".concat(e));if(!n.ok){let e=await n.json();throw Error(e.error||"Failed to fetch notes")}let a=await n.json();u(a.notes||[])}catch(e){p.k.error("Error fetching notes",{error:e instanceof Error?e.message:String(e)}),g(e instanceof Error?e.message:"Failed to load notes")}finally{h(!1)}},[t]);(0,r.useEffect)(()=>{B()},[B]);let Z=async e=>{if(e.preventDefault(),v.trim()){E(!0);try{let e=await fetch("/api/admin/assembler-notes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({buildOrderId:t,content:v.trim(),noteType:N?"redline":"general",severity:N?"critical":"info"})});if(!e.ok){let t=await e.json();throw Error(t.error||"Failed to create note")}await B(),j(""),w(!1),y(!1)}catch(e){p.k.error("Error creating note",{error:e instanceof Error?e.message:String(e)}),o("Note Creation Failed",e instanceof Error?e.message:"Failed to create note")}finally{E(!1)}}},H=async e=>{if(await s.confirm({title:"Delete Note?",description:"Delete this note?",confirmText:"Delete",variant:"destructive"}))try{let t=await fetch("/api/admin/assembler-notes",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({noteId:e})});if(!t.ok){let e=await t.json();throw Error(e.error||"Failed to delete note")}await B()}catch(e){p.k.error("Error deleting note",{error:e instanceof Error?e.message:String(e)}),o("Note Delete Failed",e instanceof Error?e.message:"Failed to delete note")}},W=async e=>{if(C.trim()){E(!0);try{let n=await fetch("/api/admin/assembler-notes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({buildOrderId:t,parentNoteId:e,content:C.trim(),noteType:"general",severity:"info"})});if(!n.ok){let e=await n.json();throw Error(e.error||"Failed to create reply")}await B(),I(""),S(null)}catch(e){p.k.error("Error creating reply",{error:e instanceof Error?e.message:String(e)}),o("Reply Creation Failed",e instanceof Error?e.message:"Failed to create reply")}finally{E(!1)}}},Q=async e=>{if(A.trim()){E(!0);try{let t=await fetch("/api/admin/assembler-notes",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({noteId:e,action:"edit",content:A.trim()})});if(!t.ok){let e=await t.json();throw Error(e.error||"Failed to update note")}await B(),O(null),q("")}catch(e){p.k.error("Error updating note",{error:e instanceof Error?e.message:String(e)}),o("Note Update Failed",e instanceof Error?e.message:"Failed to update note")}finally{E(!1)}}},J=e=>{O(e.id),q(e.content)},G=()=>{O(null),q("")},V=e=>{if(!e)return"?";let t=e.trim().split(/\s+/);return 1===t.length?t[0].charAt(0).toUpperCase():(t[0].charAt(0)+t[t.length-1].charAt(0)).toUpperCase()};return x?(0,a.jsx)("div",{className:"p-4",children:(0,a.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,a.jsx)("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-mp-orange"}),(0,a.jsx)("span",{className:"ml-2 text-sm admin-text-muted",children:"Loading..."})]})}):(0,a.jsxs)("div",{className:"p-4 space-y-6",children:[n&&"cart_checkout"===i&&(0,a.jsxs)("a",{href:"/configuratorV2?orderNumber=".concat(n),target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 px-3 py-2 text-sm font-medium text-mp-orange border border-mp-orange rounded-[4px] hover:bg-mp-orange/10 dark:hover:bg-mp-orange/15 transition-colors",children:[(0,a.jsx)(F.Z,{className:"h-4 w-4"}),"View in Configurator"]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{className:"flex items-center justify-between mb-3",children:(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary",children:["Notes",m.length>0&&(0,a.jsxs)("span",{className:"ml-1 text-xs admin-text-muted",children:["(",m.length,")"]})]})}),!b&&(0,a.jsxs)("button",{onClick:()=>y(!0),className:"w-full mb-3 py-2 px-3 bg-mp-warning hover:bg-mp-warning text-white text-sm font-medium rounded-[4px] flex items-center justify-center gap-2 transition-colors",children:[(0,a.jsx)(D.Z,{className:"h-4 w-4"}),"Add Note"]}),b&&(0,a.jsxs)("form",{onSubmit:Z,className:"mb-3 p-3 border rounded-[4px] ".concat(N?"border-mp-danger/40 dark:border-mp-danger bg-mp-danger/10 dar
1k:bg-mp-danger/15":"admin-border bg-mp-warning/10 dark:bg-mp-warning/15"),children:[(0,a.jsx)("textarea",{value:v,onChange:e=>j(e.target.value),placeholder:N?"Enter redline note...":"Enter note...",rows:3,className:"w-full text-sm border rounded px-2 py-1.5 focus:ring-mp-orange focus:border-mp-orange ".concat(N?"border-mp-danger/40 dark:border-mp-danger":"admin-border"),autoFocus:!0}),(0,a.jsxs)("div",{className:"flex items-center justify-between mt-2",children:["admin"===l||"manager"===l?(0,a.jsxs)("label",{className:"flex items-center gap-2 cursor-pointer",children:[(0,a.jsx)("input",{type:"checkbox",checked:N,onChange:e=>w(e.target.checked),className:"w-4 h-4 text-mp-danger admin-border dark:border-zinc-600 rounded focus:ring-mp-danger"}),(0,a.jsx)("span",{className:"text-xs font-medium ".concat(N?"text-mp-danger":"admin-text-secondary"),children:"Mark as Redline"})]}):(0,a.jsx)("div",{}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)("button",{type:"button",onClick:()=>{y(!1),j(""),w(!1)},className:"px-3 py-1.5 text-xs admin-text-secondary hover:admin-text-primary",children:"Cancel"}),(0,a.jsx)("button",{type:"submit",disabled:!v.trim()||T,className:"px-3 py-1.5 text-xs text-white rounded disabled:opacity-50 ".concat(N?"bg-mp-danger hover:bg-mp-danger":"bg-mp-warning hover:bg-mp-warning"),children:T?"Adding...":N?"Add Redline":"Add"})]})]})]}),f&&(0,a.jsx)("div",{className:"text-sm text-mp-danger py-2 mb-2",children:f}),0===m.length?(0,a.jsx)("div",{className:"text-sm admin-text-muted py-2 text-center",children:"No notes yet."}):(0,a.jsx)("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:m.filter(e=>!e.parentNoteId).map(e=>{let t=V(e.createdByName),n=M===e.id,r="redline"===e.noteType,i=k===e.id,s=m.filter(t=>t.parentNoteId===e.id);return(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("div",{className:"border rounded-[4px] p-3 group ".concat(n?"bg-mp-warning/10 dark:bg-mp-warning/15 admin-border":r?"border-mp-danger/40 dark:border-mp-danger bg-mp-danger/10 dark:bg-mp-danger/15":"admin-border admin-bg-secondary"),children:(0,a.jsxs)("div",{className:"flex gap-3",children:[(0,a.jsx)("div",{className:"flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold ".concat(r?"bg-mp-danger/10 dark:bg-mp-danger/15 text-mp-danger dark:text-mp-danger":"bg-mp-warning/10 dark:bg-mp-warning/15 text-mp-warning dark:text-mp-warning"),title:e.createdByName||"Unknown",children:t}),(0,a.jsx)("div",{className:"flex-1 min-w-0",children:n?(0,a.jsxs)("div",{children:[(0,a.jsx)("textarea",{value:A,onChange:e=>q(e.target.value),rows:3,className:"w-full text-sm border admin-border rounded px-2 py-1.5 focus:ring-mp-orange focus:border-mp-orange",autoFocus:!0}),(0,a.jsxs)("div",{className:"flex justify-end gap-2 mt-2",children:[(0,a.jsx)("button",{onClick:G,disabled:T,className:"px-2 py-1 text-xs admin-text-secondary hover:admin-text-primary",children:"Cancel"}),(0,a.jsxs)("button",{onClick:()=>Q(e.id),disabled:!A.trim()||T,className:"px-2 py-1 text-xs bg-mp-warning text-white rounded disabled:opacity-50 flex items-center gap-1",children:[(0,a.jsx)(R.Z,{className:"h-3 w-3"}),T?"Saving...":"Save"]})]})]}):(0,a.jsxs)(a.Fragment,{children:[r&&(0,a.jsxs)("div",{className:"flex items-center gap-1 mb-1",children:[(0,a.jsx)(P.Z,{className:"h-3.5 w-3.5 text-mp-danger"}),(0,a.jsx)("span",{className:"text-xs font-semibold text-mp-danger uppercase tracking-wide",children:"Redline"})]}),(0,a.jsx)("p",{className:"text-sm whitespace-pre-wrap ".concat(r?"text-mp-danger dark:text-mp-danger font-medium":"admin-text-primary"),children:e.content}),(0,a.jsxs)("div",{className:"flex items-center justify-between mt-1.5 text-xs admin-text-muted",children:[(0,a.jsxs)("span",{children:[e.createdByName||"Unknown"," \xb7 ",new Date(e.createdAt).toLocaleDateString()]}),(0,a.jsxs)("div",{className:"flex gap-1 opacity-100 transition-opacity focus-within:opacity-100 lg:opacity-0 lg:group-hover:opacity-100",children:[(0,a.jsx)("button",{onClick:()=>S(i?null:e.id),className:"text-mp-blue hover:text-mp-blue dark:hover:text-mp-blue-2 p-1",title:"Reply",children:(0,a.jsx)(L.Z,{className:"h-3.5 w-3.5"})}),(0,a.jsx)("button",{onClick:()=>J(e),className:"text-mp-blue hover:text-mp-blue dark:hover:text-mp-blue-2 p-1",title:"Edit note",children:(0,a.jsx)(_.Z,{className:"h-3.5 w-3.5"})}),(0,a.jsx)("button",{onClick:()=>H(e.id),className:"text-mp-danger hover:text-mp-danger dark:hover:text-mp-danger p-1",title:"Delete note",children:(0,a.jsx)(z.Z,{className:"h-3.5 w-3.5"})})]})]})]})})]})}),i&&(0,a.jsxs)("div",{className:"ml-8 p-2 border admin-border rounded-[4px] admin-bg-tertiary",children:[(0,a.jsx)("textarea",{value:C,onChange:e=>I(e.target.value),placeholder:"Write a reply...",rows:2,className:"w-full text-sm border admin-border rounded px-2 py-1.5 focus:ring-mp-orange focus:border-mp-orange",autoFocus:!0}),(0,a.jsxs)("div",{className:"flex justify-end gap-2 mt-2",children:[(0,a.jsx)("button",{onClick:()=>{S(null),I("")},className:"px-2 py-1 text-xs admin-text-secondary hover:admin-text-primary",children:"Cancel"}),(0,a.jsx)("button",{onClick:()=>W(e.id),disabled:!C.trim()||T,className:"px-2 py-1 text-xs bg-mp-blue text-white rounded disabled:opacity-50",children:T?"Sending...":"Reply"})]})]}),s.length>0&&(0,a.jsx)("div",{className:"ml-8 space-y-1",children:s.map(e=>{let t=V(e.createdByName),n=M===e.id;return(0,a.jsx)("div",{className:"border admin-border rounded-[4px] p-2 group ".concat(n?"bg-mp-warning/10 dark:bg-mp-warning/15":"admin-bg-tertiary"),children:(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)("div",{className:"flex-shrink-0 w-6 h-6 rounded-full admin-bg-tertiary dark:bg-zinc-700 text-gray-600 flex items-center justify-center text-xs font-semibold",title:e.createdByName||"Unknown",children:t}),(0,a.jsx)("div",{className:"flex-1 min-w-0",children:n?(0,a.jsxs)("div",{children:[(0,a.jsx)("textarea",{value:A,onChange:e=>q(e.target.value),rows:2,className:"w-full text-sm border admin-border rounded px-2 py-1 focus:ring-mp-orange focus:border-mp-orange",autoFocus:!0}),(0,a.jsxs)("div",{className:"flex justify-end gap-2 mt-1",children:[(0,a.jsx)("button",{onClick:G,disabled:T,className:"px-2 py-0.5 text-xs admin-text-secondary hover:admin-text-primary",children:"Cancel"}),(0,a.jsx)("button",{onClick:()=>Q(e.id),disabled:!A.trim()||T,className:"px-2 py-0.5 text-xs bg-mp-warning text-white rounded disabled:opacity-50",children:"Save"})]})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("p",{className:"text-sm admin-text-primary whitespace-pre-wrap",children:e.content}),(0,a.jsxs)("div",{className:"flex items-center justify-between mt-1 text-xs admin-text-muted",children:[(0,a.jsxs)("span",{children:[e.createdByName||"Unknown"," \xb7 ",new Date(e.createdAt).toLocaleDateString()]}),(0,a.jsxs)("div",{className:"flex gap-1 opacity-100 transition-opacity focus-within:opacity-100 lg:opacity-0 lg:group-hover:opacity-100",children:[(0,a.jsx)("button",{onClick:()=>J(e),className:"text-mp-blue hover:text-mp-blue dark:hover:text-mp-blue-2 p-0.5",title:"Edit",children:(0,a.jsx)(_.Z,{className:"h-3 w-3"})}),(0,a.jsx)("button",{onClick:()=>H(e.id),className:"text-mp-danger hover:text-mp-danger dark:hover:text-mp-danger p-0.5",title:"Delete",children:(0,a.jsx)(z.Z,{className:"h-3 w-3"})})]})]})]})})]})},e.id)})})]},e.id)})})]})]})}var B=n(31331),Z=n(81801),H=n(73910),W=n(19967),Q=n(87626),J=n(77165);function G(e){let{buildOrderId:t}=e,[n,i]=(0,r.useState)([]),[s,o]=(0,r.useState)(!0),[l,d]=(0,r.useState)(null),[c,m]=(0,r.useState)(null),[p,u]=(0,r.useState)(null),x=(0,r.useCallback)(async()=>{try{o(!0),d(null);
1let e=await fetch("/api/admin/work-instructions-review/bom-connectors?buildOrderId=".concat(t));if(!e.ok){let t=await e.json();throw Error(t.error||"Failed to fetch connectors")}let n=await e.json();i(n.connectors)}catch(e){console.error("Error fetching connectors:",e),d(e instanceof Error?e.message:"Failed to load connectors")}finally{o(!1)}},[t]);return((0,r.useEffect)(()=>{x()},[x]),s)?(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary mb-3 flex items-center gap-2",children:[(0,a.jsx)(B.Z,{className:"h-4 w-4"}),"BOM Connectors"]}),(0,a.jsxs)("div",{className:"flex items-center justify-center py-4",children:[(0,a.jsx)("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-mp-orange"}),(0,a.jsx)("span",{className:"ml-2 text-sm admin-text-muted",children:"Loading..."})]})]}):l?(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary mb-3 flex items-center gap-2",children:[(0,a.jsx)(B.Z,{className:"h-4 w-4"}),"BOM Connectors"]}),(0,a.jsx)("div",{className:"text-sm text-mp-danger py-2",children:l})]}):0===n.length?(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary mb-3 flex items-center gap-2",children:[(0,a.jsx)(B.Z,{className:"h-4 w-4"}),"BOM Connectors"]}),(0,a.jsx)("div",{className:"text-sm admin-text-muted py-2",children:"No connectors found in the BOM."})]}):(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary mb-3 flex items-center gap-2",children:[(0,a.jsx)(B.Z,{className:"h-4 w-4"}),"BOM Connectors (",n.length,")"]}),(0,a.jsx)("div",{className:"space-y-2 max-h-[calc(100vh-300px)] overflow-y-auto",children:n.map(e=>(0,a.jsx)(V,{connector:e,isExpanded:c===e.id,onToggle:()=>m(c===e.id?null:e.id),onViewImage:(e,t)=>u({url:e,label:t})},e.id))}),p&&(0,a.jsx)(K,{imageUrl:p.url,label:p.label,onClose:()=>u(null)})]})}function V(e){let{connector:t,isExpanded:n,onToggle:r,onViewImage:i}=e,s=t.pinoutImageUrls&&t.pinoutImageUrls.length>0,o=!!t.datasheetUrl,l=!!t.imageUrl,d=s||o||l;return(0,a.jsxs)("div",{className:"border admin-border rounded-[4px] overflow-hidden admin-bg-secondary",children:[(0,a.jsxs)("button",{onClick:r,className:"w-full px-3 py-2 flex items-center justify-between text-left hover:admin-bg-tertiary transition-colors",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[t.imageUrl?(0,a.jsx)("img",{src:t.imageUrl,alt:t.mpn,className:"w-8 h-8 object-contain rounded bg-white dark:bg-zinc-900 border border-gray-100 dark:border-zinc-800"}):(0,a.jsx)("div",{className:"w-8 h-8 rounded admin-bg-tertiary flex items-center justify-center",children:(0,a.jsx)(B.Z,{className:"h-4 w-4 admin-text-muted"})}),(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("p",{className:"text-sm font-medium admin-text-primary truncate",children:t.mpn}),(0,a.jsxs)("p",{className:"text-xs admin-text-muted truncate",children:[t.family||"Connector"," \xb7 Qty: ",t.quantity,t.pinCount&&" \xb7 ".concat(t.pinCount,"-pin")]})]})]}),(0,a.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s&&(0,a.jsx)("span",{className:"w-2 h-2 bg-mp-positive rounded-full",title:"Has pinout images"}),o&&(0,a.jsx)("span",{className:"w-2 h-2 bg-mp-blue rounded-full",title:"Has datasheet"}),n?(0,a.jsx)(Z.Z,{className:"h-4 w-4 admin-text-muted"}):(0,a.jsx)(H.Z,{className:"h-4 w-4 admin-text-muted"})]})]}),n&&(0,a.jsxs)("div",{className:"px-3 pb-3 border-t border-gray-100 dark:border-zinc-800 pt-2",children:[(0,a.jsx)("p",{className:"text-xs admin-text-secondary mb-2 line-clamp-2",children:t.description}),!d&&(0,a.jsx)("p",{className:"text-xs admin-text-muted italic",children:"No images or datasheets available for this connector."}),l&&(0,a.jsx)("div",{className:"mb-2",children:(0,a.jsx)("button",{onClick:()=>i(t.imageUrl,"".concat(t.mpn," - Component Image")),className:"block w-full",children:(0,a.jsx)("img",{src:t.imageUrl,alt:t.mpn,className:"w-full h-32 object-contain bg-white dark:bg-zinc-900 rounded border admin-border dark:border-zinc-700 hover:border-mp-blue/40 dark:hover:border-mp-blue/50 transition-colors cursor-pointer"})})}),s&&(0,a.jsxs)("div",{className:"mb-2",children:[(0,a.jsxs)("p",{className:"text-xs font-medium admin-text-primary mb-1 flex items-center gap-1",children:[(0,a.jsx)(W.Z,{className:"h-3.5 w-3.5"}),"Pinout Diagrams (",t.pinoutImageUrls.length,")"]}),(0,a.jsx)("div",{className:"grid grid-cols-2 gap-1",children:t.pinoutImageUrls.map((e,n)=>(0,a.jsx)("button",{onClick:()=>i(e,"".concat(t.mpn," - Pinout ").concat(n+1)),className:"block",children:(0,a.jsx)("img",{src:e,alt:"Pinout ".concat(n+1),className:"w-full h-20 object-contain bg-white dark:bg-zinc-900 rounded border admin-border dark:border-zinc-700 hover:border-mp-blue/40 dark:hover:border-mp-blue/50 transition-colors cursor-pointer"})},n))})]}),o&&(0,a.jsxs)("a",{href:t.datasheetUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-2 py-1.5 text-xs bg-mp-blue/10 dark:bg-mp-blue-2/15 text-mp-blue dark:text-mp-blue-2 roun
1ded hover:bg-mp-blue/10 dark:hover:bg-mp-blue-2/15 transition-colors",children:[(0,a.jsx)(Q.Z,{className:"h-3.5 w-3.5"}),"View Datasheet",(0,a.jsx)(F.Z,{className:"h-3 w-3"})]})]})]})}function K(e){let{imageUrl:t,label:n,onClose:r}=e;return(0,a.jsx)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black bg-opacity-75 p-4",onClick:r,children:(0,a.jsxs)("div",{className:"relative max-w-4xl max-h-[90vh] admin-bg-secondary rounded-[4px] overflow-hidden",onClick:e=>e.stopPropagation(),children:[(0,a.jsxs)("div",{className:"absolute top-0 left-0 right-0 flex items-center justify-between p-3 z-10",children:[(0,a.jsx)("span",{className:"text-white text-sm font-medium truncate max-w-md",children:n}),(0,a.jsx)("button",{onClick:r,className:"text-white hover:text-gray-300 p-1",children:(0,a.jsx)(J.Z,{className:"h-6 w-6"})})]}),(0,a.jsx)("img",{src:t,alt:n,className:"max-w-full max-h-[85vh] object-contain bg-white dark:bg-zinc-900"}),(0,a.jsx)("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-center gap-4 p-3",children:(0,a.jsxs)("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-white text-sm hover:underline flex items-center gap-1",children:[(0,a.jsx)(F.Z,{className:"h-4 w-4"}),"Open full size"]})})]})})}var Y=n(44879),$=n(41556),X=n(1345);let ee={all:"All",wire:"Wire",connector_system:"Connector",terminal:"Terminal",other:"Other"},et={wire:"bg-mp-warning/10 dark:bg-mp-warning/15 text-mp-warning dark:text-mp-warning",connector_system:"bg-mp-blue/10 dark:bg-mp-blue-2/15 text-mp-blue dark:text-mp-blue-2",terminal:"bg-mp-blue/10 dark:bg-mp-blue-2/15 text-mp-blue dark:text-mp-blue-2"},en={wire:"Wire",connector_system:"Conn",terminal:"Term"};function ea(e){let{buildOrderId:t,onCopyToClipboard:n}=e,[i,s]=(0,r.useState)([]),[o,l]=(0,r.useState)(!0),[d,c]=(0,r.useState)(null),[m,u]=(0,r.useState)(""),[x,h]=(0,r.useState)("all"),[f,g]=(0,r.useState)(null),b=(0,r.useCallback)(async()=>{try{l(!0),c(null);let e=await fetch("/api/admin/work-instructions-review/bom-parts?buildOrderId=".concat(t));if(!e.ok){let t=await e.json();throw Error(t.error||"Failed to fetch parts")}let n=await e.json();s(n.parts)}catch(e){p.k.error("Error fetching BOM parts",{buildOrderId:t,error:e instanceof Error?e.message:String(e)}),c(e instanceof Error?e.message:"Failed to load parts")}finally{l(!1)}},[t]);(0,r.useEffect)(()=>{b()},[b]),(0,r.useEffect)(()=>{if(!f)return;let e=setTimeout(()=>g(null),2e3);return()=>clearTimeout(e)},[f]);let y=(0,r.useMemo)(()=>i.filter(e=>{if("all"!==x){if("other"===x){if(["wire","connector_system","terminal"].includes(e.itemType))return!1}else if(e.itemType!==x)return!1}if(m){var t,n,a;let r=m.toLowerCase(),i=null===(t=e.partNumber)||void 0===t?void 0:t.toLowerCase().includes(r),s=null===(n=e.mpn)||void 0===n?void 0:n.toLowerCase().includes(r),o=null===(a=e.description)||void 0===a?void 0:a.toLowerCase().includes(r);if(!i&&!s&&!o)return!1}return!0}),[i,x,m]),v=(0,r.useMemo)(()=>{let e={all:i.length,wire:0,connector_system:0,terminal:0,other:0};for(let t of i)"wire"===t.itemType?e.wire++:"connector_system"===t.itemType?e.connector_system++:"terminal"===t.itemType?e.terminal++:e.other++;return e},[i]),j=(0,r.useCallback)(e=>{let t=e.mpn||e.partNumber||e.description,a="[PART: ".concat(t).concat(e.description&&t!==e.description?" - ".concat(e.description):"","]");navigator.clipboard.writeText(a),g(e.id),n&&n(a)},[n]);return o?(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary mb-3 flex items-center gap-2",children:[(0,a.jsx)(Y.Z,{className:"h-4 w-4"}),"BOM Parts"]}),(0,a.jsxs)("div",{className:"flex items-center justify-center py-4",children:[(0,a.jsx)("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-mp-orange"}),(0,a.jsx)("span",{className:"ml-2 text-sm admin-text-muted",children:"Loading..."})]})]}):d?(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary mb-3 flex items-center gap-2",children:[(0,a.jsx)(Y.Z,{className:"h-4 w-4"}),"BOM Parts"]}),(0,a.jsx)("div",{className:"text-sm text-mp-danger py-2",children:d}),(0,a.jsx)("button",{onClick:b,className:"text-sm text-mp-blue dark:text-mp-blue-2 hover:text-mp-blue dark:hover:text-mp-blue-2 hover:underline",children:"Try again"})]}):0===i.length?(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary mb-3 flex items-center gap-2",children:[(0,a.jsx)(Y.Z,{className:"h-4 w-4"}),"BOM Parts"]}),(0,a.jsx)("div",{className:"text-sm admin-text-muted py-2",children:"No parts found in the BOM."})]}):(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsxs)("h3",{className:"text-sm font-semibold admin-text-primary mb-3 flex items-center gap-2",children:[(0,a.jsx)(Y.Z,{className:"h-4 w-4"}),"BOM Parts (",i.length,")"]}),(0,a.jsxs)("div",{className:"mb-3 relative",children:[(0,a.jsx)($.Z,{className:"h-4 w-4 absolute left-2.5 top-1/2 -translate-y-1/2 admin-text-muted"}),(0,a.jsx)("input",{type:"text",value:m,onChange:e=>u(e.target.value),placeholder:"Search parts...","aria-label":"Search parts by number, MPN, or description",role:"searchbox",className:"w-full pl-8 pr-3 py-1.5 text-sm border admin-border rounded focus:ring-1 focus:ring-mp-orange focus:border-mp-orange"})]}),(0,a.jsx)("div",{className:"flex flex-wrap gap-1 mb-3",role:"tablist","aria-label":"Filter parts by type",children:["all","wire","connector_system","terminal","other"].map(e=>(0,a.jsxs)("button",{onClick:()=>h(e),role:"tab","aria-selected":x===e,"aria-label":"Filter by ".concat(ee[e]),className:"px-2 py-1 text-xs rounded ".concat(x===e?"bg-mp-orange text-white":"admin-bg-tertiary admin-text-secondary hover:admin-text-primary"),children:[ee[e]," (",v[e],")"]},e))}),(0,a.jsx)("div",{className:"space-y-1.5 max-h-[calc(100vh-400px)] overflow-y-auto",children:0===y.length?(0,a.jsx)("p",{className:"text-xs admin-text-muted text-center py-4",children:"No parts match your search."}):y.map(e=>(0,a.jsx)(er,{part:e,onCopy:()=>j(e),isCopied:f===e.id},e.id))}),(0,a.jsxs)("div",{className:"mt-3 p-2 bg-mp-blue/10 dark:bg-mp-blue-2/15 border border-mp-blue/40 rounded text-xs text-mp-blue dark:text-mp-blue-2",children:[(0,a.jsx)("strong",{children:"Tip:"})," Click the copy icon to insert a part reference into your instructions."]})]})}let er=(0,r.memo)(function(e){let{part:t,onCopy:n,isCopied:r}=e,i=t.mpn||t.partNumber||"â",s=t.description&&t.description!==i,o=et[t.itemType]||"admin-bg-tertiary admin-text-secondary dark:text-zinc-300",l=en[t.itemType]||t.itemType;return(0,a.jsxs)("div",{className:"flex items-start gap-2 p-2 border admin-border rounded admin-bg-secondary hover:admin-bg-tertiary transition-colors group",children:[(0,a.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,a.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap",children:[(0,a.jsx)("span",{className:"text-xs px-1.5 py-0.5 rounded ".concat(o),children:l}),(0,a.jsx)("span",{className:"text-xs font-medium admin-text-primary truncate",children:i})]}),s&&(0,a.jsx)("p",{className:"text-xs admin-text-muted truncate mt-0.5",title:t.description,children:t.description}),(0,a.jsx)("p",{className:"text-xs admin-text-muted mt-0.5",children:t.lengthInches?"Length: ".concat(t.lengthInches,'"'):"Qty: ".concat(t.quantity)})]}),(0,a.jsx)("button",{onClick:n,"aria-label":r?"Copied to clipboard":"Copy ".concat(i," reference"),className:"flex-shrink-0 p-2.5 min-h-[44px] min-w-[44px] flex items-center justify-center rounded transition-colors ".concat(r?"text-mp-positive dark:text-mp-positive bg-mp-positive/10 dark:bg-mp-positive/15":"admin-text-muted hover:text-mp-orange hover:bg-mp-orange/10 dark:hover:bg-mp-orange/15"),children:r?(0,a.jsx)(R.Z,{className:"h-4 w-4"}):(0,a.jsx)(X.Z,{className:"h-4 w-4"})})]})});var ei=n(79785),es=n(85497),eo=n(9105),el=n(38796),ed=n(42548),ec=n(66743);function em(e){let{buildOrderId:t,salesOrderNumber:n,orderSource:i}=e,{showError:s,showWarning:o}=(0,c.pm)(),d=(0,l.GF)(),[m,u]=(0,r.useState)([]),[x,h]=(0,r.useState)([]),[g,b]=(0,r.useState)([]),[y,v]=(0,r.useState)(null),[j,N]=(0,r.useState)(!0),[w,k]=(0,r.useState)(!1),S="cart_
1checkout"===i,C=S&&n?"/configuratorV2?orderNumber=".concat(n):null,I=(0,f.lS)({buildOrderId:t,configV2ProjectId:y}),T=(e,t)=>{let n=null==d?void 0:d.docs.find(n=>n.id===e||n.url===t);if(d&&n){d.openRefs(n.id);return}window.open(t,"_blank","noopener,noreferrer")},E=(0,r.useCallback)(async()=>{k(!0);try{var e;let a=await fetch("/api/admin/build-orders/".concat(t,"/cut-sheet"));if(!a.ok){s("Cut Sheet Load Failed","Failed to load cut sheet data.");return}let r=await a.json();if(!(null===(e=r.cutSheetData)||void 0===e?void 0:e.length)){o("Cut Sheet Unavailable","No cut sheet data on this build order. Regenerate via the conversion wizard.");return}(0,ec.c)(r.cutSheetData,n||"N/A")}catch(e){p.k.error("Error printing cut sheet",{error:e instanceof Error?e.message:String(e)}),s("Cut Sheet Print Failed","Failed to print cut sheet.")}finally{k(!1)}},[t,n,s,o]);if((0,r.useEffect)(()=>{let e=!1;return async function(){try{N(!0);let n=await fetch("/api/admin/work-instructions-review/attachments?buildOrderId=".concat(t));if(!n.ok)return;let a=await n.json();if(e)return;u(a.designFiles||[]),v((0,f.rI)(a)),h(a.attachments||[]),b(a.customerNotes||[])}catch(e){p.k.error("Error fetching files",{error:e instanceof Error?e.message:String(e)})}finally{e||N(!1)}}(),()=>{e=!0}},[t]),j)return(0,a.jsx)("div",{className:"p-4",children:(0,a.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,a.jsx)("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-mp-orange"}),(0,a.jsx)("span",{className:"ml-2 text-sm admin-text-muted",children:"Loading..."})]})});let M=!!(C||S),O=m.length>0||M,A=new Set(m.map(e=>e.url)),D=x.filter(e=>!A.has(e.fileUrl)),R=D.length>0||g.length>0,P=null!==I;if(!O&&!R&&!P)return(0,a.jsx)("div",{className:"p-4",children:(0,a.jsxs)("div",{className:"text-center py-8",children:[(0,a.jsx)(ei.Z,{className:"h-8 w-8 admin-text-muted mx-auto mb-2"}),(0,a.jsx)("p",{className:"text-sm admin-text-muted",children:"No files found for this build order."})]})});let L="border-t admin-border pt-4";return(0,a.jsxs)("div",{className:"p-4 space-y-4",children:[O&&(0,a.jsxs)("div",{children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("h3",{className:"text-sm font-semibold admin-text-primary",children:"Design Files"}),m.length>0&&(0,a.jsx)("span",{className:"text-xs admin-text-muted",children:m.length})]}),M&&(0,a.jsxs)("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[C&&(0,a.jsxs)("a",{href:C,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-mp-orange bg-mp-orange/10 dark:bg-mp-orange/15 border border-mp-orange/30 dark:border-mp-orange/50 rounded hover:bg-mp-orange/10 dark:hover:bg-mp-orange/15 transition-colors",children:[(0,a.jsx)(es.Z,{className:"w-3.5 h-3.5"}),"View in Configurator"]}),S&&(0,a.jsxs)("button",{type:"button",onClick:E,disabled:w,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-mp-orange bg-mp-orange/10 dark:bg-mp-orange/15 border border-mp-orange/30 dark:border-mp-orange/50 rounded hover:bg-mp-orange/10 dark:hover:bg-mp-orange/15 transition-colors disabled:opacity-50",children:[(0,a.jsx)(eo.Z,{className:"w-3.5 h-3.5"}),w?"Loading...":"Print Cut Sheet"]})]}),(0,a.jsxs)("div",{className:"mt-4 space-y-2",children:[m.map(e=>(0,a.jsxs)("div",{onClick:()=>T(e.id,e.url),className:"flex items-center justify-between p-3 admin-bg-tertiary border admin-border rounded-[4px] admin-bg-hover transition-colors cursor-pointer",children:[(0,a.jsxs)("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[(0,a.jsx)("div",{className:"p-2 admin-bg-tertiary rounded flex-shrink-0",children:(0,a.jsx)(el.Z,{className:"w-5 h-5 admin-text-secondary"})}),(0,a.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,a.jsx)("div",{className:"font-medium admin-text-primary text-sm truncate",children:e.name}),(0,a.jsx)("div",{className:"text-xs admin-text-muted",children:e.type})]})]}),(0,a.jsxs)("div",{className:"flex gap-2 ml-3 flex-shrink-0",children:[(0,a.jsxs)("button",{type:"button",onClick:t=>{t.stopPropagation(),T(e.id,e.url)},className:"inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-mp-blue dark:text-mp-blue-2 bg-mp-blue/10 dark:bg-mp-blue-2/15 border border-mp-blue/30 dark:border-mp-blue-2/40 rounded hover:bg-mp-blue/10 dark:hover:bg-mp-blue-2/15 transition-colors",children:[(0,a.jsx)(ed.Z,{className:"w-3 h-3"}),"View"]}
1),(0,a.jsxs)("a",{href:e.url,download:e.name,onClick:e=>e.stopPropagation(),className:"inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-mp-positive dark:text-mp-positive bg-mp-positive/10 dark:bg-mp-positive/15 border border-mp-positive/30 dark:border-mp-positive/50 rounded hover:bg-mp-positive/10 dark:hover:bg-mp-positive/15 transition-colors",children:[(0,a.jsx)(el.Z,{className:"w-3 h-3"}),"Download"]})]})]},e.id)),0===m.length&&C&&(0,a.jsx)("p",{className:"text-sm admin-text-muted",children:"No uploaded design files â view the design in the configurator above."})]})]}),R&&(0,a.jsxs)("div",{className:O?L:void 0,children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("h3",{className:"text-sm font-semibold admin-text-primary",children:"Customer Files"}),(0,a.jsx)("span",{className:"text-xs admin-text-muted",children:D.length+g.length})]}),(0,a.jsxs)("div",{className:"mt-4 space-y-2",children:[D.map(e=>(0,a.jsx)(ep,{attachment:e,onOpenRow:()=>T(e.id,e.fileUrl)},e.id)),g.map(e=>(0,a.jsx)(eu,{note:e},e.id))]})]}),P&&I&&(0,a.jsxs)("div",{className:O||R?L:void 0,children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("h3",{className:"text-sm font-semibold admin-text-primary",children:"Production Drawing"}),(0,a.jsx)("span",{className:"text-xs admin-text-muted",children:"1"})]}),(0,a.jsx)("div",{className:"mt-4 space-y-2",children:(0,a.jsxs)("div",{onClick:()=>T(I.id,I.url),className:"flex items-center justify-between p-3 admin-bg-tertiary border admin-border rounded-[4px] admin-bg-hover transition-colors cursor-pointer",children:[(0,a.jsxs)("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[(0,a.jsx)("div",{className:"p-2 admin-bg-tertiary rounded flex-shrink-0",children:(0,a.jsx)(Q.Z,{className:"w-5 h-5 admin-text-secondary"})}),(0,a.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,a.jsx)("div",{className:"font-medium admin-text-primary text-sm truncate",children:I.title}),(0,a.jsx)("div",{className:"text-xs admin-text-muted",children:"ConfigV2"})]})]}),(0,a.jsxs)("div",{className:"flex gap-2 ml-3 flex-shrink-0",children:[(0,a.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),T(I.id,I.url)},className:"inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-mp-blue dark:text-mp-blue-2 bg-mp-blue/10 dark:bg-mp-blue-2/15 border border-mp-blue/30 dark:border-mp-blue-2/40 rounded hover:bg-mp-blue/10 dark:hover:bg-mp-blue-2/15 transition-colors",children:[(0,a.jsx)(ed.Z,{className:"w-3 h-3"}),"View"]}),(0,a.jsxs)("a",{href:I.url,target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),className:"inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-mp-positive dark:text-mp-positive bg-mp-positive/10 dark:bg-mp-positive/15 border border-mp-positive/30 dark:border-mp-positive/50 rounded hover:bg-mp-positive/10 dark:hover:bg-mp-positive/15 transition-colors",children:[(0,a.jsx)(F.Z,{className:"w-3 h-3"}),"Open"]})]})]})})]})]})}function ep(e){var t;let{attachment:n,onOpenRow:r}=e;return(0,a.jsx)("div",{className:"border admin-border rounded-[4px] p-2 admin-bg-secondary hover:admin-bg-tertiary transition-colors cursor-pointer",onClick:r,children:(0,a.jsxs)("div",{className:"flex items-start gap-2",children:[(0,a.jsx)("div",{className:"flex-shrink-0 w-12 h-12 rounded overflow-hidden admin-bg-tertiary flex items-center justify-center",children:n.isImage?(0,a.jsx)("img",{src:n.fileUrl,alt:n.fileName,className:"w-full h-full object-cover"}):n.isPdf?(0,a.jsx)(Q.Z,{className:"h-6 w-6 text-mp-danger"}):(0,a.jsx)(Q.Z,{className:"h-6 w-6 admin-text-muted"})}),(0,a.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,a.jsx)("p",{className:"text-xs font-medium admin-text-primary truncate",title:n.fileName,children:n.fileName}),(0,a.jsx)("p",{className:"text-xs admin-text-muted",children:(t=n.fileSize)<1024?"".concat(t," B"):t<1048576?"".concat((t/1024).toFixed(1)," KB"):"".concat((t/1048576).toFixed(1)," MB")})]}),(0,a.jsx)("div",{className:"flex flex-col gap-1",children:(0,a.jsx)("a",{href:n.fileUrl,target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),className:"p-1 admin-text-muted hover:text-mp-orange",title:"Open in New Tab",children:(0,a.jsx)(F.Z,{className:"h-4 w-4"})})})]})})}function eu(e){let{note:t}=e,n="quote"===t.source?"Quote":"Line Item",r=(t.source,"bg-mp-blue/10 dark:bg-mp-blue-2/15 text-mp-blue dark:text-mp-blue-2");return(0,a.jsxs)("div",{className:"border admin-border rounded-[4px] p-3 admin-bg-secondary",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,a.jsx)("span",{className:"text-xs px-2 py-0.5 rounded font-medium ".concat(r),children:"Customer"}),(0,a.jsx)("span",{className:"text-xs px-2 py-0.5 rounded admin-bg-tertiary admin-text-secondary dark:text-zinc-300",children:n})]}),(0,a.jsx)("p",{className:"text-xs font-medium admin-text-primary mb-1",children:t.label}),(0,a.jsx)("p",{className:"text-sm admin-text-secondary whitespace-pre-wrap leading-relaxed",children:t.content})]})}var ex=n(16356),eh=n(77122),ef=n(99588),eg=n(57895);let eb="/api/admin/operations-handbook",ey={category:"admin-bg-secondary admin-text-secondary",to
1pic:"bg-mp-blue/10 text-mp-blue",rule:"bg-mp-orange/10 text-mp-orange"};function ev(e){return"category"===e?"Category":"topic"===e?"Topic":"Rule"}function ej(e,t){if(e&&"object"==typeof e&&"error"in e){let t=e.error;if("string"==typeof t&&t.trim())return t}return t}function eN(e,t){var n;return"".concat(e.title,"\n").concat(null!==(n=e.body)&&void 0!==n?n:"").toLowerCase().includes(t)}function ew(e){let{markdown:t}=e;return(0,a.jsx)("div",{className:"prose prose-sm max-w-none prose-headings:mt-2 prose-headings:mb-1 prose-p:my-1 prose-ul:my-1 prose-ol:my-1 prose-li:my-0 text-mp-ink-2 dark:text-zinc-200",children:(0,a.jsx)(ex.UG,{remarkPlugins:[eh.Z],components:eg.tF,children:t})})}function ek(e){let{buildOrderId:t}=e,n=(0,d.Y)(),{showError:i,showSuccess:s}=(0,c.pm)(),[o,l]=(0,r.useState)([]),[m,u]=(0,r.useState)(!0),[x,h]=(0,r.useState)(null),[f,g]=(0,r.useState)({}),[b,y]=(0,r.useState)(""),[v,j]=(0,r.useState)(null),[N,w]=(0,r.useState)(""),[k,S]=(0,r.useState)(""),[C,I]=(0,r.useState)(null),[T,E]=(0,r.useState)(""),[M,O]=(0,r.useState)(""),[A,F]=(0,r.useState)(""),[R,P]=(0,r.useState)(!1),L=(0,r.useCallback)(async()=>{try{h(null);let e=await fetch(eb);if(!e.ok){let t=await e.json().catch(()=>null);throw Error(ej(t,"Failed to fetch handbook"))}let t=await e.json();l(Array.isArray(t.tree)?t.tree:[])}catch(e){p.k.error("Error fetching operations handbook",{error:e instanceof Error?e.message:String(e)}),h(e instanceof Error?e.message:"Failed to load handbook")}finally{u(!1)}},[]);(0,r.useEffect)(()=>{L()},[L]);let _=(0,r.useMemo)(()=>(function e(t,n){if(!n)return t;let a=[];for(let r of t){let t=e(r.children,n);(eN(r,n)||t.length>0)&&a.push({...r,children:eN(r,n)?r.children:t})}return a})(o,b.trim().toLowerCase()),[o,b]),U=(0,r.useMemo)(()=>(function e(t){let n=0;for(let a of t)"rule"===a.kind&&(n+=1),n+=e(a.children);return n})(_),[_]),q=b.trim().length>0,B=e=>!!q||!1!==f[e],W=e=>{g(t=>({...t,[e]:!1===t[e]}))},Q=()=>{j(null),w(""),S("")},G=()=>{I(null),E(""),O(""),F("")},V=e=>{if(G(),j(e),w(""),S(""),e.parentId){let t=e.parentId;g(e=>({...e,[t]:!0}))}},K=e=>{var t;Q(),I(e.id),E(e.title),O(null!==(t=e.body)&&void 0!==t?t:""),F("")},Y=async e=>{if(e.preventDefault(),v&&N.trim()&&!R){P(!0);try{let e={kind:v.kind,title:N.trim()};v.parentId&&(e.parentId=v.parentId),"rule"===v.kind&&(e.body=k);let t=await fetch(eb,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(ej(e,"Failed to create entry"))}let n=v.parentId;Q(),await L(),n&&g(e=>({...e,[n]:!0})),s("Entry Created","".concat(ev(e.kind)," added to the handbook."))}catch(e){p.k.error("Error creating handbook entry",{error:e instanceof Error?e.message:String(e)}),i("Create Failed",e instanceof Error?e.message:"Failed to create entry")}finally{P(!1)}}},X=async e=>{if(T.trim()&&!R){P(!0);try{let t={title:T.trim()};"category"!==e.kind&&(t.body=M),A.trim()&&(t.changeSummary=A.trim());let n=await fetch("".concat(eb,"/").concat(e.id),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>null);throw Error(ej(e,"Failed to save entry"))}G(),await L(),s("Entry Saved","".concat(ev(e.kind)," updated."))}catch(e){p.k.error("Error saving handbook entry",{error:e instanceof Error?e.message:String(e)}),i("Save Failed",e instanceof Error?e.message:"Failed to save entry")}finally{P(!1)}}},ee=async e=>{let t="rule"!==e.kind;if(await n.confirm({title:"Delete ".concat(ev(e.kind),"?"),description:t?"This ".concat(e.kind," and all of its children will be removed."):"Delete this rule?",confirmText:"Delete",variant:"destructive"}))try{let t=await fetch("".concat(eb,"/").concat(e.id),{method:"DELETE"});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(ej(e,"Failed to delete entry"))}C===e.id&&G(),(null==v?void 0:v.parentId)===e.id&&Q(),await L(),s("Entry Deleted","".concat(ev(e.kind)," removed."))}catch(e){p.k.error("Error deleting handbook entry",{error:e instanceof Error?e.message:String(e)}),i("Delete Failed",e instanceof Error?e.message:"Failed to delete entry")}},et=e=>(0,a.jsxs)("form",{onSubmit:Y,className:"mb-2 p-3 border admin-border rounded-[4px] bg-mp-warning/10 dark:bg-mp-warning/15",children:[(0,a.jsx)("input",{value:N,onChange:e=>w(e.target.value),placeholder:"".concat(ev(e.kind)," Title"),className:"w-full text-sm border admin-border rounded px-2 py-1.5 focus:ring-mp-orange focus:border-mp-orange",autoFocus:!0}),"rule"===e.kind&&(0,a.jsx)("div",{className:"mt-2",children:(0,a.jsx)(eg.VG,{value:k,onChange:S,placeholder:"Write markdown...",rows:3})}),(0,a.jsxs)("div",{className:"flex justify-end gap-2 mt-2",children:[(0,a.jsx)("button",{type:"button",onClick:Q,className:"px-3 py-1.5 text-xs admin-text-secondary hover:admin-text-primary",children:"Cancel"}),(0,a.jsx)("button",{type:"submit",disabled:!N.trim()||R,className:"px-3 py-1.5 text-xs text-white rounded-[4px] disabled:opacity-50 bg-mp-orange hover:bg-mp-orange",children:R?"Adding...":"Add ".concat(ev(e.kind))})]})]}),en=e=>(0,a.jsxs)("div",{className:"mb-2 p-3 border admin-border rounded-[4px] bg-mp-warning/10 dark:bg-mp-warning/15",children:[(0,a.jsx)("input",{value:T,onChange:e=>E(e.target.value),placeholder:"Title",className:"w-full text-sm border admin-border rounded px-2 py-1.5 focus:ring-mp-orange focus:border-mp-orange",autoFocus:!0}),"category"!==e.kind&&(0,a.jsx)("div",{className:"mt-2",children:(0,a.jsx)(eg.VG,{value:M,onChange:O,placeholder:"Write markdown...",rows:"rule"===e.kind?6:3})}),(0,a.jsx)("input",{value:A,onChange:e=>F(e.target.value),placeholder:"Change Summary (Optional)",className:"w-full mt-2 text-sm border admin-border rounded px-2 py-1.5 focus:ring-mp-orange focus:border-mp-orange"}),(0,a.jsxs)("div",{className:"flex justify-end gap-2 mt-2",children:[(0,a.jsx)("button",{type:"button",onClick:G,disabled:R,className:"px-3 py-1.5 text-xs admin-text-secondary hover:admin-text-primary",children:"Cancel"}),(0,a.jsx)("button",{type:"button",onClick:()=>X(e),disabled:!T.trim()||R,className:"px-3 py-1.5 text-xs text-white rounded-[4px] disabled:opacity-50 bg-mp-orange hover:bg-mp-orange",children:R?"Saving...":"Save"})]})]}),ea=e=>{let t="category"===e.kind?"topic":"topic"===e.kind?"rule":null;return(0,a.jsxs)("div",{className:"flex items-center gap-0.5 opacity-100 lg:opacity-0 lg:group-hover:opacity-100 lg:focus-within:opacity-100",children:[t&&(0,a.jsx)("button",{type:"button",onClick:()=>V({kind:t,parentId:e.id}),className:"flex-shrink-0 px-1.5 py-0.5 text-[11px] font-medium text-mp-orange hover:underline",children:"topic"===t?"Add Topic":"Add Rule"}),(0,a.jsx)("button",{type:"button",onClick:()=>K(e),className:"flex-shrink-0 p-1 admin-text-muted hover:admin-text-primary","aria-label":"Edit ".concat(e.title),title:"Edit ".concat(ev(e.kind)),children:(0,a.jsx)(ef.Z,{className:"h-3.5 w-3.5"})}),(0,a.jsx)("button",{type:"button",onClick:()=>ee(e),className:"flex-shrink-0 text-mp-danger hover:text-mp-danger p-1",title:"Delete ".concat(ev(e.kind)),children:(0,a.jsx)(z.Z,{className:"h-3.5 w-3.5"})})]})},er=(e,t)=>{let n="rule"!==e.kind&&B(e.id),r=C===e.id,i=e.children.length,s=null!==v&&v.parentId===e.id&&"category"!==v.kind;if("rule"===e.kind){var o;return(0,a.jsxs)("article",{className:"ml-3 mb-2 rounded-[4px] border admin-border group ".concat(r?"bg-mp-warning/10 dark:bg-mp-warning/15":"admin-bg-secondary/40"),children:[(0,a.jsxs)("div",{className:"flex items-start gap-2 px-2.5 py-2",children:[(0,a.jsx)("span",{className:"mt-0.5 flex-shrink-0 text-[10px] font-medium px-1.5 py-0.5 rounded-[3px] ".concat(ey.rule),children:"Rule"}),(0,a.jsx)("div",{className:"min-w-0 flex-1",children:(0,a.jsx)("h4",{className:"text-sm font-medium admin-text-primary",children:e.title})}),ea(e)]}),r?(0,a.jsx)("div",{className:"px-2.5 pb-2",children:en(e)}):(0,a.jsx)("div",{className:"px-2.5 pb-2.5",children:(null===(o=e.body)||void 0===o?void 0:o.trim())?(0,a.jsx)(ew,{markdown:e.body}):(0,a.jsx)("p",{className:"text-xs admin-text-muted italic",children:"No Body"})})]},e.id)}return(0,a.jsxs)("div",{className:0===t?"pb-3 mb-3 border-b admin-border last:border-b-0 last:mb-0 last:pb-0":"mt-1",children:[(0,a.jsxs)("div",{className:"flex items-center gap-1 py-1.5 pr-1 rounded-[4px] group ".concat(r?"bg-mp-warning/10 dark:bg-mp-warning/15":"hover:admin-bg-hover"),style:{paddingLeft:0===t?4:12},children:[(0,a.jsx)("button",{type:"button",onClick:()=>W(e.id),className:"flex-shrink-0 p-0.5 admin-text-muted hover:admin-text-primary","aria-label":n?"Collapse ".concat(e.title):"Expand ".concat(e.title),disabled:q,children:n?(0,a.jsx)(Z.Z,{className:"h-4 w-4"}):(0,a.jsx)(H.Z,{className:"h-4 w-4"})}),(0,a.jsx)("span",{className:"flex-shrink-0 text-[10px] font-medium px-1.5 py-0.5 rounded-[3px] ".concat(ey[e.kind]),children:ev(e.kind)}),(0,a.jsx)("button",{type:"button",onClick:()=>W(e.id),className:"flex-1 min-w-0 text-left truncate ".concat("category"===e.kind?"text-sm font-semibold admin-text-primary":"text-sm font-medium admin-text-primary"),disabled:q,children:e.title}),(0,a.jsx)("span",{className:"flex-shrink-0 text-[10px] px-1.5 py-0.5 rounded-[3px] admin-bg-secondary admin-text-muted",children:i}),ea(e)]}),r&&en(e),s&&v&&et(v),n&&e.children.map(e=>er(e,t+1))]},e.id)};return(0,a.jsxs)("div",{className:"flex flex-col h-full min-h-0",children:[(0,a.jsxs)("div",{className:"shrink-0 border-b admin-border",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between px-3 py-2",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("h3",{className:"text-sm font-semibold admin-text-primary",children:"Operations Handbook"}),!m&&!x&&o.length>0&&(0,a.jsx)("p",{className:"text-[11px] admin-text-muted",children:q?"".concat(U," ").concat(1===U?"Rule":"Rules"," Match"):"".concat(U," ").concat(1===U?"Rule":"Rules")})]}),(null==v?void 0:v.kind)!=="category"&&(0,a.jsxs)("button",{type:"button",onClick:()=>V({kind:"category",parentId:null}),className:"px-2.5 py-1 text-xs font-medium text-white bg-mp-orange rounded-[4px] flex items-center gap-1 hover:bg-mp-orange",children:[(0,a.jsx)(D.Z,{className:"h-3.5 w-3.5"}),"New Category"]})]}),o.length>0&&(0,a.jsxs)("div",{className:"flex items-center gap-2 px-3 pb-2",children:[(0,a.jsxs)("div",{className:"relative flex-1 min-w-0",children:[(0,a.jsx)($.Z,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 admin-text-muted"}),(0,a.jsx)("input",{type:"text",role:"searchbox","aria-label":"Filter handbook",value:b,onChange:e=>y(e.target.value),placeholder:"Filter titles and bodies",className:"w-full rounded-[4px] border admin-border bg-transparent pl-7 pr-7 py-1.5 text-sm admin-text-primary placeholder:admin-text-muted focus:ring-mp-orange focus:border-mp-orange"}),b&&(0,a.jsx)("button",{type:"button",onClick:()=>y(""),className:"absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 admin-text-muted hover:admin-text-primary","aria-label":"Clear filter",children:(0,a.jsx)(J.Z,{className:"h-3.5 w-3.5"})})]}),(0,a.jsx)("button",{type:"button",onClick:()=>g({}),disabled:q,className:"flex-shrink-0 text-[11px] font-medium admin-text-secondary hover:admin-text-primary disabled:opacity-40",children:"Expand All"}),(0,a.jsx)("button",{type:"button",onClick:()=>g(function(e,t){let n={},a=e=>
1{"rule"!==e.kind&&(n[e.id]=t),e.children.forEach(a)};return e.forEach(a),n}(o,!1)),disabled:q,className:"flex-shrink-0 text-[11px] font-medium admin-text-secondary hover:admin-text-primary disabled:opacity-40",children:"Collapse All"})]})]}),(0,a.jsxs)("div",{className:"flex-1 min-h-0 overflow-y-auto p-3",children:[(null==v?void 0:v.kind)==="category"&&et(v),m?(0,a.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,a.jsx)("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-mp-orange"}),(0,a.jsx)("span",{className:"ml-2 text-sm admin-text-muted",children:"Loading..."})]}):x?(0,a.jsx)("div",{className:"p-3 bg-mp-danger/10 dark:bg-mp-danger/15 border border-mp-danger/30 dark:border-mp-danger/50 rounded-[4px] text-sm text-mp-danger",children:x}):0===o.length&&(null==v?void 0:v.kind)!=="category"?(0,a.jsx)("div",{className:"text-sm admin-text-muted py-8 text-center",children:"No Handbook Entries Yet"}):0===_.length?(0,a.jsx)("div",{className:"text-sm admin-text-muted py-8 text-center",children:"No Entries Match"}):(0,a.jsx)("div",{children:_.map(e=>er(e,0))})]})]})}var eS=n(22539),eC=n(78027);function eI(e){let{buildOrderId:t,buildOrderName:n}=e,[i,s]=(0,r.useState)("cut-length"),[o,l]=(0,r.useState)([]),[d,c]=(0,r.useState)({}),[m,u]=(0,r.useState)(!0),[x,h]=(0,r.useState)(null);return(0,r.useEffect)(()=>{(async function(){try{let e=await fetch("/api/admin/wire-cutting-params/all");if(!e.ok)throw Error("Failed to fetch cutting parameters");let t=await e.json();l(t.wireCuttingConstants||[]),c(t.spliceParamsByGauge||{})}catch(e){p.k.error("Error fetching wire cutting constants",{error:e instanceof Error?e.message:String(e)}),h(e instanceof Error?e.message:"Failed to load")}finally{u(!1)}})()},[]),(0,a.jsxs)("div",{className:"p-3 space-y-3",children:[(0,a.jsxs)("div",{className:"grid grid-cols-2 rounded-[4px] border admin-border bg-white dark:bg-gray-900 p-1",children:[(0,a.jsx)("button",{type:"button",onClick:()=>s("cut-length"),className:"rounded-[2px] px-3 py-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-mp-orange ".concat("cut-length"===i?"bg-mp-orange text-white":"admin-text-secondary hover:admin-text-primary"),children:"Cut Length"}),(0,a.jsx)("button",{type:"button",onClick:()=>s("lot-sampling"),className:"rounded-[2px] px-3 py-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-mp-orange ".concat("lot-sampling"===i?"bg-mp-orange text-white":"admin-text-secondary hover:admin-text-primary"),children:"Lot Sampling"})]}),"lot-sampling"===i?(0,a.jsx)(eC.LotAcceptanceSamplingCalculator,{}):m?(0,a.jsx)("div",{className:"p-4 flex items-center justify-center",children:(0,a.jsx)("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-mp-orange"})}):x?(0,a.jsx)("div",{className:"p-3 bg-mp-danger/10 dark:bg-mp-danger/15 border border-mp-danger/30 dark:border-mp-danger/50 rounded-[4px] text-sm text-mp-danger dark:text-mp-danger",children:x}):(0,a.jsx)(eS.CutLengthCalculator,{wireCuttingConstants:o,spliceParamsByGauge:d,buildOrderId:t,buildOrderName:n})]})}var eT=n(31847);let eE="w-full rounded-[2px] border admin-border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-mp-blue";function eM(e){e&&(e.style.height="auto",e.style.height="".concat(e.scrollHeight,"px"))}function eO(e){let{buildOrderId:t,disabled:n=!1,refreshKey:i=0,onOpenIssuesChange:s,onAssumptionsChange:o}=e,{showError:l}=(0,c.pm)(),[d,m]=(0,r.useState)([]),[u,x]=(0,r.useState)([]),h=(0,r.useCallback)((e,t)=>{m(e),x(t),null==o||o(e.length),null==s||s(t.filter(e=>!e.resolved).length)},[o,s]);(0,r.useEffect)(()=>{let e=!1;return(async()=>{try{var n,a;let r=await fetch("/api/admin/build-orders/".concat(t,"/ai-review"));if(!r.ok)return;let i=await r.json();if(e)return;h(null!==(n=i.aiAssumptions)&&void 0!==n?n:[],null!==(a=i.aiIssues)&&void 0!==a?a:[])}catch(e){p.k.error("Failed to load WI AI review",{buildOrderId:t,error:e instanceof Error?e.message:String(e)})}})(),()=>{e=!0}},[h,t,i]);let f=async(e,n)=>{h(e,n);try{let a=await fetch("/api/admin/build-orders/".concat(t,"/ai-review"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({aiAssumptions:e,aiIssues:n})});a.ok||l("Could not save AI review",String(a.status))}catch(e){l("Could not save AI review",e instanceof Error?e.message:"Network error")}},g=(e,t)=>{f(d.map(n=>n.id===e?{...n,...t}:n),u)},b=(e,t)=>{f(d,u.map(n=>n.id===e?{...n,...t}:n))};return(0,a.jsxs)("div",{children:[(0,a.jsxs)("section",{id:"wi-assumptions",className:"border-b admin-border px-4 py-3",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(eT.Z,{className:"h-5 w-5 shrink-0 text-mp-warning"}),(0,a.jsx)("h3",{className:"text-sm font-semibold admin-text-primary",children:"Assumptions"})]}),(0,a.jsxs)("button",{type:"button",disabled:n,onClick:()=>void f([...d,{id:crypto.randomUUID(),text:"",visibility:"internal"}
1],u),className:"inline-flex shrink-0 items-center gap-1 rounded-[2px] border admin-border px-2.5 py-1 text-sm font-medium admin-text-primary hover:admin-bg-secondary disabled:cursor-not-allowed disabled:opacity-50",children:[(0,a.jsx)(D.Z,{className:"h-4 w-4"}),"Add Assumption"]})]}),0===d.length?(0,a.jsx)("p",{className:"mt-2 text-sm admin-text-muted",children:"No assumptions recorded."}):(0,a.jsx)("div",{className:"mt-3 space-y-3",children:d.map((e,t)=>(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)("textarea",{ref:e=>eM(e),value:e.text,disabled:n,rows:3,onChange:t=>{eM(t.currentTarget),g(e.id,{text:t.target.value})},className:"".concat(eE," min-h-[4.5rem] resize-y overflow-hidden"),placeholder:"Assumption ".concat(t+1)}),(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsxs)("select",{"aria-label":"Visibility for assumption ".concat(t+1),value:e.visibility,disabled:n,onChange:t=>g(e.id,{visibility:"external"===t.target.value?"external":"internal"}),className:"".concat(eE," w-36"),children:[(0,a.jsx)("option",{value:"internal",children:"Internal"}),(0,a.jsx)("option",{value:"external",children:"External"})]}),(0,a.jsx)("button",{type:"button",disabled:n,onClick:()=>void f(d.filter(t=>t.id!==e.id),u),className:"rounded-[2px] p-2 text-gray-400 hover:text-mp-danger disabled:opacity-50","aria-label":"Delete assumption ".concat(t+1),children:(0,a.jsx)(z.Z,{className:"h-4 w-4"})})]})]},e.id))})]}),(0,a.jsxs)("section",{id:"wi-issues",className:"px-4 py-3",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,a.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,a.jsx)(P.Z,{className:"h-5 w-5 shrink-0 text-mp-danger"}),(0,a.jsx)("h3",{className:"text-sm font-semibold admin-text-primary",children:"Issues To Be Resolved"})]}),(0,a.jsxs)("button",{type:"button",disabled:n,onClick:()=>void f(d,[...u,{id:crypto.randomUUID(),text:"",resolved:!1}]),className:"inline-flex shrink-0 items-center gap-1 rounded-[2px] border admin-border px-2.5 py-1 text-sm font-medium admin-text-primary hover:admin-bg-secondary disabled:cursor-not-allowed disabled:opacity-50",children:[(0,a.jsx)(D.Z,{className:"h-4 w-4"}),"Add Issue"]})]}),0===u.length?(0,a.jsx)("p",{className:"mt-2 text-sm admin-text-muted",children:"No unresolved issues."}):(0,a.jsx)("div",{className:"mt-3 space-y-3",children:u.map((e,t)=>(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)("textarea",{ref:e=>eM(e),value:e.text,disabled:n,rows:3,onChange:t=>{eM(t.currentTarget),b(e.id,{text:t.target.value})},className:"".concat(eE," min-h-[4.5rem] resize-y overflow-hidden ").concat(e.resolved?"line-through opacity-60":""),placeholder:"Issue ".concat(t+1)}),(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsxs)("label",{className:"inline-flex items-center gap-2 text-sm admin-text-secondary",children:[(0,a.jsx)("input",{type:"checkbox",checked:e.resolved,disabled:n,onChange:t=>b(e.id,{resolved:t.target.checked}),className:"h-4 w-4 rounded border-gray-300 text-mp-blue focus:ring-mp-blue dark:border-zinc-600"}),"Resolved"]}),(0,a.jsx)("button",{type:"button",disabled:n,onClick:()=>void f(d,u.filter(t=>t.id!==e.id)),className:"rounded-[2px] p-2 text-gray-400 hover:text-mp-danger disabled:opacity-50","aria-label":"Delete issue ".concat(t+1),children:(0,a.jsx)(z.Z,{className:"h-4 w-4"})})]})]},e.id))})]})]})}var eA=n(53916);let eF=["Quality Control","Close Out"];function eD(e){let{workSteps:t,value:n,onChange:i,placeholder:s="Search operations...",disabled:o=!1,autoFocus:l=!1}=e,[d,c]=(0,r.useState)(""),[m,p]=(0,r.useState)(!1),[u,x]=(0,r.useState)(0),h=(0,r.useRef)(null),f=(0,r.useRef)(null),g=(0,r.useRef)(null),b=(0,r.useMemo)(()=>new eA.Z(t,{keys:["name"],threshold:.3,ignoreLocation:!0}),[t]),{regular:y,pinned:v,all:j}=(0,r.useMemo)(()=>{let e=new Set(eF.map(e=>e.toLowerCase())),n=d.trim()?b.search(d.trim()).map(e=>e.item):[...t],a=[],r=[];for(let t of n)e.has(t.name.toLowerCase())?r.push(t):a.push(t);return a.sort((e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:"base"}
1)),r.sort((e,t)=>eF.findIndex(t=>t.toLowerCase()===e.name.toLowerCase())-eF.findIndex(e=>e.toLowerCase()===t.name.toLowerCase())),{regular:a,pinned:r,all:[...a,...r]}},[t,d,b]);(0,r.useEffect)(()=>{x(0)},[j.length]),(0,r.useEffect)(()=>{if(!m||!g.current)return;let e=g.current.children[u];null==e||e.scrollIntoView({block:"nearest"})},[u,m]),(0,r.useEffect)(()=>{let e=e=>{h.current&&!h.current.contains(e.target)&&(p(!1),c(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let N=e=>{i(e),c(""),p(!1)};return(0,a.jsxs)("div",{ref:h,className:"relative",children:[(0,a.jsx)("input",{ref:f,type:"text",value:m?d:n||"",onChange:e=>{c(e.target.value),m||p(!0)},onFocus:()=>{p(!0),c("")},onKeyDown:e=>{if("Escape"===e.key){var t;p(!1),c(""),null===(t=f.current)||void 0===t||t.blur()}else"ArrowDown"===e.key?(e.preventDefault(),x(e=>Math.min(e+1,j.length-1))):"ArrowUp"===e.key?(e.preventDefault(),x(e=>Math.max(e-1,0))):"Enter"===e.key&&m&&j[u]&&(e.preventDefault(),N(j[u].name))},placeholder:n||s,disabled:o,autoFocus:l,className:"w-full px-2 py-2 pr-8 border admin-border rounded text-sm focus:ring-mp-orange focus:border-mp-orange cursor-pointer focus:cursor-text"}),(0,a.jsx)(Z.Z,{className:"absolute right-2 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none transition-transform ".concat(m?"rotate-180":"")}),m&&(0,a.jsx)("div",{className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded border admin-border bg-white dark:bg-zinc-900",ref:g,children:0===j.length&&d.trim()?(0,a.jsx)("div",{className:"px-3 py-2 text-sm admin-text-muted",children:"No matching operations"}):0===j.length?(0,a.jsx)("div",{className:"px-3 py-2 text-sm admin-text-muted",children:"No work steps loaded"}):(0,a.jsxs)(a.Fragment,{children:[y.map((e,t)=>(0,a.jsx)("button",{type:"button",onClick:()=>N(e.name),className:"block w-full px-3 py-1.5 text-left text-sm transition-colors ".concat(t===u?"bg-mp-orange/10 dark:bg-mp-orange/15 text-mp-orange":"hover:admin-bg-tertiary admin-text-primary"," ").concat(e.name===n?"font-semibold":""),children:e.name},e.id)),v.length>0&&y.length>0&&(0,a.jsx)("div",{className:"border-t admin-border"}),v.map((e,t)=>(0,a.jsx)("button",{type:"button",onClick:()=>N(e.name),className:"block w-full px-3 py-1.5 text-left text-sm transition-colors ".concat(y.length+t===u?"bg-mp-orange/10 dark:bg-mp-orange/15 text-mp-orange":"hover:admin-bg-tertiary admin-text-muted"," ").concat(e.name===n?"font-semibold":""),children:e.name},e.id))]})})]})}function eR(e){let{zoomIn:t,zoomOut:n,fitView:i}=(0,s._K)(),[o,l]=(0,r.useState)(!1),[d,c]=(0,r.useState)(""),[m,p]=(0,r.useState)(!1),u=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!o)return;let e=e=>{u.current&&!u.current.contains(e.target)&&l(!1)};return window.addEventListener("mousedown",e),()=>window.removeEventListener("mousedown",e)},[o]);let x=async()=>{let t=d.trim();if(t&&!m){p(!0);try{await e.onAddOperation({operationName:t,after:e.selectedOpId?[e.selectedOpId]:[]}),c(""),l(!1)}finally{p(!1)}}},h="rounded-[2px] border admin-border admin-bg-secondary px-2.5 py-1.5 text-[12px] font-medium admin-text-primary hover:admin-bg-tertiary disabled:opacity-50";return(0,a.jsxs)("div",{className:"!absolute left-4 top-4 z-20 flex w-auto items-start gap-1.5",role:"toolbar","aria-label":"Routing tools",children:[(0,a.jsxs)("div",{className:"relative",ref:u,children:[(0,a.jsx)("button",{type:"button",className:h,disabled:e.locked,onClick:()=>l(e=>!e),"data-testid":"wi-add-operation",children:"+ Operation"}),o?(0,a.jsxs)("div",{className:"absolute left-0 top-full mt-1 w-[360px] rounded-[4px] border admin-border admin-bg-secondary p-3 shadow-xl",children:[(0,a.jsxs)("div",{className:"mb-1 text-[11px] font-semibold admin-text-muted",children:["New operation",e.selectedOpName?" \xb7 runs after ".concat(e.selectedOpName):" \xb7 added at the end"]}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("div",{className:"min-w-0 flex-1",children:(0,a.jsx)(eD,{workSteps:e.workSteps,value:d,onChange:c,placeholder:"Operation name",autoFocus:!0})}),(0,a.jsx)("button",{type:"button",className:h,disabled:!d.trim()||m,onClick:()=>void x(),"data-testid":"wi-add-operation-confirm",children:"Add"})]}),(0,a.jsxs)("div",{className:"mt-3 flex flex-col gap-1 border-t admin-border pt-2 text-[12.5px]",children:[(0,a.jsx)("button",{type:"button",className:"rounded-[2px] px-1.5 py-1 text-left hover:admin-bg-tertiary",onClick:()=>{l(!1),e.onPopulate()},children:"Populate from library or quoteâ¦"}),e.onCopyFromBo?(0,a.jsx)("button",{type:"button",className:"rounded-[2px] px-1.5 py-1 text-left hover:admin-bg-tertiary",onClick:()=>{var t;l(!1),null===(t=e.onCopyFromBo)||void 0===t||t.call(e)},children:"Copy from another build orderâ¦"}):null]})]}):null]}),(0,a.jsx)("button",{type:"button",className:h,onClick:e.onAutoLayout,"data-testid":"wi-auto-layout",children:"Auto-layout"}),(0,a.jsx)("button",{type:"button",className:h,onClick:()=>i({padding:.06,maxZoom:1}),title:"Fit to view",children:"Fit"}),(0,a.jsx)("button",{type:"button",className:"".concat(h," w-8 px-0 text-center"),"aria-label":"Zoom out",onClick:()=>n(),children:"â"}),(0,a.jsx)("button",{type:"button",className:"".concat(h," w-8 px-0 text-center"),"aria-label":"Zoom in",onClick:()=>t(),children:"+"})]})}let eP=new Set(["closeout","shipping"]);
1function eL(e,t,n){let a=new Map(e.map(e=>[e.id,e])),r=a.get(n.operationId),i=a.get(n.dependsOnOperationId);return r&&i?n.operationId===n.dependsOnOperationId?{code:"ROUTING_SELF",message:"".concat(r.operationName," cannot depend on itself."),operationIds:[r.id]}:"start_to_start"===n.dependencyType&&"qc"!==r.opCatalogType?{code:"ROUTING_SS_NOT_QC",message:"Only a QC operation can start with another; ".concat(r.operationName," must run after it."),operationIds:[r.id]}:i.opCatalogType&&eP.has(i.opCatalogType)?{code:"ROUTING_TERMINAL_SINK",message:"".concat(i.operationName," is the last step; nothing can run after it."),operationIds:[i.id]}:!function(e,t){var n,a;let r=new Map;for(let a of[...e,t])r.set(a.dependsOnOperationId,[...null!==(n=r.get(a.dependsOnOperationId))&&void 0!==n?n:[],a.operationId]);let i=new Set,s=[t.operationId];for(;s.length;){let e=s.pop();if(e===t.dependsOnOperationId)return!0;if(!i.has(e))for(let t of(i.add(e),null!==(a=r.get(e))&&void 0!==a?a:[]))s.push(t)}return!1}(t.filter(e=>M(e)!==M(n)),n)?null:{code:"ROUTING_CYCLE",message:"".concat(i.operationName," already waits on ").concat(r.operationName,"; this edge would loop."),operationIds:[i.id,r.id]}:{code:"ROUTING_UNKNOWN_OP",message:"That operation is not on this build order.",operationIds:[]}}function e_(e,t){let n=M(t);return[...e.filter(e=>M(e)!==n),{...t,implicit:!1}]}function ez(e,t){return e.filter(e=>M(e)!==t)}function eU(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"finish_to_start";return{operationId:t,dependsOnOperationId:e,dependencyType:n,impl
1icit:!1}}var eq=n(54281);n(36556);var eB=n(14520);let eZ={op:(0,r.memo)(function(e){let{data:t,selected:n}=e,r=T(t.opCatalogType);return(0,a.jsxs)("div",{"data-testid":"wi-op-node","aria-label":"Operation ".concat(t.sequenceNumber," ").concat(t.name),className:["group relative rounded-[4px] border bg-white px-2.5 py-1.5 text-left shadow-sm dark:bg-zinc-900",n?"border-mp-orange bg-[#FFF6E6] ring-[3px] ring-mp-orange/20 dark:bg-zinc-800":"admin-border",t.isNonManufacturing?"opacity-80":""].join(" "),style:{width:148,height:66,borderLeft:"3px solid ".concat(C[r])},children:[E.map((e,n)=>(0,a.jsx)(s.HH,{id:"in-".concat(n),type:"target",position:s.Ly.Left,isConnectable:2===n&&!t.locked,className:2===n?"wi-port":"wi-port-ghost",style:{top:e}},"in-".concat(n))),(0,a.jsx)(s.HH,{id:"ss-in",type:"target",position:s.Ly.Top,isConnectable:!t.locked,className:"wi-port wi-port-ss",style:{left:"50%"}}),(0,a.jsxs)("div",{className:"flex items-center justify-between text-[10.5px] admin-text-muted",children:[(0,a.jsx)("span",{className:"font-brandMono font-semibold",children:t.sequenceNumber}),(0,a.jsx)("span",{className:"tabular-nums",children:t.estimateLabel})]}),(0,a.jsx)("div",{className:"mt-0.5 line-clamp-2 text-[12px] font-medium leading-[1.25] admin-text-primary",children:t.name}),t.incompleteReason?(0,a.jsx)("span",{"data-testid":"wi-node-incomplete",title:t.incompleteReason,className:"absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-mp-warning text-[10px] font-bold text-white",children:"!"}):null,E.map((e,n)=>(0,a.jsx)(s.HH,{id:"out-".concat(n),type:"source",position:s.Ly.Right,isConnectable:2===n&&!t.locked,className:2===n?"wi-port":"wi-port-ghost",style:{top:e}},"out-".concat(n))),(0,a.jsx)(s.HH,{id:"ss-out",type:"source",position:s.Ly.Bottom,isConnectable:!t.locked,className:"wi-port wi-port-ss",style:{left:"50%"}})]})})};function eH(e,t){var n;let a=eW(e,t);return{id:e.id,sequenceNumber:e.sequenceNumber,operationName:e.operationName,opCatalogType:null!==(n=e.opCatalogType)&&void 0!==n?n:null,estimateMinutes:a}}function eW(e,t){var n,a,r,i,s;let o=Number(null!==(n=e.estimatedTime)&&void 0!==n?n:0),l=Number(null!==(a=e.estimatedSecsPerUnit)&&void 0!==a?a:0),d=Number(null!==(r=e.operationQuantity)&&void 0!==r?r:1)||1,c=Number(null!==(i=e.timeMultiplier)&&void 0!==i?i:1)||1,m=(null!==(s=e.quoteTimeApplication)&&void 0!==s?s:"per_unit").toLowerCase(),p="per_bo"===m||"per_batch"===m?1:"per_line_item"===m?d:d*(t||1);return Number.isFinite(o)&&o>0?o*c*p:Number.isFinite(l)&&l>0?l/60*c*p:0}function eQ(e){return e.map(e=>({operationId:e.operationId,dependsOnOperationId:e.dependsOnOperationId,dependencyType:e.dependencyType,implicit:e.implicit}))}function eJ(e){let{operations:t,edges:n,selectedOpId:i,locked:o,incompleteReasonByOpId:l,boQuantity:d}=e,{fitView:c}=(0,s._K)(),m=(0,r.useMemo)(()=>t.map(e=>eH(e,d)),[t,d]),p=(0,r.useMemo)(()=>eQ(n),[n]),u=(0,r.useMemo)(()=>"".concat(m.map(e=>e.id).sort().join(","),"|").concat(p.map(M).sort().join(",")),[m,p]),x=(0,r.useMemo)(()=>(function(e,t){let n=new Map(e.map(e=>[e.id,e])),a=t.filter(e=>n.has(e.operationId)&&n.has(e.dependsOnOperationId)&&e.operationId!==e.dependsOnOperationId),r=new Map;for(let e of a)"start_to_start"!==e.dependencyType||r.has(e.operationId)||r.set(e.operationId,e.dependsOnOperationId);let i=new(w()).graphlib.Graph;i.setDefaultEdgeLabel(()=>({})),i.setGraph({rankdir:"LR",nodesep:16,ranksep:30,marginx:10,marginy:10});let s=[...e].sort(A).filter(e=>!r.has(e.id));for(let e of s)i.setNode(e.id,{width:148,height:66});for(let e of a)"finish_to_start"===e.dependencyType&&(r.has(e.operationId)||r.has(e.dependsOnOperationId)||i.setEdge(e.dependsOnOperationId,e.operationId));w().layout(i);let o=new Map;for(let e of s){let t=i.node(e.id);t&&o.set(e.id,{x:t.x-74,y:t.y-33})}for(let{target:e,source:t}of[...r.entries()].map(e=>{let[t,n]=e;return{target:t,source:n}}).sort((e,t)=>A(n.get(e.target),n.get(t.target)))){let n=o.get(t);if(!n){o.set(e,{x:10,y:10+96*o.size});continue}let a=n.y+66+30;for(let[r,i]of(o.set(e,{x:n.x,y:a}),o))r!==e&&r!==t&&148>Math.abs(i.x-n.x)&&i.y>n.y&&i.y<a+66&&(i.y+=96)}let l=new Map,d=e=>{var t,n;return null!==(n=null===(t=o.get(e))||void 0===t?void 0:t.y)&&void 0!==n?n:0};for(let t of e){let e=a.filter(e=>"finish_to_start"===e.dependencyType&&e.dependsOnOperationId===t.id).sort((e,t)=>
1d(e.operationId)-d(t.operationId));O(e.length).forEach((t,n)=>{var a;let r=M(e[n]);l.set(r,{...null!==(a=l.get(r))&&void 0!==a?a:{targetHandle:"in-2"},sourceHandle:"out-".concat(t)})});let n=a.filter(e=>"finish_to_start"===e.dependencyType&&e.operationId===t.id).sort((e,t)=>d(e.dependsOnOperationId)-d(t.dependsOnOperationId));O(n.length).forEach((e,t)=>{var a;let r=M(n[t]);l.set(r,{...null!==(a=l.get(r))&&void 0!==a?a:{sourceHandle:"out-2"},targetHandle:"in-".concat(e)})})}for(let e of a)"start_to_start"===e.dependencyType&&l.set(M(e),{sourceHandle:"ss-out",targetHandle:"ss-in"});return{positions:o,handles:l}})(m,p),[m,p]),[h,f,b]=(0,s.Rr)([]),[y,v]=(0,r.useState)(null),j=(0,r.useRef)(!1),N=(0,r.useRef)(null),k=(0,r.useCallback)(e=>{var t,n;return{sequenceNumber:e.sequenceNumber,name:e.operationName,opCatalogType:null!==(t=e.opCatalogType)&&void 0!==t?t:null,estimateLabel:g(eW(e,d)),incompleteReason:null!==(n=l.get(e.id))&&void 0!==n?n:null,locked:o||!1===e.routable,isNonManufacturing:!1===e.routable||null!=e.opCatalogType&&["kitting","closeout","shipping","wi_authoring"].includes(e.opCatalogType)}},[d,l,o]);(0,r.useEffect)(()=>{let e=N.current!==u;N.current=u,f(n=>{let a=new Map(n.map(e=>[e.id,e]));return t.map(t=>{var n;let r=a.get(t.id),s=e||!r?null!==(n=x.positions.get(t.id))&&void 0!==n?n:{x:0,y:0}:r.position;return{id:t.id,type:"op",position:s,data:k(t),selected:t.id===i,draggable:!o}})})},[t,x,u,i,k,o,f]);let S=(0,r.useMemo)(()=>(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return e.map(e=>{var a;let r=M(e),i="start_to_start"===e.dependencyType,o=i?"#8b5cf6":"#A9AFA9",l=null!==(a=t.get(r))&&void 0!==a?a:i?{sourceHandle:"ss-out",targetHandle:"ss-in"}:{sourceHandle:"out-2",targetHandle:"in-2"};return{id:r,source:e.dependsOnOperationId,target:e.operationId,sourceHandle:l.sourceHandle,targetHandle:l.targetHandle,type:i?"straight":"default",selected:n===r,className:i?"wi-edge-ss":"wi-edge-fs",style:{stroke:o,strokeWidth:n===r?2.5:1.5,...i?{strokeDasharray:"4 3"}:{}},markerEnd:{type:s.QZ.ArrowClosed,width:9,height:9,color:o},data:{dependencyType:e.dependencyType,implicit:!0===e.implicit}}})})(p,x.handles,y),[p,x.handles,y]),C=(0,r.useCallback)((t,n)=>{v(null),e.onSelectOp(n.id)},[e]),I=(0,r.useCallback)(()=>{v(null),e.onSelectOp(null)},[e]),T=(0,r.useCallback)(t=>{if(R.current=!0,o||!t.source||!t.target)return;let n=j.current||"ss-out"===t.sourceHandle||"ss-in"===t.targetHandle,a=eU(t.source,t.target,n?"start_to_start":"finish_to_start"),r=eL(m,p,a);if(r){e.onEdgeError(r.message);return}e.onEdgesChange(e_(p,a))},[p,m,o,e]),E=(0,r.useRef)(null),F=(0,r.useMemo)(()=>new Set(t.filter(e=>!1!==e.routable).map(e=>e.id)),[t]),D=(0,r.useCallback)(e=>{var t;if(!e.source||!e.target||e.source===e.target)return!1;if(!F.has(e.source)||!F.has(e.target))return E.current="Generic, office, and shipping steps sit outside the routing and cannot be linked.",!1;let n="ss-out"===e.sourceHandle||"ss-in"===e.targetHandle,a=eL(m,p,eU(e.source,e.target,n?"start_to_start":"finish_to_start"));return E.current=null!==(t=null==a?void 0:a.message)&&void 0!==t?t:null,null===a},[p,m,F]),R=(0,r.useRef)(!1),P=(0,r.useCallback)(()=>{R.current=!1,E.current=null},[]),L=(0,r.useCallback)(()=>{!R.current&&E.current&&e.onEdgeError(E.current),E.current=null},[e]);return(0,r.useEffect)(()=>{let t=t=>{let n=t.target,a=n&&("INPUT"===n.tagName||"TEXTAREA"===n.tagName||n.isContentEditable);("s"===t.key||"S"===t.key)&&(j.current="keydown"===t.type),a||(("Delete"===t.key||"Backspace"===t.key)&&"keydown"===t.type&&(y&&!o?(t.preventDefault(),e.onEdgesChange(ez(p,y)),v(null)):i&&!o&&(t.preventDefault(),e.onRequestDeleteOp(i))),"Escape"===t.key&&"keydown"===t.type&&(v(null),e.onSelectOp(null)))};return window.addEventListener("keydown",t),window.addEventListener("keyup",t),()=>{window.removeEventListener("keydown",t),window.removeEventListener("keyup",t)}},[p,o,e,y,i]),(0,a.jsx)(s.x$,{className:"!absolute inset-0",nodes:h,edges:S,nodeTypes:eZ,onNodesChange:b,onNodeClick:C,onPaneClick:I,onEdgeClick:(e,t)=>v(t.id),onConnect:T,onConnectStart:P,onConnectEnd:L,isValidConnection:D,nodesConnectable:!o,nodesDraggable:!o,deleteKeyCode:null,defaultViewport:{x:24,y:24,zoom:1}
1,minZoom:.4,maxZoom:1.6,proOptions:{hideAttribution:!0},onInit:()=>{window.requestAnimationFrame(()=>c({padding:.06,maxZoom:1}))},children:(0,a.jsx)(eq.A,{variant:eq.T.Dots,gap:20,size:1,color:"#e5e7eb"})})}function eG(e){var t;let n=(0,r.useRef)(null),i=null!==(t=e.containerRef)&&void 0!==t?t:n;return(0,a.jsxs)("div",{ref:i,className:"relative h-full w-full overflow-hidden admin-bg-primary","data-testid":"wi-graph-canvas",children:[(0,a.jsx)(eJ,{...e}),e.overlays]})}var eV=n(29355),eK=n(87614),eY=n(54793),e$=n(89917);function eX(e){let{workSteps:t,value:n,onPick:r}=e;return(0,a.jsxs)("div",{className:"max-w-xs",children:[(0,a.jsx)("label",{className:"block text-xs font-medium admin-text-primary mb-1",children:"Name"}),0===t.length&&(0,a.jsx)("p",{className:"text-xs text-mp-warning dark:text-mp-warning mb-1",children:"Loading work steps..."}),(0,a.jsx)(eD,{workSteps:t,value:n,onChange:e=>{let n=t.find(t=>t.name===e);n&&r(e,n.id)},placeholder:"Search operations...",disabled:0===t.length})]})}function e0(e){let{value:t,onChange:n}=e;return(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{className:"block text-xs font-medium admin-text-primary mb-1",children:"Description"}),(0,a.jsx)("input",{type:"text",value:t,onChange:e=>n(e.target.value),className:"w-full px-3 py-2 border admin-border rounded text-sm focus:ring-mp-orange focus:border-mp-orange"})]})}function e1(e){var t,n,r,i,s,o,l,d,c;let{operation:m,formData:p,setFormData:u,workSteps:h,boQuantity:f}=e,y=h.find(e=>e.id===m.workStepId)||h.find(e=>e.name===p.operationName),v=!(d={catalogType:m.opCatalogType,selectedLevel:p.level,qualifiedOperatorMaxLevel:m.qualifiedOperatorMaxLevel}).catalogType||!d.selectedLevel||(null!==(c=d.qualifiedOperatorMaxLevel)&&void 0!==c?c:0)>=d.selectedLevel,j=null!==(t=m.qualifiedOperatorMaxLevel)&&void 0!==t?t:0,N=e=>{let t=null==y?void 0:y.timeStandard;if(!t)return 0;let n="simple"===e?t.simpleTime:"complex"===e?t.complexTime:t.mediumTime;return n&&n>0?n:0},w=(()=>{let e=N(p.complexity);return e>0?Math.round(e/60*100)/100:0})(),k=x({quoteEstimatedSeconds:m.quoteEstimatedSeconds,workStepTimeStandard:null!==(n=null==y?void 0:y.timeStandard)&&void 0!==n?n:null,complexity:p.complexity,defaultSecsPerUnit:null!==(i=null!==(r=m.estimatedSecsPerUnit)&&void 0!==r?r:m.defaultSecsPerUnit)&&void 0!==i?i:null,manualOverrideSeconds:p.manualOverride?Math.round(60*p.estimatedTime):null}),S=function(e,t){let n=(null!=e?e:"").toLowerCase();if(n.startsWith("per_")){let e=n.slice(4).replaceAll("_"," ");if("unit"===e||"batch"===e||"line item"===e||"bo"===e||"item"===e){let e=(null!=t?t:"").toLowerCase();return e.includes("crimp")||e.includes("pin")?"pin":e.includes("wire")?"wire":"unit"}return e}let a=(null!=t?t:"").toLowerCase();return a.includes("crimp")||a.includes("pin")?"pin":"unit"}(null==y?void 0:y.timeApplication,null!==(s=null==y?void 0:y.name)&&void 0!==s?s:p.operationName),C="".concat(S.endsWith("s")?S:"".concat(S,"s").replace(/\b\w/g,e=>e.toUpperCase())," / harness"),I="Standard / ".concat(S),T=null!==(l=null!==(o=m.quoteTimeApplication)&&void 0!==o?o:null==y?void 0:y.timeApplication)&&void 0!==l?l:null,E=(null!=T?T:"per_unit").toLowerCase(),M="per_bo"===E||"per_batch"===E?"per_batch":"per_line_item"===E?"per_line_item":"per_unit",O=Math.abs(p.timeMultiplier-1)>.15,A=Math.floor(p.estimatedTime),F=Math.round((p.estimatedTime-A)*60),D=(0,eK.S3)({estimatedTime:p.estimatedTime,estimatedSecsPerUnit:m.estimatedSecsPerUnit,operationQuantity:p.operationQuantity,timeMultiplier:p.timeMultiplier,boQuantity:f,quoteTimeApplication:T}),R=null!==m.quoteEstimatedSeconds?Number(m.quoteEstimatedSeconds):0,P=Number.isFinite(R)&&R>0?(0,eK.S3)({estimatedTime:R/60,operationQuantity:p.operationQuantity,timeMultiplier:p.timeMultiplier,boQuantity:f,quoteTimeApplication:T}):0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"flex items-end gap-3 flex-wrap",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{className:"block text-[10px] font-medium admin-text-muted mb-0.5",children:"Complexity"}),(0,a.jsxs)("select",{value:p.complexity,onChange:e=>u(t=>({...t,complexity:e.target.value})),className:"w-28 px-2 py-1 border admin-border rounded text-xs focus:ring-mp-orange focus:border-mp-orange",children:[(0,a.jsx)("option",{value:"simple",children:"Simple"}),(0,a.jsx)("option",{value:"medium",children:"Medium"}),(0,a.jsx)("option",{value:"complex",children:"Complex"})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{className:"block text-[10px] font-medium admin-text-muted mb-0.5",children:"Operator"}),(0,a.jsxs)("select",{value:p.level,onChange:e=>u(t=>({...t,level:Number(e.target.value)})),className:"w-20 px-2 py-1 border admin-border rounded text-xs focus:ring-mp-orange focus:border-mp-orange",children:[(0,a.jsx)("option",{value:1,children:"L1"}),(0,a.jsx)("option",{value:2,children:"L2"}),(0,a.jsx)("option",{value:3,children:"L3"})]})]}),(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{className:"block text-[10px] font-medium admin-text-muted mb-0.5",children:I}),(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)(eV.Y2,{value:A,onChange:e=>{let t=e||0;u(e=>({...e,estimatedTime:Math.round((t+F/60)*100)/100,manualOverride:!0}))},min:0,unit:"m",className:"w-12"}),(0,a.jsx)(eV.Y2,{value:F,onChange:e=>{let t=Math.max(0,Math.min(59,e||0));u(e=>({...e,estimatedTime:Math.round((A+t/60)*100)/100,manualOverride:!0}))},min:0,max:59,unit:"s",className:"w-12"}),(0,a.jsx)("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium border admin-border admin-text-secondary",children:b[k.source]}),!p.manualOverride&&(0,a.jsx)("button",{type:"button",onClick:()=>u(e=>({...e,manualOverride:!0})),className:"text-[10px] font-medium text-mp-orange hover:underline",children:"Override"})]})]}),(0,a.jsx)(eV.Fz,{value:p.operationQuantity,onChange:e=>u(t=>({...t,operationQuantity:e||1})),label:C,min:1,className:"w-14"}),(0,a.jsxs)("div",{className:"flex-1 min-w-[180px]",children:[(0,a.jsxs)("label",{className:"block text-[10px] font-medium admin-text-muted mb-0.5",children:["Tweak ",(0,a.jsxs)("span",{className:"text-mp-orange font-semibold",children:[p.timeMultiplier.toFixed(1),"\xd7"]})]}),(0,a.jsxs)("div",{className:"relative h-4 flex items-center",children:[(0,a.jsx)("div",{className:"absolute top-1/2 -translate-y-1/2 w-px h-3 bg-mp-orange/70 pointer-events-none",style:{left:"".concat(20,"%")},"aria-hidden":!0}),(0,a.jsx)("input",{type:"range",min:.5,max:3,step:.1,value:p.timeMultiplier,onCh
1ange:e=>u(t=>({...t,timeMultiplier:parseFloat(e.target.value)})),className:"relative w-full h-1.5 accent-mp-orange cursor-pointer"})]})]})]}),w>0&&w!==p.estimatedTime&&(0,a.jsxs)("button",{type:"button",onClick:()=>u(e=>({...e,estimatedTime:w,manualOverride:!1})),className:"text-xs font-medium text-mp-orange hover:underline",children:["Apply Standard (",g(w),")"]}),O&&(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{className:"block text-[10px] font-medium admin-text-muted mb-0.5",children:"Tweak Reason"}),(0,a.jsx)("input",{type:"text",value:p.timeMultiplierReason,onChange:e=>u(t=>({...t,timeMultiplierReason:e.target.value})),placeholder:"Why is this tweak needed?",className:"w-full max-w-md px-2 py-1 border admin-border rounded text-xs focus:ring-mp-orange focus:border-mp-orange"})]}),!v&&(0,a.jsxs)("div",{className:"inline-flex items-center gap-2 px-2 py-1 rounded bg-mp-warning/10 dark:bg-mp-warning/15 text-mp-warning dark:text-mp-warning text-xs font-medium border border-mp-warning/30",children:[(0,a.jsxs)("span",{children:["No Qualified Operator For L",p.level]}),j>=1&&j<p.level&&(0,a.jsxs)("button",{type:"button",onClick:()=>u(e=>({...e,level:j})),className:"underline font-semibold",children:["Use L",j]})]}),(0,a.jsxs)("div",{className:"px-2 py-1 admin-bg-tertiary rounded text-xs flex items-center gap-1 flex-wrap",children:[(0,a.jsx)("span",{className:"admin-text-secondary",children:p.estimatedTime>0?"".concat(A,"m").concat(F>0?" ".concat(F,"s"):""):"0m"}),"per_batch"!==M&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{className:"text-mp-orange font-medium",children:"\xd7"}),(0,a.jsx)("span",{className:"admin-text-secondary",children:p.operationQuantity})]}),(0,a.jsx)("span",{className:"text-mp-orange font-medium",children:"\xd7"}),(0,a.jsxs)("span",{className:"admin-text-secondary",children:[p.timeMultiplier.toFixed(1),"\xd7"]}),"per_unit"===M&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{className:"text-mp-orange font-medium",children:"\xd7"}),(0,a.jsxs)("span",{className:"admin-text-secondary",children:[f," harness",1!==f?"es":""]})]}),(0,a.jsx)("span",{className:"text-mp-orange font-medium",children:"="}),(0,a.jsx)("span",{className:"font-semibold admin-text-primary",children:g(D/60)}),P>0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{className:"mx-1 admin-text-muted",children:"|"}),(0,a.jsxs)("span",{className:"admin-text-secondary",children:["Quote ",g(P/60)]}),(0,a.jsx)("span",{className:"font-semibold admin-text-primary",children:function(e){if(null===e)return"â";let t=Math.round(10*e)/10;return"".concat(t>0?"+":"").concat(t%1==0?t.toString():t.toFixed(1),"%")}(P>0?(D/P-1)*100:null)})]})]})]})}function e2(e){let{value:t,onChange:n,quoteTier:r}=e;return(0,a.jsx)(eg.VG,{value:t,onChange:n,rows:8,label:"Custom Instructions",placeholder:"Detailed instructions for this operation...",snippets:eY.$,quoteTier:"standard"===r||"precision"===r||"high-precision"===r?r:void 0})}function e5(e){let{onDelete:t,isSaving:n,disabled:r,autosaveStatus:i,lastSavedAt:s,formatLastSaved:o,isDirty:l,onSaveNow:d}=e;return(0,a.jsxs)("div",{className:"flex justify-between items-center pt-2 border-t border-gray-100 dark:border-zinc-800",children:[(0,a.jsx)("button",{onClick:t,disabled:n||r,className:"px-3 py-1.5 text-sm text-mp-danger hover:text-mp-danger dark:hover:text-mp-danger disabled:opacity-50",children:"Delete"}),(0,a.jsxs)("div",{className:"flex items-center gap-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-1.5 text-xs admin-text-muted",children:["saving"===i&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"h-3 w-3 border-2 border-mp-orange border-t-transparent rounded-full animate-spin"}),(0,a.jsx)("span",{children:"Saving..."})]}),"pending"===i&&(0,a.jsx)("span",{children:"Unsaved"}),"saved"===i&&(0,a.jsxs)("span",{className:"text-mp-positive dark:text-mp-positive",children:["Saved",s?" ".concat(o()):""]}),"idle"===i&&s&&(0,a.jsxs)("span",{children:["Saved ",o()]})]}),(0,a.jsx)("button",{type:"button","data-testid":"wi-save-now",onClick:()=>{d()},disabled:r||!l&&!n,className:"px-3 py-1.5 bg-mp-orange text-white rounded text-sm disabled:opacity-50 hover:bg-mp-orange-dark",children:n?"Saving...":l?"Save Now":"Saved"})]})]})}function e3(e){let{operation:t,onSave:n,onFlush:i,onDelete:s,isSaving:o,workSteps:l,boQuantity:d,quoteTier:c,disabled:m=!1}=e,p=function(e,t,n,a){let[i,s]=(0,r.useState)(()=>{var t,n;return{operationName:e.operationName,workStepId:e.workStepId,operationDescription:e.operationDescription||"",complexity:e.complexity||"medium",level:null!==(t=e.level)&&void 0!==t?t:1,estimatedTime:e.estimatedTime?parseFloat(e.estimatedTime):0,operationQuantity:null!==(n=e.operationQuantity)&&void 0!==n?n:1,timeMultiplier:e.timeMultiplier?parseFloat(e.timeMultiplier):1,timeMultiplierReason:e.timeMultiplierReason||"",customInstru
1ctions:e.customInstructions||"",attachmentUrls:e.attachmentUrls||[],manualOverride:!!e.manualTimeOverride}}),[o,l]=(0,r.useState)(null),[d,c]=(0,r.useState)("idle"),[m,p]=(0,r.useState)(!1),[,u]=(0,r.useState)(0),x=(0,r.useRef)(!0),h=(0,r.useRef)(!1),f=(0,r.useRef)(t);f.current=t;let g=(0,r.useRef)(n);g.current=n;let b=(0,r.useCallback)(e=>({operationName:e.operationName,...e.workStepId?{workStepId:e.workStepId}:{},operationDescription:e.operationDescription||null,complexity:e.complexity,level:e.level,estimatedTime:e.estimatedTime?e.estimatedTime.toString():null,operationQuantity:e.operationQuantity,timeMultiplier:e.timeMultiplier.toString(),timeMultiplierReason:e.timeMultiplierReason||null,customInstructions:e.customInstructions||null,attachmentUrls:e.attachmentUrls.length>0?e.attachmentUrls:null,manualTimeOverride:e.manualOverride}),[]);return(0,r.useEffect)(()=>{if(x.current){x.current=!1;return}p(!0),c("pending"),f.current(b(i))},[i,b]),(0,r.useEffect)(()=>()=>{g.current()},[]),(0,r.useEffect)(()=>{a?c("saving"):h.current&&(l(new Date),c("saved"),p(!1)),h.current=a},[a]),(0,r.useEffect)(()=>{let e=setInterval(()=>u(e=>e+1),3e4);return()=>clearInterval(e)},[]),{formData:i,setFormData:s,buildSaveData:b,autosaveStatus:d,lastSavedAt:o,isDirty:m,saveNow:async()=>{await n()&&(c("saved"),l(new Date),p(!1))},formatLastSaved:()=>{if(!o)return null;let e=Math.floor((new Date().getTime()-o.getTime())/1e3),t=Math.floor(e/60);return e<5?"just now":e<60?"".concat(e,"s ago"):t<60?"".concat(t,"m ago"):o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}}}(t,n,i,o),{formData:u,setFormData:x}=p;return(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsx)(eX,{workSteps:l,value:u.operationName,onPick:(e,t)=>x(n=>({...n,operationName:e,workStepId:t}))}),(0,a.jsx)(e0,{value:u.operationDescription,onChange:e=>x(t=>({...t,operationDescription:e}))}),(0,a.jsx)(e1,{operation:t,formData:u,setFormData:x,workSteps:l,boQuantity:d}),(0,a.jsx)(e2,{value:u.customInstructions,onChange:e=>x(t=>({...t,customInstructions:e})),quoteTier:c}),(0,a.jsx)(e$.z,{attachmentUrls:u.attachmentUrls,onAttachmentsChange:e=>x(t=>({...t,attachmentUrls:e})),maxAttachments:10}),(0,a.jsx)(e5,{onDelete:s,isSaving:o,disabled:m,autosaveStatus:p.autosaveStatus,lastSavedAt:p.lastSavedAt,formatLastSaved:p.formatLastSaved,isDirty:p.isDirty,onSaveNow:p.saveNow})]})}function e4(e){var t,n;let{operation:i,operations:o,edges:l,locked:d,boQuantity:c}=e,m=(0,s.Sj)(),{getNode:p}=(0,s._K)(),u=p(i.id),[x,h]=(0,r.useState)(!1),[f,g]=(0,r.useState)("finish_to_start"),[b,y]=(0,r.useState)(""),v=(0,r.useMemo)(()=>new Map(o.map(e=>[e.id,e])),[o]),j=l.filter(e=>e.operationId===i.id),N=l.filter(e=>e.dependsOnOperationId===i.id),w=(0,r.useMemo)(()=>o.map(e=>eH(e,c)),[o,c]),k=(0,r.useMemo)(()=>eQ(l),[l]),S=!1!==i.routable,C=o.filter(e=>!1!==e.routable).filter(e=>e.id!==i.id&&!j.some(t=>t.dependsOnOperationId===e.id)).filter(e=>!b.trim()||e.operationName.toLowerCase().includes(b.trim().toLowerCase())).slice(0,12),I=t=>{let n=eU(t,i.id,f),a=eL(w,k,n);if(a){e.onEdgeError(a.message);return}e.onEdgesChange(e_(k,n)),h(!1),y("")},T=(()=>{var t,n;let a=null===(t=e.canvasRef)||void 0===t?void 0:t.current,r=null===(n=e.hostRef)||void 0===n?void 0:n.current;if(!u||!a||!r)return{right:16,top:16,maxHeight:"calc(100% - 32px)"};let i=a.getBoundingClientRect(),s=r.getBoundingClientRect(),o=i.left-s.left,l=i.top-s.top,d=o+u.position.x*m.zoom+m.x,c=l+u.position.y*m.zoom+m.y,p=s.width,x=s.height,h=d+148*m.zoom+18,f=Math.max(8,Math.min(c-8,x-8-Math.min(x-16,420)));return{left:h+380>p-8?Math.max(8,d-380-18):h,top:f,maxHeight:x-f-8}})(),E="qc"===i.opCatalogType;return(0,a.jsxs)("div",{role:"dialog","aria-labelledby":"wi-op-card-title","data-testid":"wi-op-details",className:"!absolute z-[60] flex flex-col overflow-hidden rounded-[4px] border admin-border admin-bg-secondary shadow-xl",style:{width:380,...T},onMouseDown:e=>e.stopPropagation(),children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 border-b admin-border admin-bg-tertiary px-3.5 py-2.5",children:[(0,a.jsxs)("span",{id:"wi-op-card-title",className:"truncate text-[13px] font-semibold admin-text-primary",children:[(0,a.jsx)("span",{className:"mr-1.5 font-brandMono admin-text-muted",children:i.sequenceNumber}),i.operationName]}),(0,a.jsx)("span",{className:"ml-auto text-[11px] admin-text-muted",children:(t=i.opCatalogType)?null!==(n=eB.w[t])&&void 0!==n?n:t:"Unassigned"}),(0,a.jsx)("button",{type:"button","aria-label":"Close details",className:"ml-1 rounded-[2px] px-1 admin-text-muted hover:admin-text-primary",onClick:e.onClose,children:"â"})]}),(0,a.jsxs)("div",{className:"min-h-0 flex-1 overflow-y-auto px-3.5 py-3",children:[S?null:(0,a.jsx)("div",{className:"mb-3 rounded-[2px] bg-mp-warning/10 px-2 py-1.5 text-[12px] text-mp-warning","data-testid":"wi-op-not-routable",children:"Generic, office, and shipping steps sit outside the routing and cannot be linked."}),(0,a.jsx)("div",{className:"mb-1 text-[11px] font-semibold admin-text-muted",children:"Runs after"}),(0,a.jsxs)("div",{className:"mb-3 overflow-hidden rounded-[2px] border admin-border","data-testid":"wi-op-predecessors",children:[0===j.length?(0,a.jsx)("div",{className:"px-2 py-1.5 text-[12px] admin-text-muted",children:"Nothing. This step can start first."}):null,j.map(t=>{var n,r,i;let s=v.get(t.dependsOnOperationId);return(0,a.jsxs)("div",{className:"flex items-center gap-2 border-b admin-border px-2 py-1.5 text-[12.5px] last:border-b-0",children:[(0,a.jsx)("span",{className:"w-4 font-brandMono text-[11px] admin-text-muted",children:null!==(n=null==s?void 0:s.sequenceNumber)&&void 0!==n?n:"?"}),(0,a.jsx)("span",{className:"truncate admin-text-primary",children:null!==(r=null==s?void 0:s.operationName)&&void 0!==r?r:t.dependsOnOperationId}),"start_to_start"===t.dependencyType?(0,a.jsx)("span",{className:"rounded-[2px] bg-[#f5f3ff] px-1 text-[10.5px] font-semibold text-[#6d28d9]",children:"starts with"}):null,t.implicit?(0,a.jsx)("span",{className:"text-[10.5px] admin-text-muted",children:"sequence"}):null,d?null:(0,a.jsx)("button",{type:"button","aria-label":"Remove dependency on ".concat(null!==(i=null==s?void 0:s.operationName)&&void 0!==i?i:"operation"),className:"ml-auto rounded-[2px] px-1 admin-text-muted hover:text-mp-danger",onClick:()=>void e.onEdgesChange(ez(k,"".concat(t.dependsOnOperationId,"->").concat(t.operationId))),children:"â"})]},"".concat(t.dependsOnOperationId,"->").concat(t.operationId))}),!d&&S?(0,a.jsx)("div",{className:"admin-bg-primary px-2 py-1.5 text-[12.5px]",children:x?(0,a.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("input",{autoFocus:!0,value:b,onChange:e=>y(e.target.value),placeholder:"Search operations",className:"min-w-0 flex-1 rounded-[2px] border admin-border px-2 py-1 text-[12px]"}),(0,a.jsxs)("label",{className:"flex items-center gap-1 text-[11px]",title:E?"":"Only QC operations can start with another step",children:[(0,a.jsx)("input",{type:"checkbox",disabled:!E,checked:"start_to_start"===f,onChange:e=>g(e.target.checked?"start_to_start":"finish_to_start")}),"starts with"]}),(0,a.jsx)("button",{type:"button",className:"admin-text-muted",onClick:()=>h(!1),children:"Cancel"})]}),(0,a.jsxs)("div",{className:"max-h-40 overflow-y-auto",children:[C.map(e=>(0,a.jsxs)("button",{type:"button",className:"flex w-full items-center gap-2 rounded-[2px] px-1.5 py-1 text-left hover:admin-bg-tertiary",onClick:()=>I(e.id),children:[(0,a.jsx)("span",{className:"w-4 font-brandMono text-[11px] admin-text-muted",children:e.sequenceNumber}),(0,a.jsx)("span",{className:"truncate",children:e.operationName})]},e.id)),0===C.length?(0,a.jsx)("div",{className:"px-1.5 py-1 admin-text-muted",children:"No matching operations"}):null]})]}):(0,a.jsx)("button",{type:"button",className:"font-medium text-mp-blue",onClick:()=>h(!0),"data-testid":"wi-add-predecessor",children:"+ Add predecessor"})}):null]}),(0,a.jsx)("div",{className:"mb-1 text-[11px] font-semibold admin-text-muted",children:"Followed by"}),(0,a.jsxs)("div",{className:"mb-3 overflow-hidden rounded-[2px] border admin-border","data-testid":"wi-op-successors",children:[0===N.length?(0,a.jsx)("div",{className:"px-2 py-1.5 text-[12px] admin-text-muted",children:"Nothing waits on this step."}):null,N.map(e=>{var t,n;let r=v.get(e.operationId);return(0,a.jsxs)("div",{className:"flex items-center gap-2 border-b admin-border px-2 py-1.5 text-[12.5px] last:border-b-0",children:[(0,a.jsx)("span",{className:"w-4 font-brandMono text-[11px] admin-text-muted",children:null!==(t=null==r?void 0:r.sequenceNumber)&&void 0!==t?t:"?"}),(0,a.jsx)("span",{className:"truncate admin-text-primary",children:null!==(n=null==r?void 0:r.operationName)&&void 0!==n?n:e.operationId}),"start_to_start"===e.dependencyType?(0,a.jsx)("span",{className:"rounded-[2px] bg-[#f5f3ff] px-1 text-[10.5px] font-semibold text-[#6d28d9]",children:"starts with"}):null]}
1,"".concat(e.dependsOnOperationId,"->").concat(e.operationId))})]}),(0,a.jsx)(e3,{operation:i,onSave:t=>e.onSave(i.id,t),onFlush:e.onFlush,onDelete:()=>e.onDelete(i.id),isSaving:e.isSaving,workSteps:e.workSteps,boQuantity:c,quoteTier:e.quoteTier,disabled:d},i.id)]})]})}let e6=[{id:"notes",label:"Notes",icon:"â"},{id:"bom",label:"BOM",icon:"â°"},{id:"files",label:"Files",icon:"â¤"},{id:"handbook",label:"Handbook",icon:"â£"},{id:"checks",label:"Checks",icon:"â"},{id:"tools",label:"Tools",icon:"â"}];function e9(e){let{open:t,badges:n,onToggle:r}=e;return(0,a.jsx)("div",{className:"!absolute !bottom-4 !right-4 !left-auto !top-auto z-20 flex w-auto gap-1 rounded-[4px] border admin-border admin-bg-secondary p-1 shadow-sm",role:"toolbar","aria-label":"Panels",children:e6.map(e=>{let i=null==n?void 0:n[e.id];return(0,a.jsxs)("button",{type:"button","aria-pressed":t===e.id,"aria-label":e.label,title:e.label,"data-testid":"wi-dock-".concat(e.id),onClick:()=>r(e.id),className:["relative flex h-8 w-8 items-center justify-center rounded-[2px] text-[13px]",t===e.id?"bg-mp-blue text-white":"admin-text-secondary hover:admin-bg-tertiary"].join(" "),children:[e.icon,i?(0,a.jsx)("span",{className:"absolute -right-1 -top-1 min-w-4 rounded-full bg-mp-orange px-1 text-center text-[9px] font-bold leading-4 text-white",children:i}):null]},e.id)})})}function e8(e){let{title:t,onClose:n,children:r}=e;return(0,a.jsxs)("div",{role:"dialog","aria-label":t,"data-testid":"wi-panel-sheet",className:"!absolute inset-y-0 !right-0 !left-auto z-30 flex w-[600px] max-w-full flex-col border-l admin-border admin-bg-secondary shadow-xl",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2 border-b admin-border admin-bg-tertiary px-4 py-2.5",children:[(0,a.jsx)("span",{className:"text-[13px] font-semibold admin-text-primary",children:t}),(0,a.jsx)("button",{type:"button","aria-label":"Close ".concat(t),className:"ml-auto rounded-[2px] px-1 admin-text-muted hover:admin-text-primary",onClick:n,children:"â"})]}),(0,a.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:r})]})}let e7={notes:"Assembler Notes",bom:"Bill Of Materials",files:"Files",handbook:"Operations Handbook",checks:"Checks",tools:"Quick Tools"};function te(e){let{operations:t,incompleteReasonByOpId:n,estimateMinutesFor:r}=e;return(0,a.jsxs)("div",{className:"flex-1 overflow-y-auto px-4 py-3","data-testid":"wi-readonly-list",children:[(0,a.jsx)("p",{className:"mb-3 text-[12px] admin-text-muted",children:"Routing is edited on a desktop. This list shows the operations in order."}),(0,a.jsx)("ol",{className:"flex flex-col gap-1.5",children:t.map(e=>{let t=n.get(e.id);return(0,a.jsxs)("li",{className:"flex items-center gap-3 rounded-[4px] border admin-border admin-bg-secondary px-3 py-2",style:{borderLeft:"3px solid ".concat(C[T(e.opCatalogType)])},children:[(0,a.jsx)("span",{className:"w-5 font-brandMono text-[11px] font-semibold admin-text-muted",children:e.sequenceNumber}),(0,a.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] font-medium admin-text-primary",children:e.operationName}),(0,a.jsx)("span",{className:"text-[11px] tabular-nums admin-text-muted",children:g(r(e))}),t?(0,a.jsx)("span",{title:t,className:"rounded-[2px] bg-mp-warning/10 px-1.5 text-[10px] font-semibold text-mp-warning",children:t}):null]},e.id)})})]})}function tt(e){var t,n;let r={positive:"text-mp-positive",warning:"text-mp-warning",danger:"text-mp-danger",muted:"admin-text-muted",neutral:"admin-text-muted"}[null!==(n=null===(t=e.verdict)||void 0===t?void 0:t.tone)&&void 0!==n?n:"muted"];return(0,a.jsxs)("div",{className:"flex flex-shrink-0 items-center gap-3 border-b admin-border px-6 py-4",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("h2",{className:"truncate text-lg font-semibold admin-text-primary",children:e.title}),(0,a.jsx)("div",{className:"truncate text-[13px] admin-text-secondary",children:e.subt
1itle})]}),(0,a.jsxs)("div",{className:"ml-auto flex items-center gap-2",children:[e.locked?(0,a.jsx)("span",{className:"rounded-[2px] bg-mp-blue/10 px-2 py-1 text-[11px] font-semibold text-mp-blue","data-testid":"wi-locked-banner",children:"AI run in progress \xb7 editing paused"}):null,(0,a.jsxs)("span",{"data-testid":"wi-estimate-summary",className:"inline-flex flex-shrink-0 items-center gap-2 whitespace-nowrap rounded border admin-border admin-bg-tertiary px-3 py-1.5 text-xs admin-text-secondary",children:["Setup ",g(e.setupMinutes),null!=e.quoteMinutes?(0,a.jsxs)(a.Fragment,{children:[" \xb7 Quote ",g(e.quoteMinutes)]}):null,e.verdict?(0,a.jsx)("span",{"data-testid":"wi-variance-chip",className:"whitespace-nowrap font-semibold ".concat(r),children:e.verdict.label}):null]}),(0,a.jsxs)("span",{title:"Longest chain of dependent steps if every branch is staffed. Production Plan shows the staffed schedule.",className:"inline-flex flex-shrink-0 items-center whitespace-nowrap rounded border admin-border admin-bg-tertiary px-3 py-1.5 text-xs admin-text-secondary","data-testid":"wi-critical-path",children:["Critical Path ",null==e.criticalPathMinutes?"â":g(e.criticalPathMinutes)]}),(0,a.jsx)(l.qW,{optional:!0}),(0,a.jsx)("button",{type:"button","data-testid":"wi-save-state",onClick:e.onSaveNow,disabled:"dirty"!==e.saveState,className:["rounded-[2px] px-2 py-1 text-xs","dirty"===e.saveState?"font-medium text-mp-orange hover:bg-mp-orange/10":"admin-text-muted"].join(" "),children:"dirty"===e.saveState?"Unsaved \xb7 Save now":"saving"===e.saveState?"Savingâ¦":"Saved"}),(0,a.jsx)("button",{type:"button",onClick:e.onClose,className:"rounded border admin-border px-4 py-2 text-sm admin-text-primary",children:"Close"})]})]})}function tn(e){var t;return(0,a.jsxs)("div",{className:"flex flex-shrink-0 flex-wrap items-center gap-3 border-t admin-border admin-bg-tertiary px-6 py-4",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-3 text-[12px] admin-text-muted",children:[Object.keys(I).map(e=>(0,a.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,a.jsx)("i",{className:"inline-block h-2 w-2 rounded-[2px]",style:{background:C[e]}}),I[e]]},e)),(0,a.jsx)("span",{children:"â after"}),(0,a.jsx)("span",{children:"â starts with"})]}),(0,a.jsxs)("div",{className:"ml-auto flex items-center gap-3 text-[13px] admin-text-secondary",children:[e.children,(0,a.jsxs)("span",{children:[e.operationCount," operations \xb7 ",e.branchCount," ",1===e.branchCount?"branch":"branches"]}),e.unauthoredCount>0?(0,a.jsxs)("button",{type:"button","data-testid":"wi-unauthored-count",onClick:e.onShowUnauthored,className:"font-medium text-mp-warning",children:[e.unauthoredCount," unauthored"]}):null,(0,a.jsx)("span",{"data-testid":"wi-graph-valid",title:null!==(t=e.graphMessage)&&void 0!==t?t:void 0,className:["inline-flex items-center rounded-[2px] border px-2.5 py-0.5 font-brandMono text-xs font-semibold",e.graphValid?"border-mp-positive/30 bg-mp-positive/10 text-mp-positive":"border-mp-danger/30 bg-mp-danger/10 text-mp-danger"].join(" "),children:e.graphValid?"Graph Valid":"Graph Invalid"}),(0,a.jsx)("button",{type:"button",onClick:e.onClose,className:"rounded border admin-border px-4 py-2 text-sm admin-text-primary",children:"Close"}),(0,a.jsx)("button",{type:"button","data-testid":"wi-approve",onClick:e.onApprove,disabled:e.approveDisabled||e.isApproving,className:"rounded bg-mp-positive px-4 py-2 text-sm text-white disabled:opacity-50",children:e.isApproving?"Approvingâ¦":"Approve WI"})]})]})}function ta(e){let{buildOrderId:t,children:n}=e,[i,s]=(0,r.useState)([]);return(0,r.useEffect)(()=>{let e=!1;return(0,f.QC)(t,e=>fetch(e).then(e=>e.ok?e.json():null)).then(t=>{e||s(t)}).catch(()=>void 0),()=>{e=!0}},[t]),(0,a.jsx)(l.Dc,{assemblyId:t,docs:i,surface:"wi",children:n})}function tr(e){var t,n,l,u,g,b,N,w,k,S,C,I,T,E,M,O,A,F,D;let{buildOrder:R,onClose:P,onApproved:L}=e,_=(0,d.Y)(),{showError:z,showSuccess:U}=(0,c.pm)(),B=function(){let[e,t]=(0,r.useState)(!0);return(0,r.useEffect)(()=>{if(!window.matchMedia)return;let e=window.matchMedia("(min-width: 1024px)"),n=()=>t(e.matches);
1return n(),e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]),e}(),Z=function(e,t){var n;let{onApproved:a,onClose:i}=t,s=(0,d.Y)(),{showError:o,showSuccess:l}=(0,c.pm)(),[u,g]=(0,r.useState)([]),[b,j]=(0,r.useState)(null),[N,w]=(0,r.useState)(!1),[k,S]=(0,r.useState)(0),[C,I]=(0,r.useState)(null!==(n=e.aiOpenIssues)&&void 0!==n?n:0),[T,E]=(0,r.useState)(0),[M,O]=(0,r.useState)("WI Pending"===e.boStatus||"Queued"===e.boStatus||"In Progress"===e.boStatus&&(!e.workInstructionsVerifiedAt||!e.workInstructionsVerifiedBy)),[A,F]=(0,r.useState)("WI Pending"===e.boStatus||"Queued"===e.boStatus&&"Kitted"===e.kitStatus||"In Progress"===e.boStatus),D=(0,r.useRef)(!1);D.current=N;let[R,P]=(0,r.useState)(!0),[L,_]=(0,r.useState)(!1),[z,U]=(0,r.useState)(null),[q,B]=(0,r.useState)(null),[Z,H]=(0,r.useState)([]),[W,Q]=(0,r.useState)(!1),[J,G]=(0,r.useState)([]),[V,K]=(0,r.useState)(!1),[Y,$]=(0,r.useState)(null),[X,ee]=(0,r.useState)([]),[et,en]=(0,r.useState)(""),[ea,er]=(0,r.useState)(!1),[ei,es]=(0,r.useState)(!1),eo=(0,r.useRef)([]),[el,ed]=(0,r.useState)(null),[ec,em]=(0,r.useState)(.2),[ep,eu]=(0,r.useState)({}),[ex,eh]=(0,r.useState)(!1),[ef,eg]=(0,r.useState)([]),eb=(0,r.useRef)(new Map),ey=(0,r.useRef)(null),ev=(0,r.useRef)(null),ej=(0,r.useRef)([]),eN=(0,r.useRef)(new Map),[ew,ek]=(0,r.useState)(0),[eS,eC]=(0,r.useState)(!1),[eI,eT]=(0,r.useState)(!1),eE=(0,r.useCallback)(e=>{for(let t of e)eN.current.set(t.id,{...t})},[]),eM=(0,r.useCallback)(e=>{let t=new Set(e),n=e=>{var n;if(!t.has(e.id))return e;let a=null!==(n=eN.current.get(e.id))&&void 0!==n?n:e,r=eb.current.get(e.id);return r?{...a,...r}:a};g(e=>e.map(n)),eo.current=eo.current.map(n),ek(e=>e+1)},[]),[eO,eA]=(0,r.useState)([]),eF=(0,r.useCallback)(async()=>{try{P(!0);let t=await fetch("/api/admin/build-orders/".concat(e.id,"/operations?manufacturing=false"));if(!t.ok)throw Error("Failed to fetch operations");let n=await t.json();em("number"==typeof n.varianceThreshold&&Number.isFinite(n.varianceThreshold)?n.varianceThreshold:.2);let a=(n.operations||[]).filter(e=>!(0,m.$1)({operationName:e.operationName,catalogType:e.opCatalogType}));j(n.routing&&"object"==typeof n.routing?n.routing:null);let r=a.filter(e=>(0,m.EK)({operationName:e.operationName,catalogType:e.opCatalogType})&&!e.isEnriched);if(r.length>0)for(let t of r){let n=(0,m.bz)(e.id,t.id);fetch(n.url,{method:n.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(n.body)}).catch(()=>{})}eo.current=a;let i=a.filter(e=>!(0,m.EK)({operationName:e.operationName,catalogType:e.opCatalogType}));g(i),eE(a),U(null),i.length>0&&!q&&B(i[0].id)}catch(t){p.k.error("Error fetching operations",{buildOrderId:e.id,error:t instanceof Error?t.message:String(t)}),U("Failed to load operations")}finally{P(!1)}},[e.id,eE]);(0,r.useEffect)(()=>{eF()},[eF]),(0,r.useEffect)(()=>{let t=!1;return(async()=>{try{var n;let a=await fetch("/api/admin/build-orders/".concat(e.id,"/agent-runs"));if(!a.ok||t)return;let r=await a.json();"boolean"==typeof r.canRun&&O(r.canRun),"boolean"==typeof r.canSend&&F(r.canSend);let i=null===(n=r.runs)||void 0===n?void 0:n[0],s=(null==i?void 0:i.status)==="queued"||(null==i?void 0:i.status)==="running";w(s)}catch(t){p.k.warn("Failed to load WI agent runs",{buildOrderId:e.id,error:t instanceof Error?t.message:String(t)})}})(),()=>{t=!0}},[e.id]),(0,r.useEffect)(()=>{fetch("/api/admin/build-orders/".concat(e.id,"/quote-tier")).then(e=>e.ok?e.json():null).then(e=>{(null==e?void 0:e.tier)&&ed(e.tier)}).catch(t=>p.k.warn("quote tier fetch failed",{buildOrderId:e.id,error:t instanceof Error?t.message:String(t)}))},[e.id]),(0,r.useEffect)(()=>{let t=!1;return(0,f.QC)(e.id,e=>fetch(e).then(e=>e.ok?e.json():null)).then(e=>{t||eA(e)}),()=>{t=!0}},[e.id]),(0,r.useEffect)(()=>{ej.current=u},[u]);let eD=(0,r.useCallback)(async()=>{if(!(Z.length>0)){Q(!0);try{let e=await fetch("/api/admin/work-steps?limit=200");if(!e.ok)throw Error("Failed to fetch work steps");let t=await e.json();H((t.workSteps||[]).map(e=>({id:e.id,name:e.name,description:e.description||null,timeApplication:e.timeApplication||null,timeStandard:e.timeStandard?{simpleTime:e.timeStandard.simpleTime,mediumTime:e.timeStandard.mediumTime,complexTime:e.timeStandard.complexTime}:null})))}catch(e){p.k.error("Error fetching work steps",{error:e instanceof Error?e.message:String(e)})}finally{Q(!1)}}},[Z.length]);(0,r.useEffect)(()=>{eD()},[eD]);let eR=(0,r.useCallback)(async()=>{try{let e=await fetch("/api/admin/system/operation-templates");if(!e.ok)return;let t=await e.json();G(t.templates||[])}catch(e){p.k.error("Failed to fetch operation templates",{error:e instanceof Error?e.message:String(e)})}},[]);(0,r.useEffect)(()=>{eR()},[eR]);let eP=(0,r.useCallback)(async t=>{er(!0);try{let n=new URLSearchParams;e.partNumber&&n.set("partNumber",e.partNumber),n.set("excludeBoId",e.id),t&&n.set("search",t);let a=await fetch("/api/admin/build-orders/with-enriched-ops?".concat(n));if(!a.ok)return;let r=await a.json();ee(r.matches||[])}catch(e){p.k.error("Failed to fetch copy BO candidates",{error:e instanceof Error?e.message:String(e)})}finally{er(!1)}},[e.id,e.partNumber]),eL=(0,r.useRef)(null),e_=(0,r.useCallback)(e=>{en(e),eL.current&&clearTimeout(eL.current),eL.current=setTimeout(()=>{eP(e||void 0)},400)},[eP]),ez=async t=>{let n=t.inventreeBoNumber||"BO-".concat(t.id.slice(0,8));if(!await s.confirm({title:"Copy WI From ".concat(n,"?"),description:"Matched operations (by work step or name) will be overwritten with the source's instructions, timings, and attachments. Unmatched source operations will be inserted into this BO. Generic placeholder ops will be replaced.",confirmText:"Copy WI",variant:"warning"}))return!1;es(!0);try{let n=await fetch("/api/admin/build-orders/".concat(e.id,"/operations/copy-enrichment"),{method:"POST",headers:{"Content-Type":"application/json"}
1,body:JSON.stringify({sourceBoId:t.id})});if(!n.ok){let e=await n.json();throw Error(e.error||"Failed to copy enrichment")}let a=await n.json();await eF();let r=[];return r.push("".concat(a.copied," updated")),"number"==typeof a.added&&r.push("".concat(a.added," added")),r.push("".concat(a.skipped," unmatched")),l("WI Copied","Copied WI: ".concat(r.join(", "),".")),!0}catch(e){return p.k.error("Error copying from BO",{error:e instanceof Error?e.message:String(e)}),o("WI Copy Failed",e instanceof Error?e.message:"Failed to copy enrichment"),!1}finally{es(!1)}},eU=async t=>{if(!D.current){K(!0);try{var n,a,r;let i=[...u],s=[];for(let e of t.operations){let t=i.findIndex(t=>t.operationName===e.operationName);if(-1===t)continue;let[n]=i.splice(t,1);s.push({id:n.id,operationDescription:null!==(a=e.operationDescription)&&void 0!==a?a:null,complexity:e.complexity,estimatedTime:null==e.estimatedTime?null:String(e.estimatedTime),customInstructions:null!==(r=e.customInstructions)&&void 0!==r?r:null})}if(0===s.length){o("Template Not Applied","No matching operations to update.");return}let l=await fetch("/api/admin/build-orders/".concat(e.id,"/operations"),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({operations:s})});if(!l.ok){let e=await l.json().catch(()=>({}));throw Error("object"==typeof e&&e&&"error"in e&&"string"==typeof e.error?e.error:"Failed to apply template")}let d=await l.json(),c=v(d&&"object"==typeof d&&"failed"in d?d.failed:null);if(c.length>0){let e=c.map(e=>{let t=ej.current.find(t=>t.id===e.id);return(null==t?void 0:t.operationName)||e.id.slice(0,8)});o("Template Not Applied","Could not save: ".concat(e.join(", ")));return}let m=e=>{var t,n,a;let r=s.find(t=>t.id===e.id);return r?{...e,operationDescription:null!==(t=r.operationDescription)&&void 0!==t?t:e.operationDescription,complexity:r.complexity,estimatedTime:null!==(n=r.estimatedTime)&&void 0!==n?n:e.estimatedTime,customInstructions:null!==(a=r.customInstructions)&&void 0!==a?a:e.customInstructions}:e},p=u.map(m);g(p),eo.current=eo.current.map(m),eE(p),ek(e=>e+1);let x="string"==typeof(null===(n=s[0])||void 0===n?void 0:n.id)?s[0].id:null;x&&B(x)}catch(e){p.k.error("Error loading template",{templateId:t.id,error:e instanceof Error?e.message:String(e)}),o("Template Not Applied",e instanceof Error?e.message:"Failed to apply template")}finally{K(!1)}}},eq=async(e,t)=>{let n=u.filter(e=>!(0,m.EK)({operationName:e.operationName,catalogType:e.opCatalogType}));if(!e.trim()||0===n.length)return!1;let a=new Date().toISOString(),r=[...J,{id:crypto.randomUUID(),name:e.trim(),description:t.trim()||"".concat(n.length," operations"),operations:n.map(e=>({operationName:e.operationName,operationDescription:e.operationDescription,complexity:e.complexity||"medium",estimatedTime:e.estimatedTime?parseFloat(e.estimatedTime):null,customInstructions:e.customInstructions})),isDefault:!1,createdAt:a,updatedAt:a}];$(null);try{let e=await fetch("/api/admin/system/operation-templates",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({templates:r})});if(e.ok)return G(r),!0;{let t=401===e.status?"You don't have permission to save templates":"Failed to save template (".concat(e.status,")");return $(t),!1}}catch(e){return p.k.error("Error saving template",{error:e instanceof Error?e.message:String(e)}),$("Network error â could not save template"),!1}},eB=async e=>{try{(await fetch("/api/admin/system/operation-templates",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({templates:e})})).ok&&G(e)}catch(e){p.k.error("Error persisting templates",{error:e instanceof Error?e.message:String(e)})}},eZ=async(e,t,n)=>{if(!t.trim())return;let a=new Date().toISOString(),r=J.map(r=>r.id===e?{...r,name:t.trim(),description:n.trim(),updatedAt:a}:r);await eB(r)},eH=async e=>{let t=J.filter(t=>t.id!==e);await eB(t)},eW=(0,r.useCallback)(async()=>{if(D.current)return!1;ey.current&&(clearTimeout(ey.current),ey.current=null),ev.current&&await ev.current;let t=Array.from(eb.current.entries());if(0===t.length)return!0;eb.current.clear(),eC(!1);let n=t.map(e=>{let[t,n]=e;return function(e,t){let n={id:e};for(let[e,a]of Object.entries(t))y.has(e)&&void 0!==a&&(n[e]=a);return n}(t,n)}).filter(e=>Object.keys(e).length>1);if(0===n.length)return!0;let a=n.map(e=>String(e.id)),r=(async()=>{eu(e=>{let t={...e};for(let e of a)t[e]=!0;return t});try{let t=await fetch("/api/admin/build-orders/".concat(e.id,"/operations"),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({operations:n})});if(!t.ok){let e=await t.json().catch(()=>({})),n="object"==typeof e&&e&&"error"in e&&"string"==typeof e.error?e.error:"Failed to save operations";if(t.status>=400&&t.status<500)return eM(a),o("Save Failed",n),eT(!1),!1;throw Error(n)}let i=await t.json(),s=v(i&&"object"==typeof i&&"failed"in i?i.failed:null),l=new Set(s.map(e=>e.id));if(s.length>0){let e=s.map(e=>{let t=ej.current.find(t=>
1t.id===e.id);return(null==t?void 0:t.operationName)||e.id.slice(0,8)});o("Save Failed","Could not save: ".concat(e.join(", "))),eM(s.map(e=>e.id))}for(let e of n){var r;let t=String(e.id);if(l.has(t))continue;let n=null!==(r=eN.current.get(t))&&void 0!==r?r:ej.current.find(e=>e.id===t);n&&eN.current.set(t,{...n,...e})}return eT(0===s.length),0===s.length}catch(n){p.k.error("Error saving operations",{opIds:a,error:n instanceof Error?n.message:String(n)});let e=a.map(e=>{var t;return(null===(t=ej.current.find(t=>t.id===e))||void 0===t?void 0:t.operationName)||e.slice(0,8)});for(let[n,a]of(o("Save Failed","Could not save: ".concat(e.join(", "))),t))eb.current.set(n,{...a,...eb.current.get(n)});return eC(!0),eT(!1),!1}finally{eu(e=>{let t={...e};for(let e of a)delete t[e];return t})}})();ev.current=r;try{return await r}finally{ev.current===r&&(ev.current=null),eb.current.size>0&&!ey.current&&(ey.current=setTimeout(()=>{ey.current=null,eW()},5e3))}},[e.id,eM,o]),eQ=(0,r.useCallback)((e,t)=>{var n;if(D.current)return;let a=null!==(n=eb.current.get(e))&&void 0!==n?n:{};eb.current.set(e,{...a,...t}),eC(!0),g(n=>n.map(n=>n.id===e?{...n,...t}:n)),eo.current=eo.current.map(n=>n.id===e?{...n,...t}:n),ey.current||(ey.current=setTimeout(()=>{ey.current=null,eW()},5e3))},[eW]),eJ=(0,r.useCallback)(async()=>{await eW(),i()},[eW,i]),eG=(0,r.useCallback)(e=>{q&&q!==e&&eW(),B(e)},[eW,q]),eV=async t=>{var n,a;if(D.current)return!1;let r=t.operationName.trim();if(!r)return!1;let i={operationName:r,operationDescription:t.operationDescription||void 0,workStepId:t.workStepId||void 0,complexity:null!==(n=t.complexity)&&void 0!==n?n:"medium",estimatedTime:t.estimatedTime,after:t.after,startsWith:t.startsWith};_(!0);try{let t=await fetch("/api/admin/build-orders/".concat(e.id,"/operations"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!t.ok){let e=await t.json();throw Error(e.error||"Failed to add operation")}let n=await t.json();return await eF(),(null===(a=n.operation)||void 0===a?void 0:a.id)&&B(n.operation.id),!0}catch(t){return p.k.error("Error adding operation",{buildOrderId:e.id,operationName:r,error:t instanceof Error?t.message:String(t)}),o("Operation Add Failed",t instanceof Error?t.message:"Failed to add operation"),!1}finally{_(!1)}},eK=async t=>{eb.current.delete(t);let n=u.findIndex(e=>e.id===t);_(!0);try{let a=await fetch("/api/admin/build-orders/".concat(e.id,"/operations/").concat(t),{method:"DELETE"});if(!a.ok){let e=await a.json();throw Error(e.error||"Failed to delete")}let r=u.filter(e=>e.id!==t);eo.current=eo.current.filter(e=>e.id!==t),g(r),q===t&&(0===r.length?B(null):n<r.length?B(r[n].id):B(r[r.length-1].id))}catch(e){p.k.error("Error deleting operation",{opId:t,error:e instanceof Error?e.message:String(e)}),o("Operation Not Deleted",e instanceof Error?e.message:"Failed to delete operation")}finally{_(!1)}},eY=async function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(D.current)return!1;_(!0);try{let n=await fetch("/api/admin/build-orders/".concat(e.id,"/operations/populate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.force?{force:!0}:{})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error("object"==typeof e&&e&&"error"in e&&"string"==typeof e.error?e.error:"Failed to populate operations")}return await eF(),!0}catch(t){return p.k.error("Error populating operations",{buildOrderId:e.id,error:t instanceof Error?t.message:String(t)}),o("Populate Failed",t instanceof Error?t.message:"Failed to populate operations"),!1}finally{_(!1)}},e$=(0,r.useMemo)(()=>u.map(e=>{var t;if(e.quoteTimeApplication)return e;let n=Z.find(t=>t.id===e.workStepId)||Z.find(t=>t.name===e.operationName);return{...e,quoteTimeApplication:null!==(t=null==n?void 0:n.timeApplication)&&void 0!==t?t:null}}),[u,Z]),eX=(0,r.useMemo)(()=>(function(e){let t=[];for(let r of e){var n,a;if(!(0,m.EK)({operationName:r.operationName,catalogType:null!==(a=r.catalogType)&&void 0!==a?a:r.opCatalogType})){if(!(r.libraryOperationId||(null===(n=r.customInstructions)||void 0===n?void 0:n.trim()))){t.push({operationId:r.id,operationName:r.operationName,reason:"no_instructions"});continue}!function(e){var t;if(x({quoteEstimatedSeconds:e.quoteEstimatedSeconds,workStepTimeStandard:e.workStepTimeStandard,complexity:e.complexity,defaultSecsPerUnit:null!==(t=e.estimatedSecsPerUnit)&&void 0!==t?t:e.defaultSecsPerUnit,manualOverrideSeconds:e.manualOverrideSeconds}).perUnitSeconds>0)return!0;
1if(null==e.estimatedTime||""===e.estimatedTime)return!1;let n="number"==typeof e.estimatedTime?e.estimatedTime:parseFloat(String(e.estimatedTime));return Number.isFinite(n)&&n>0}(r)&&t.push({operationId:r.id,operationName:r.operationName,reason:"no_time_source"})}}return{complete:0===t.length,incomplete:t}})(u.map(e=>{var t,n,a;let r=Z.find(t=>t.id===e.workStepId)||Z.find(t=>t.name===e.operationName);return{id:e.id,operationName:e.operationName,opCatalogType:e.opCatalogType,customInstructions:e.customInstructions,libraryOperationId:null!==(t=e.libraryOperationId)&&void 0!==t?t:null,quoteEstimatedSeconds:e.quoteEstimatedSeconds,estimatedSecsPerUnit:null!==(n=e.estimatedSecsPerUnit)&&void 0!==n?n:null,estimatedTime:e.estimatedTime,complexity:e.complexity,workStepTimeStandard:null!==(a=null==r?void 0:r.timeStandard)&&void 0!==a?a:null,manualOverrideSeconds:e.manualTimeOverride&&e.estimatedTime?Math.round(60*parseFloat(e.estimatedTime)):null}})),[u,Z]),e0=(0,r.useMemo)(()=>{let e=new Map;for(let t of eX.incomplete)e.set(t.operationId,t.reason);return e},[eX]),e1=async()=>{if(!D.current&&(!(C>0)||await s.confirm({title:"Unresolved AI Issues",description:"".concat(C," AI issues are unresolved. Approve anyway?"),confirmText:"Approve Anyway",variant:"warning"}))&&await eW()){if(!eX.complete){eg(eX.incomplete),o("Cannot Approve",eX.incomplete.map(e=>e.operationName).join(", "));return}eh(!0);try{let t=async t=>fetch("/api/admin/work-instructions-review/".concat(e.id,"/approve"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({approvalJustification:t,expectedOperations:(0,m.dS)(eo.current)})}),n=await t();if(422===n.status){let e=await n.json().catch(()=>({})),a=e&&"object"==typeof e&&"incompleteOperations"in e&&Array.isArray(e.incompleteOperations)?e.incompleteOperations.flatMap(e=>{if(!e||"object"!=typeof e)return[];let t="operationId"in e?e.operationId:void 0,n="operationName"in e?e.operationName:void 0;return"string"!=typeof t||"string"!=typeof n?[]:[{operationId:t,operationName:n}]}):[];if(a.length>0){eg(a),o("Cannot Approve",a.map(e=>e.operationName).join(", "));return}if(e&&"object"==typeof e&&"requiresJustification"in e&&e.requiresJustification){let e=await s.prompt({title:"Approve Setup Variance",description:"Setup estimate differs from the quote target. Enter a justification to approve anyway.",inputLabel:"Justification",multiline:!0,required:!0});if(!e)return;n=await t(e)}}if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error?e.error:"Failed to approve")}l("Approved","Work instructions approved."),null==a||a(),i()}catch(t){p.k.error("Error approving work instructions",{buildOrderId:e.id,error:t instanceof Error?t.message:String(t)}),o("Approval Failed",t instanceof Error?t.message:"Failed to approve")}finally{eh(!1)}}},e2=e$.find(e=>e.id===q)||null,e5=(0,r.useMemo)(()=>(0,m.hE)(e$,e.quantity),[e$,e.quantity]),e3=function(e){let{setupEstimateMinutes:t,quoteTargetMinutes:n,threshold:a}=e;if(!(n>0))return{tone:"neutral",label:"No Quote Target",requiresJustification:!1,variancePercent:null};let r=t/n-1,i=Math.abs(r),s=Math.round(1e3*r)/10,o=r>=0?"Over":"Under",l="".concat(r>=0?"+":"-").concat(Math.round(Math.abs(s)),"%");return i>a?{tone:"danger",label:"".concat(l," ").concat(o," â Needs Justification"),requiresJustification:!0,variancePercent:s}:i<=.02?{tone:"positive",label:"On Target",requiresJustification:!1,variancePercent:s}:{tone:"warning",label:"".concat(l," ").concat(o),requiresJustification:!1,variancePercent:s}}({setupEstimateMinutes:e5.setupEstimateMinutes,quoteTargetMinutes:e5.quoteTargetMinutes,threshold:ec}),e4=(0,r.useMemo)(()=>new Set(Object.keys(ep)),[ep]),e6=e4.size>0,e9=(0,r.useCallback)(()=>S(e=>e+1),[]);return{operations:u,operationsForTotals:e$,allOps:eo.current,routing:b,isLoading:R,isSaving:L,error:z,refetch:eF,workSteps:Z,isLoadingWorkSteps:W,quoteTier:el,varianceThreshold:ec,refDocs:eO,selectedOpId:q,selectedOp:e2,selectOp:eG,queueOpSave:eQ,flushPending:eW,savingOpIds:e4,formEpoch:ew,saveState:e6?"saving":eS?"dirty":eI?"saved":"idle",close:eJ,addOperation:eV,deleteOperation:eK,reorder:t=>
1{if(D.current)return;let n=new Map(u.map(e=>[e.id,e])),a=t.flatMap(e=>{let t=n.get(e);return t?[t]:[]});g(a),fetch("/api/admin/build-orders/".concat(e.id,"/operations"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({operationIds:(0,h.J)(eo.current.map(e=>e.id),a.map(e=>e.id))})}).then(t=>{t.ok||(p.k.error("Failed to reorder operations",{status:t.status,buildOrderId:e.id}),g(u),eF())}).catch(e=>{p.k.error("Network error reordering operations",{error:String(e)}),g(u)})},populate:eY,templates:{list:J,isLoading:V,saveError:Y,clearSaveError:()=>$(null),load:eU,saveAs:eq,update:eZ,remove:eH},copyFromBo:{results:X,search:et,setSearch:e_,isLoading:ea,isCopying:ei,fetchCandidates:eP,copy:ez},reviewSnapshot:()=>(0,m.dS)(eo.current),completeness:eX,incompleteReasonByOpId:e0,estimateTotals:e5,varianceVerdict:e3,approve:e1,isApproving:ex,approveBlockers:ef,ai:{active:N,setActive:w,canRun:M,canSend:A,openIssues:C,setOpenIssues:I,assumptionCount:T,setAssumptionCount:E,reviewEpoch:k,bumpReviewEpoch:e9}}}(R,{onApproved:L,onClose:P}),H=Z.ai.active,W=function(e,t,n){var a,i,s,o,l;let{showError:d}=(0,c.pm)(),[m,p]=(0,r.useState)(null!==(a=null==t?void 0:t.edges)&&void 0!==a?a:[]),[u,x]=(0,r.useState)(null!==(i=null==t?void 0:t.mode)&&void 0!==i?i:"implicit"),[h,f]=(0,r.useState)(null!==(s=null==t?void 0:t.validation)&&void 0!==s?s:null),[g,b]=(0,r.useState)(null!==(o=null==t?void 0:t.criticalPathMinutes)&&void 0!==o?o:null),[y,v]=(0,r.useState)(null),[N,w]=(0,r.useState)(!1),k=(0,r.useRef)(null!==(l=null==t?void 0:t.edges)&&void 0!==l?l:[]),S=(0,r.useRef)(null),C=(0,r.useRef)(null),I=(0,r.useRef)(n.locked);I.current=n.locked;let T=(0,r.useRef)(n.onSaved);T.current=n.onSaved;let E=(0,r.useCallback)(e=>{var t,n,a,r;let i=null!==(t=null==e?void 0:e.edges)&&void 0!==t?t:[];k.current=i,p(i),x(null!==(n=null==e?void 0:e.mode)&&void 0!==n?n:"implicit"),f(null!==(a=null==e?void 0:e.validation)&&void 0!==a?a:null),b(null!==(r=null==e?void 0:e.criticalPathMinutes)&&void 0!==r?r:null),v(null)},[]);(0,r.useEffect)(()=>{E(t)},[e,t,E]);let M=(0,r.useCallback)(async t=>{w(!0);try{var n,a,r,i,s,o;let l=await fetch("/api/admin/build-orders/".concat(e,"/operations/dependencies"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({edges:t.map(e=>({operationId:e.operationId,dependsOnOperationId:e.dependsOnOperationId,dependencyType:e.dependencyType}))})}),c=await l.json().catch(()=>({}));if(!l.ok||!c.routing){let e=null!==(i=c.code)&&void 0!==i?i:"ROUTING_FAILED",t=null!==(s=c.error)&&void 0!==s?s:"The routing could not be saved.";return v({code:e,message:t,operationIds:null===(r=c.details)||void 0===r?void 0:null===(a=r[0])||void 0===a?void 0:a.operationIds}),d(null!==(o=j[e])&&void 0!==o?o:"Routing Not Saved",t),p(k.current),!1}return k.current=c.routing.edges,p(c.routing.edges),x(c.routing.mode),f(c.routing.validation),b(c.routing.criticalPathMinutes),v(null),null===(n=T.current)||void 0===n||n.call(T,c.routing),!0}catch(e){return v({code:"NETWORK",message:e instanceof Error?e.message:"Network error"}),d("Routing Not Saved","Check your connection and try again."),p(k.current),!1}finally{w(!1)}},[e,d]);return{edges:m,mode:u,routingError:y,saving:N,setEdges:(0,r.useCallback)(async e=>{if(I.current)return d("Editing Locked","Wait for the AI run to finish before changing the routing."),!1;if(p(e),S.current)return C.current=e,S.current;let t=(async()=>{let t=await M(e);for(;C.current;){let e=C.current;C.current=null,t=await M(e)}return t})();S.current=t;try{return await t}finally{S.current=null}},[M,d]),seed:E,criticalPathMinutes:g,validation:h}}(R.id,Z.routing,{locked:H,onSaved:()=>{Z.refetch()}}),{setEdges:Q}=W,{queueOpSave:J,flushPending:V,selectOp:K}=Z,[Y,$]=(0,r.useState)(null),X=(0,r.useCallback)(e=>{$(e),K(e)},[K]),[ee,et]=(0,r.useState)(null),[en,er]=(0,r.useState)("parts"),[ei,es]=(0,r.useState)(0),eo=(0,r.useRef)(null),el=(0,r.useRef)(null),ed=(Z.allOps.length>0?Z.allOps:Z.operations).filter(e=>!(0,m.$1)({operationName:e.operationName,catalogType:e.opCatalogType})),ec=(0,r.useMemo)(()=>{var e;return null!==(e=ed.find(e=>e.id===Y))&&void 0!==e?e:null},[ed,Y]),ep=R.quantity||1,eu=(0,r.useMemo)(()=>ed.map(e=>eH(e,ep)),[ed,ep]),ex=(0,r.useMemo)(()=>eQ(W.edges),[W.edges]),eh=(0,r.useMemo)(()=>(function(e,t){var n,a,r,i,s,o,l,d;let c=new Map(e.map(e=>[e.id,e])),m=new Map,p=new Map;for(let t of e)p.set(t.id,0);for(let e of t)c.has(e.operationId)&&c.has(e.dependsOnOperationId)&&(m.set(e.operationId,[...null!==(n=m.get(e.operationId))&&void 0!==n?n:[],e]),p.set(e.operationId,(null!==(a=p.get(e.operationId))&&void 0!==a?a:0)+1));let u=e.filter(e=>0===p.get(e.id)).map(e=>e.id),x=[];for(;u.length;){let e=u.shift();for(let n of(x.push(e),t)){if(n.dependsOnOperationId!==e||!c.has(n.operationId))continue;let t=(null!==(r=p.get(n.operationId))&&void 0!==r?r:0)-1;p.set(n.operationId,t),0===t&&u.push(n.operationId)}}if(x.length!==e.length)return 0;let h=new Map,f=new Map,g=0;for(let e of x){let t=0;for(let n of null!==(s=m.get(e))&&void 0!==s?s:[]){let e="start_to_start"===n.dependencyType?null!==(o=h.get(n.dependsOnOperationId))&&void 0!==o?o:0:null!==(l=f.get(n.dependsOnOperationId))&&void 0!==l?l:0;e>t&&(t=e)}
1let n=t+Math.max(0,null!==(d=null===(i=c.get(e))||void 0===i?void 0:i.estimateMinutes)&&void 0!==d?d:0);h.set(e,t),f.set(e,n),n>g&&(g=n)}return Math.round(g)})(eu,ex),[eu,ex]),ef=(0,r.useMemo)(()=>(function(e,t){var n,a,r,i,s;let o=new Map,l=new Map;for(let e of t)"finish_to_start"===e.dependencyType&&(o.set(e.dependsOnOperationId,(null!==(n=o.get(e.dependsOnOperationId))&&void 0!==n?n:0)+1),l.set(e.operationId,(null!==(a=l.get(e.operationId))&&void 0!==a?a:0)+1));let d=0,c=0;for(let t of e)(null!==(r=o.get(t.id))&&void 0!==r?r:0)>=2&&(d+=1),(null!==(i=o.get(t.id))&&void 0!==i?i:0)===0&&(null!==(s=l.get(t.id))&&void 0!==s?s:0)>0&&(c+=1);return{branches:d,sinks:c}})(eu,ex),[eu,ex]),eg=(0,r.useMemo)(()=>{let e=new Map;for(let[t,n]of Z.incompleteReasonByOpId)e.set(t,"no_instructions"===n?"No Instructions":"No Time Source");return e},[Z.incompleteReasonByOpId]),eb=Z.operations.filter(e=>eg.has(e.id)).length,ey=(0,r.useCallback)(async e=>Q(e),[Q]),ev=(0,r.useCallback)((e,t)=>J(e,t),[J]),ej=(0,r.useCallback)(e=>z("Dependency Not Allowed",e),[z]),eN=(0,r.useRef)(null),ew=(0,r.useCallback)(e=>{var t;null===(t=eN.current)||void 0===t||t.call(eN,e)},[]),eS=(0,r.useCallback)(async e=>{let t=ed.find(t=>t.id===e);t&&await _.confirm({title:"Delete operation?",description:'"'.concat(t.operationName,'" will be removed. Steps that waited on it will wait on its predecessors instead.'),confirmText:"Delete",variant:"destructive"})&&(await Z.deleteOperation(e),await Z.refetch())},[_,ed,Z]);eN.current=eS;let eC=(0,r.useCallback)(async e=>{await Z.addOperation({operationName:e.operationName,after:e.after}),await Z.refetch()},[Z]),[eT,eE]=(0,r.useState)(!1),eM=(0,r.useCallback)(async()=>{if(await V()&&await _.confirm({title:"Approve Active WI Reuse?",description:"Approve the Active WI already loaded for this part revision. Review the instructions and estimate first.",confirmText:"Approve Reuse"})){eE(!0);try{let e=e=>fetch("/api/admin/build-orders/".concat(R.id,"/work-instruction/reuse"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({approvalJustification:e,expectedOperations:Z.reviewSnapshot()})}),t=await e(),n=await t.json();if(422===t.status&&n.requiresJustification){let a=await _.prompt({title:"Approve Setup Variance",description:"Setup estimate differs from the quote target. Enter a justification to approve reuse.",inputLabel:"Justification",multiline:!0,required:!0});if(!a)return;t=await e(a),n=await t.json()}if(!t.ok)throw Error(n.error||"Could not approve Active WI reuse");U("Active WI Approved"),null==L||L(),P()}catch(e){z("Reuse Failed",e instanceof Error?e.message:"Try again.")}finally{eE(!1)}}},[R.id,_,V,L,P,Z,z,U]),eA=(0,r.useCallback)(async()=>{if(await _.confirm({title:"Populate operations?",description:"Adds operations from the matching library work instruction, a prior build order, or the quote. Existing operations are kept.",confirmText:"Populate"}))try{await Z.populate(),await Z.refetch(),U("Operations Populated")}catch(e){z("Populate Failed",e instanceof Error?e.message:"Try again.")}},[_,Z,z,U]),eF=null!==(k=null!==(w=null!==(N=null===(t=W.routingError)||void 0===t?void 0:t.message)&&void 0!==N?N:null===(l=W.validation)||void 0===l?void 0:null===(n=l.errors[0])||void 0===n?void 0:n.message)&&void 0!==w?w:null===(g=W.validation)||void 0===g?void 0:null===(u=g.warnings[0])||void 0===u?void 0:u.message)&&void 0!==k?k:null,eD=!W.routingError&&(null===(S=null===(b=W.validation)||void 0===b?void 0:b.ok)||void 0===S||S),eP=[null!==(C=R.inventreeBoNumber)&&void 0!==C?C:R.id.slice(0,8),null!==(I=R.partNumber)&&void 0!==I?I:R.partName,"Qty ".concat(R.quantity),null!=R.wipBinNumber?"WIP Bin ".concat(R.wipBinNumber):null].filter(Boolean).join(" \xb7 "),eL=(0,r.useCallback)(()=>{Promise.resolve(Z.flushPending()).finally(P)},[P,Z]),e_=B?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(eR,{locked:H,workSteps:Z.workSteps,selectedOpId:Y,selectedOpName:null!==(T=null==ec?void 0:ec.operationName)&&void 0!==T?T:null,onAddOperation:eC,onPopulate:eA,onAutoLayout:()=>es(e=>e+1)}),(0,a.jsx)(e9,{open:ee,badges:{checks:eb||void 0},onToggle:e=>et(t=>t===e?null:e)}),ee?(0,a.jsxs)(e8,{title:e7[ee],onClose:()=>et(null),children:["notes"===ee?(0,a.jsx)(q,{buildOrderId:R.id,salesOrderNumber:null!==(E=R.salesOrderNumber)&&void 0!==E?E:void 0,orderSource:null!==(M=R.orderSource)&&void 0!==M?M:void 0}):null,"bom"===ee?(0,a.jsxs)("div",{children:[(0,a.jsx)("div",{className:"mb-3 inline-flex rounded-[2px] border admin-border",children:["parts","connectors"].map(e=>(0,a.jsx)("button",{type:"button",onClick:()=>er(e),className:"px-3 py-1 text-[12px] ".concat(en===e?"bg-mp-blue text-white":"admin-text-secondary"),children:"parts"===e?"Parts":"Connectors"},e))}),"parts"===en?(0,a.jsx)(ea,{buildOrderId:R.id}):(0,a.jsx)(G,{buildOrderId:R.id})]}):null,"files"===ee?(0,a.jsx)(em,{buildOrderId:R.id,salesOrderNumber:null!==(O=R.salesOrderNumber)&&void 0!==O?O:void 0,orderSource:null!==(A=R.orderSource)&&void 0!==A?A:void 0}):null,"handbook"===ee?(0,a.jsx)(ek,{buildOrderId:R.id}):null,"tools"===ee?(0,a.jsx)(eI,{buildOrderId:R.id,buildOrderName:null!==(F=R.inventreeBoNumber)&&void 0!==F?F:void 0}):null,"checks"===ee?(0,a.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"wi-checks-panel",children:[0===eb?(0,a.jsx)("div",{className:"text-[13px] admin-text-muted",children:"Every manufacturing operation has instructions and a time source."}):Z.operations.filter(e=>eg.has(e.id)).map(e=>(0,a.jsxs)("button",{type:"button",className:"flex items-center gap-2 rounded-[2px] border admin-border px-2 py-1.5 text-left text-[13px] hover:admin-bg-tertiary",onClick:()=>{X(e.id),et(null)},children:[(0,a.jsx)("span",{className:"font-brandMono text-[11px] admin-text-muted",children:e.sequenceNumber}),(0,a.jsx)("span",{className:"truncate admin-text-primary",children:e.operationName}),(0,a.jsx)("span",{className:"ml-auto rounded-[2px] bg-mp-warning/10 px-1.5 text-[10px] font-semibold text-mp-warning",children:eg.get(e.id)})]},e.id)),eF?(0,a.jsx)("div",{className:"mt-2 text-[12px] admin-text-secondary",children:eF}):null]}):null]}):null]}):null,[ez,eU]=(0,r.useState)(null);(0,r.useEffect)(()=>{eU(document.body)},[]);let eq=(0,a.jsx)("div",{className:"fixed inset-0 z-[100] flex items-center justify-center overflow-hidden bg-black bg-opacity-50","data-testid":"wi-setup-modal","data-modal-surface":!0,children:(0,a.jsx)("div",{ref:el,className:"relative flex h-[95vh] max-h-[95vh] w-[98vw] max-w-[1800px] flex-col overflow-hidden admin-bg-secondary rounded-[4px]","data-modal-surface":!0,children:(0,a.jsxs)(s.tV,{children:[(0,a.jsx)(tt,{title:"Work Instruction Setup",subtitle:eP,setupMinutes:Z.estimateTotals.setupEstimateMinutes,quoteMinutes:Z.estimateTotals.quoteTargetMinutes,verdict:Z.varianceVerdict,criticalPathMinutes:null!==(D=W.criticalPathMinutes)&&void 0!==D?D:eh,saveState:Z.saveState,onSaveNow:()=>void Z.flushPending(),onClose:eL,locked:H}),Z.error?(0,a.jsx)("div",{className:"border-b border-mp-danger/30 bg-mp-danger/10 px-6 py-2 text-[13px] text-mp-danger",children:Z.error}):null,(0,a.jsxs)("div",{className:"grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)] overflow-hidden ".concat(B?"grid-cols-[minmax(0,1fr)_360px]":"grid-cols-1"),children:[B?(0,a.jsx)("div",{className:"relative h-full min-h-0 min-w-0 overflow-hidden border-r admin-border",children:Z.isLoading&&0===ed.length?(0,a.jsx)("div",{className:"flex h-full items-center justify-center text-[13px] admin-text-muted",children:"Loading operationsâ¦"}):(0,a.jsx)(eG,{containerRef:eo,operations:ed,edges:W.edges,selectedOpId:Y,locked:H,incompleteReasonByOpId:eg,boQuantity:ep,onSelectOp:X,onEdgesChange:e
1y,onEdgeError:ej,onRequestDeleteOp:ew,overlays:e_},ei)}):(0,a.jsx)(te,{operations:ed,incompleteReasonByOpId:eg,estimateMinutesFor:e=>eW(e,ep)}),B?(0,a.jsxs)("aside",{className:"flex h-full min-h-0 flex-col overflow-hidden admin-bg-secondary","data-testid":"wi-assistant-rail",children:[(0,a.jsx)("div",{className:"flex items-center gap-2 border-b admin-border px-4 py-2.5 text-[13px] font-semibold admin-text-primary",children:"Assistant"}),(0,a.jsxs)("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[(0,a.jsx)(o.W,{flush:!0,runsUrl:"/api/admin/build-orders/".concat(R.id,"/agent-runs"),canRun:Z.ai.canRun,canSend:Z.ai.canSend,runKind:"wi_build",reviseKind:"wi_revise",hasPriorRunLabel:"AI",onRunStateChange:e=>{Z.ai.setActive(e),e||(Z.refetch(),Z.ai.bumpReviewEpoch())},summaryLinks:[{label:"assumption",count:Z.ai.assumptionCount,href:"#wi-assumptions"},{label:"issue",count:Z.ai.openIssues,href:"#wi-issues"}]}),(0,a.jsx)("div",{className:"border-t admin-border px-4 py-3",children:(0,a.jsx)(eO,{buildOrderId:R.id,disabled:H,refreshKey:Z.ai.reviewEpoch,onOpenIssuesChange:Z.ai.setOpenIssues,onAssumptionsChange:Z.ai.setAssumptionCount})})]})]}):null]}),(0,a.jsx)("div",{className:"flex justify-end px-4 py-2",children:(0,a.jsx)("button",{type:"button",onClick:()=>void eM(),disabled:H||eT||!eD||Z.approveBlockers.length>0,className:"rounded border px-3 py-1.5 text-sm disabled:opacity-50",children:eT?"Approvingâ¦":"Approve Active WI Reuse"})}),(0,a.jsx)(tn,{operationCount:Z.operations.length,branchCount:ef.branches,graphValid:eD,graphMessage:eF,unauthoredCount:eb,onShowUnauthored:()=>et("checks"),onClose:eL,onApprove:()=>void Z.approve(),approveDisabled:H||!eD||Z.approveBlockers.length>0,isApproving:Z.isApproving}),ec&&B?(0,a.jsx)(e4,{operation:ec,operations:ed,edges:W.edges,locked:H,boQuantity:ep,quoteTier:Z.quoteTier,workSteps:Z.workSteps,isSaving:Z.savingOpIds.has(ec.id),onSave:ev,onFlush:V,onDelete:e=>void eS(e),onClose:()=>X(null),onEdgesChange:ey,onEdgeError:ej,canvasRef:eo,hostRef:el}):null]})})});return ez?(0,i.createPortal)(eq,ez):eq}function ti(e){return(0,l.GF)()?(0,a.jsx)(tr,{...e}):(0,a.jsx)(ts,{...e})}function ts(e){return(0,a.jsx)(ta,{buildOrderId:e.buildOrder.id,children:(0,a.jsx)(tr,{...e})})}var to=ti},78027:function(e,t,n){n.d(t,{LotAcceptanceSamplingCalculator:function(){return v}});var a=n(57437),r=n(2265);let i=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23];function s(e){if(e<.5)return Math.log(Math.PI/Math.sin(Math.PI*e))-s(1-e);let t=e-1,n=i[0],a=t+7+.5;for(let e=1;e<i.length;e+=1)n+=i[e]/(t+e);return .5*Math.log(2*Math.PI)+(t+.5)*Math.log(a)-a+Math.log(n)}function o(e,t){return t<0||t>e?-1/0:s(e+1)-s(t+1)-s(e-t+1)}function l(e,t,n,a){let r=Math.min(a,t,n),i=o(e,n),s=0;for(let a=0;a<=r;a+=1)a<n-(e-t)||(s+=Math.exp(o(t,a)+o(e-t,n-a)-i));return s}let d=[.9,.95,.975,.99,.995,.999],c=[.001,.002,.005,.01,.02,.05,.1],m=[0,1,2,3];function p(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return"".concat((100*e).toFixed(t),"%")}function u(e){let t=100*e,n=Number.isInteger(t)?0:1;return"".concat(t.toFixed(n),"%")}function x(e){return"".concat((100*e).toFixed(3),"%")}function h(e){return e<.01?"".concat((100*e).toFixed(1),"%"):"".concat((100*e).toFixed(0),"%")}function f(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0}).format(e)}function g(e,t){return t.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t)}let b=Math.log(1e4);function y(e){let{result:t,variant:n}=e,r="public"===n,i=Math.min(t.lotSize,Math.max(Math.ceil(1.6*t.finiteSampleSize),10)),s=Math.max(1,i-1),o=e=>18+(1-Math.min(1,Math.max(0,e)))*132,d=e=>34+(e-1)/s*468,c=Array.from({length:121},(e,n)=>{let a=Math.max(1,Math.min(i,Math.round(1+n/120*(i-1)))),r=1-l(t.lotSize,t.defectThreshold,a,t.allowedDefects);return{x:d(a),y:o(r)}}).map((e,t)=>"".concat(0===t?"M":"L"," ").concat(e.x," ").concat(e.y)).join(" "),m=o(t.confidence),h=d(t.finiteSampleSize),g=o(t.actualConfidence),b=r?"fill-gray-500":"fill-gray-500 dark:fill-gray-400",y=r?"stroke-gray-300":"stroke-gray-300 dark:stroke-gray-600";return(0,a.jsxs)("div",{className:r?"rounded-lg border border-gray-200 bg-white p-3 shadow-sm":"rounded-[4px] border admin-border admin-bg-secondary dark:bg-zinc-900 p-3",children:[(0,a.jsxs)("svg",{viewBox:"0 0 ".concat(520," ").concat(180),className:"w-full h-auto",role:"img","aria-labelledby":"
1confidence-curve-title",children:[(0,a.jsx)("title",{id:"confidence-curve-title",children:"Confidence reached vs. units inspected"}),[0,.5,1].map(e=>(0,a.jsx)("text",{x:28,y:o(e)+3,textAnchor:"end",fontSize:"9",className:b,children:p(e,0)},e)),(0,a.jsx)("text",{x:34,y:170,textAnchor:"start",fontSize:"9",className:b,children:"0"}),(0,a.jsxs)("text",{x:502,y:170,textAnchor:"end",fontSize:"9",className:b,children:[f(i)," units"]}),(0,a.jsx)("line",{x1:34,y1:150,x2:502,y2:150,className:y,strokeWidth:"1"}),(0,a.jsx)("line",{x1:34,y1:18,x2:34,y2:150,className:y,strokeWidth:"1"}),(0,a.jsx)("line",{x1:34,y1:m,x2:502,y2:m,className:"stroke-amber-500",strokeWidth:"1.5",strokeDasharray:"6 5"}),(0,a.jsxs)("text",{x:502,y:m-5,textAnchor:"end",fontSize:"9",className:"fill-amber-600",children:[u(t.confidence)," target"]}),(0,a.jsx)("path",{d:c,fill:"none",className:"stroke-mp-orange",strokeWidth:"3"}),(0,a.jsx)("line",{x1:h,y1:18,x2:h,y2:150,className:r?"stroke-gray-500":"stroke-gray-500 dark:stroke-gray-400",strokeWidth:"1",strokeDasharray:"4 4"}),(0,a.jsx)("circle",{cx:h,cy:g,r:"5",className:"fill-mp-orange"})]}),(0,a.jsxs)("div",{className:"mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs ".concat(r?"text-gray-700":"admin-text-primary"),children:[(0,a.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,a.jsx)("span",{className:"h-0.5 w-4 bg-mp-orange"}),"Confidence as sample size grows"]}),(0,a.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,a.jsx)("span",{className:"h-0 w-4 border-t-2 border-dashed border-amber-500"}),"Your target confidence"]}),(0,a.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,a.jsx)("span",{className:"h-2.5 w-2.5 rounded-full bg-mp-orange"}),"Your plan: ",f(t.finiteSampleSize)," units inspected â ",x(t.actualConfidence)," confidence"]})]})]})}function v(e){var t;let{variant:n="admin"}=e,i="public"===n,s=i?"rounded-lg border border-gray-200 bg-white p-4 shadow-sm":"rounded-[4px] border admin-border admin-bg-secondary dark:bg-zinc-900 p-4",v=i?"text-gray-950":"admin-text-primary",j=i?"text-gray-600":"admin-text-secondary",N=i?{lotSize:"Lot size (N)",confidence:"Confidence target",defectRate:"Defect rate to catch (p)",allowedDefects:"Allowed defects (c)",defectThreshold:"Defect threshold (D)",infiniteSampleSize:"Infinite-lot sample size",actualConfidence:"Actual confidence at sample size"}:{lotSize:"Lot size N",confidence:"Confidence",defectRate:"Defect rate to rule out (p)",allowedDefects:"Defects allowed (c)",defectThreshold:"Lot threshold D",infiniteSampleSize:"Infinite-population n",actualConfidence:"Actual confidence at n"},[w,k]=(0,r.useState)("1200"),[S,C]=(0,r.useState)(.99),[I,T]=(0,r.useState)(.01),[E,M]=(0,r.useState)(0),O=(0,r.useMemo)(()=>(function(e){let t=function(e){let t=Math.max(1,Math.floor(Number.isFinite(e.lotSize)?e.lotSize:1)),n=Math.max(0,Math.floor(Number.isFinite(e.allowedDefects)?e.allowedDefects:0));return{lotSize:t,confidence:e.confidence,defectRate:e.defectRate,allowedDefects:n}}(e),n=Math.ceil(t.defectRate*t.lotSize),a=function(e){let{lotSize:t,confidence:n,defectRate:a,allowedDefects:r}=e,i=1-n,s=Math.ceil(a*t);for(let e=r+1;e<t;e+=1)if(l(t,s,e,r)<=i)return{n:e,fullInspection:!1};return{n:t,fullInspection:!0}}(t),r=function(e){let t=1-e.confidence;for(let n=e.allowedDefects+1;n<=2e6;n+=1)if(function(e,t,n){let a=0;for(let r=0;r<=n;r+=1)a+=Math.exp(o(t,r)+r*Math.log(e)+(t-r)*Math.log(1-e));return a}(e.defectRate,n,e.allowedDefects)<=t)return n;return 2e6}({confidence:t.confidence,defectRate:t.defectRate,allowedDefects:t.allowedDefects}),i=1-l(t.lotSize,n,a.n,t.allowedDefects);return{...t,defectThreshold:n,finiteSampleSize:a.n,infiniteSampleSize:r,actualConfidence:i,sampleShare:a.n/t.lotSize,fullInspection:a.fullInspection}})({lotSize:Number(w),confidence:S,defectRate:I,allowedDefects:E}),[E,S,I,w]),A="ACCEPT on ".concat(O.allowedDefects," defects"),F="Inspect ".concat(f(O.finiteSampleSize)," of ").concat(f(O.lotSize),". If ").concat(0===(t=O.allowedDefects)?"none":"".concat(t," or fewer")," fail, you are ").concat(u(O.confidence)," confident the lot defect rate is below ").concat(h(O.defectRate),".");return(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsx)("div",{className:s,children:(0,a.jsxs)("div",{className:"grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4",children:[(0,a.jsxs)("div",{children:[(0,a.jsxs)("label",{className:"block",children:[(0,a.jsx)("span",{className:"text-xs font-medium ".concat(j),children:N.lotSize}),(0,a.jsx)("input",{type:"number",min:1,step:1,value:w,onChange:e=>k(e.target.value),className:"".concat(i?"mt-1 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-950 focus:outline-none focus:ring-2 focus:ring-mp-orange":"mt-1 w-full rounded-[2px] border admin-border admin-bg-secondary dark:bg-gray-900 px-3 py-2 text-sm admin-text-primary focus:outline-none focus:ring-2 focus:ring-mp-orange"," tabular-nums font-mono")})]}),(0,a.jsx)("input",{type:"range",min:0,max:1e3,step:1,"aria-label":"Quick-adjust lot quantity","aria-valuetext":"".concat(f(Number(w))," units"),value:Math.round(Math.log(Math.min(1e5,Math.max(10,Number(w)||10))/10)/b*1e3),onChange:e=>k(String(Math.round(10*Math.exp(Number(e.target.value)/1e3*b)))),className:"mt-2 w-full accent-mp-orange"}),(0,a.jsxs)("div",{className:"mt-1 flex justify-between text-[10px] ".concat(j),children:[(0,a.jsx)("span",{children:f(10)}),(0,a.jsx)("span",{children:f(1e5)})]})]}),(0,a.jsxs)("label",{className:"block",children:[(0,a.jsxs)("span",{className:"flex items-baseline justify-between text-xs font-medium ".concat(j),children:[N.confidence,(0,a.jsx)("span",{className:"font-mono ".concat(v),children:u(S)})]}),(0,a.jsx)("div",{className:"mt-1 h-[38px]"}),(0,a.jsx)("input",{type:"range",list:"confidence-ticks",min:Math.min(...d),max:Math.max(...d),step:"any","aria-valuetext":u(S),value:S,onChange:e=>C(g(Number(e.target.value),d)),className:"mt-2 w-full accent-mp-orange"}),(0,a.jsxs)("div",{className:"mt-1 flex justify-between text-[10px] ".concat(j),children:[(0,a.jsx)("span",{children:u(Math.min(...d))}),(0,a.jsx)("span",{children:u(Math.max(...d))})]}),(0,a.jsx)("datalist",{id:"confidence-ticks",children:d.map(e=>(0,a.jsx)("option",{value:e},e))})]}),(0,a.jsxs)("label",{className:"block",children:[(0,a.jsxs)("span",{className:"flex items-baseline justify-between text-xs font-medium ".concat(j),children:[N.defectRate,(0,a.jsx)("span",{className:"font-mono ".concat(v),children:h(I)})]}),(0,a.jsx)("div",{className:"mt-1 h-[38px]"}),(0,a.jsx)("input",{type:"range",list:"defect-rate-ticks",min:Math.min(...c),max:Math.max(...c),step:"any","aria-valuetext":h(I),value:I,onChange:e=>T(g(Number(e.target.value),c)),className:"mt-2 w-full accent-mp-orange"}),(0,a.jsxs)("div",{className:"mt-1 flex justify-between text-[10px] ".concat(j),children:[(0,a.jsx)("span",{children:h(Math.min(...c))}),(0,a.jsx)("span",{children:h(Math.max(...c))})]}),(0,a.jsx)("datalist",{id:"defect-rate-ticks",children:c.map(e=>(0,a.jsx)("option",{value:e},e))})]}),(0,a.jsxs)("label",{className:"block",children:[(0,a.jsxs)("span",{className:"flex items-baseline justify-between text-xs font-medium ".concat(j),children:[N.allowedDefects,(0,a.jsx)("span",{className:"font-mono ".concat(v),children:E})]}),(0,a.jsx)("div",{className:"mt-1 h-[38px]"}),(0,a.jsx)("input",{type:"range",list:"allowed-defects-ticks",min:Math.min(...m),max:Math.max(...m),step:1,"aria-valuetext":"".concat(E," allowed defects"),value:E,onChange:e=>M(Number(e.target.value)),className:"mt-2 w-full accent-mp-orange"}),(0,a.jsxs)("div",{className:"mt-1 flex justify-between text-[10px] ".concat(j),children:[(0,a.jsx)("span",{children:f(Math.min(...m))}),(0,a.jsx)("span",{children:f(Math.max(...m))})]}),(0,a.jsx)("datalist",{id:"allowed-defects-ticks",children:m.map(e=>(0,a.jsx)("option",{value:e},e))})]})]})}),(0,a.jsxs)("div",{className:"grid grid-cols-1 lg:grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)
1] gap-4",children:[(0,a.jsxs)("section",{className:s,children:[(0,a.jsx)("p",{className:"text-xs uppercase tracking-wide ".concat(j),children:"Units to inspect"}),(0,a.jsx)("div",{"data-testid":"lot-sampling-primary-n",className:"mt-2 text-4xl font-bold ".concat(v," tabular-nums font-mono"),children:f(O.finiteSampleSize)}),(0,a.jsx)("p",{className:"mt-2 text-sm font-semibold text-mp-positive dark:text-green-300",children:A}),(0,a.jsx)("p",{className:"mt-3 text-sm ".concat(j),children:F}),(0,a.jsx)("p",{className:"mt-3 text-xs ".concat(j),children:i?"This calculator estimates a lot-screening plan. It does not replace ANSI/ASQ Z1.4, customer plans, or C=0 Squeglia table lookups.":"This is a confidence calculator for internal QC screening. It does not replace ANSI/ASQ Z1.4, customer plans, or C=0 Squeglia table lookups."})]}),(0,a.jsx)("section",{className:"".concat(s," overflow-x-auto"),children:(0,a.jsx)("table",{className:"min-w-full text-sm",children:(0,a.jsxs)("tbody",{className:i?"divide-y divide-gray-200":"divide-y admin-divide",children:[(0,a.jsxs)("tr",{children:[(0,a.jsx)("th",{className:"py-2 pr-4 text-left font-medium ".concat(j),children:N.defectThreshold}),(0,a.jsxs)("td",{className:"py-2 text-right ".concat(v," tabular-nums font-mono"),children:[f(O.defectThreshold)," units or more"]})]}),(0,a.jsxs)("tr",{children:[(0,a.jsx)("th",{className:"py-2 pr-4 text-left font-medium ".concat(j),children:N.infiniteSampleSize}),(0,a.jsx)("td",{className:"py-2 text-right ".concat(v," tabular-nums font-mono"),children:f(O.infiniteSampleSize)})]}),(0,a.jsxs)("tr",{children:[(0,a.jsx)("th",{className:"py-2 pr-4 text-left font-medium ".concat(j),children:N.actualConfidence}),(0,a.jsx)("td",{className:"py-2 text-right ".concat(v," tabular-nums font-mono"),children:x(O.actualConfidence)})]}),(0,a.jsxs)("tr",{children:[(0,a.jsx)("th",{className:"py-2 pr-4 text-left font-medium ".concat(j),children:"Sample share of lot"}),(0,a.jsx)("td",{className:"py-2 text-right ".concat(v," tabular-nums font-mono"),children:p(O.sampleShare,1)})]})]})})})]}),O.fullInspection&&(0,a.jsx)("div",{className:"rounded-[4px] border border-mp-danger/30 dark:border-mp-danger/30 bg-mp-danger/10 dark:bg-red-950/40 p-3 text-sm text-mp-danger dark:text-red-300",children:"The math requires 100% inspection at these settings; loosen p, lower confidence, or inspect the whole lot."}),O.sampleShare>.4&&(0,a.jsxs)("div",{className:"rounded-[4px] border border-mp-warning/30 dark:border-mp-warning/30 bg-mp-warning/10 dark:bg-yellow-950/40 p-3 text-sm text-mp-warning dark:text-yellow-300",children:[(0,a.jsx)("span",{className:"font-semibold",children:"Large sample share."})," For destructive tests, consider process controls like crimp-height monitoring and per-setup pull tests instead of heavy lot inspection."]}),(0,a.jsx)(y,{result:O,variant:n})]})}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.