(()=>{var a={};a.id=9550,a.ids=[9550],a.modules={261:a=>{"use strict";a.exports=require("next/dist/shared/lib/router/utils/app-paths")},3295:a=>{"use strict";a.exports=require("next/dist/server/app-render/after-task-async-storage.external.js")},8849:(a,b,c)=>{"use strict";c.d(b,{A:()=>d});let d=(0,c(23339).A)("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]])},10846:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},12412:a=>{"use strict";a.exports=require("assert")},14674:(a,b,c)=>{"use strict";c.d(b,{A:()=>d});let d=(0,c(23339).A)("ShoppingBag",[["path",{d:"M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z",key:"hou9p0"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}]])},17693:(a,b,c)=>{"use strict";c.d(b,{PL:()=>l,an:()=>j,mL:()=>k});var d=c(38301),e=c(73852),f=c(45478),g=c(64158);let h={history:[],approvals:[],postings:null,walletMovements:[],inventoryMovements:[],journals:[],auditLogs:[],voucher:null};function i(a){return a&&"object"==typeof a&&"data"in a?a.data:a}function j(a){if(e.A.isAxiosError(a)){let b=a.response?.data?.detail;return"string"==typeof b?b:b&&"object"==typeof b?b.message||b.error_code||"Buy order request failed":a.response?.data?.message||a.message}return a instanceof Error?a.message:"Buy order request failed"}function k(a,b="buy-voucher"){let c=window.open("","_blank","width=920,height=1100");if(!c)throw Error("Popup blocked. Allow popups to print the voucher.");let d=a.items.map((a,b)=>`
    <tr>
      <td>${b+1}</td>
      <td>${a.metal_type||"gold"}</td>
      <td>${a.weight_grams}</td>
      <td>${a.quantity}</td>
      <td>${a.price_per_gram}</td>
      <td>${a.premium}</td>
      <td>${a.line_total}</td>
    </tr>
  `).join("");c.document.open(),c.document.write(`
    <!doctype html>
    <html>
      <head>
        <title>${b}</title>
        <style>
          body { font-family: Arial, sans-serif; color: #111827; margin: 28px; }
          header { display: flex; justify-content: space-between; border-bottom: 2px solid #d4af37; padding-bottom: 16px; margin-bottom: 20px; }
          h1 { font-size: 22px; margin: 0 0 6px; }
          table { width: 100%; border-collapse: collapse; margin-top: 16px; }
          th, td { border: 1px solid #e5e7eb; padding: 8px; font-size: 12px; text-align: left; }
          th { background: #f8fafc; }
          .grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px 24px; font-size: 13px; }
          .totals { width: 320px; margin-left: auto; margin-top: 18px; }
          .totals div { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px solid #e5e7eb; }
          button { margin-top: 24px; padding: 8px 14px; }
          @media print { button { display: none; } body { margin: 18px; } }
        </style>
      </head>
      <body>
        <header>
          <div>
            <h1>Buy Gold Voucher</h1>
            <div>${a.order_no}</div>
          </div>
          <div>Status: ${a.status}</div>
        </header>
        <section class="grid">
          <div><strong>Order type:</strong> ${a.order_type}</div>
          <div><strong>Created:</strong> ${a.created_at||"-"}</div>
          <div><strong>Supplier:</strong> ${a.supplier_id||"-"}</div>
          <div><strong>Customer:</strong> ${a.customer_id||"-"}</div>
          <div><strong>Currency:</strong> ${a.currency?.code||a.currency?.name_en||"-"}</div>
          <div><strong>Posted:</strong> ${a.posted_at||"-"}</div>
        </section>
        <table>
          <thead><tr><th>#</th><th>Metal</th><th>Weight</th><th>Qty</th><th>Price/g</th><th>Premium</th><th>Total</th></tr></thead>
          <tbody>${d||'<tr><td colspan="7">No items</td></tr>'}</tbody>
        </table>
        <section class="totals">
          <div><span>Subtotal</span><strong>${a.subtotal_amount}</strong></div>
          <div><span>Fees</span><strong>${a.fee_amount}</strong></div>
          <div><span>Tax</span><strong>${a.tax_amount}</strong></div>
          <div><span>Discount</span><strong>${a.discount_amount}</strong></div>
          <div><span>Total</span><strong>${a.total_amount}</strong></div>
        </section>
        <button onclick="window.print()">Print</button>
      </body>
    </html>
  `),c.document.close(),c.focus()}function l(){let[a,b]=(0,d.useState)([]),[c,e]=(0,d.useState)(null),[k,l]=(0,d.useState)(h),[m,n]=(0,d.useState)(0),[o,p]=(0,d.useState)(1),[q,r]=(0,d.useState)(!1),[s,t]=(0,d.useState)(!1),[u,v]=(0,d.useState)(null),w=(0,d.useCallback)(async(a={})=>{r(!0),v(null);try{let c=await f.api.get(g.H.BUY_ORDERS.LIST,{params:{skip:0,limit:500,req_status:a.status||void 0,buy_order_type:a.buy_order_type||void 0}}),d=function(a){let b=i(a);return Array.isArray(b)?b:b?.items??[]}(c),e=function(a,b){let c=b.search?.trim().toLowerCase();return a.filter(a=>!(b.status&&a.status!==b.status||b.buy_order_type&&a.buy_order_type!==b.buy_order_type||b.currency_id&&a.currency_id!==b.currency_id||b.branch_id&&a.target_branch_id!==b.branch_id||b.vault_id&&a.target_vault_id!==b.vault_id||b.customer_id&&a.customer_id!==b.customer_id||b.supplier_id&&a.supplier_id!==b.supplier_id||b.date_from&&new Date(a.created_at)<new Date(b.date_from)||b.date_to&&new Date(a.created_at)>new Date(`${b.date_to}T23:59:59`))&&(!c||[a.buy_order_no,a.status,a.buy_order_type,a.customer_id,a.supplier_id,a.purchase_request_no,a.supplier_reference,a.external_reference].some(a=>String(a??"").toLowerCase().includes(c))))}(d,a),h=a.page??1,j=a.page_size??25,k=e.slice((h-1)*j,h*j);return b(k),n(e.length),p(Math.max(1,Math.ceil(e.length/j))),{items:k,total:e.length,page:h,page_size:j,pages:Math.max(1,Math.ceil(e.length/j))}}catch(a){return v(j(a)),null}finally{r(!1)}},[]),x=(0,d.useCallback)(async a=>{r(!0),v(null);try{let b=i(await f.api.get(g.H.BUY_ORDERS.GET_BY_ID(a)));return e(b),b}catch(a){return v(j(a)),null}finally{r(!1)}},[]),y=(0,d.useCallback)(async a=>{t(!0);try{return i(await f.api.post(g.H.BUY_ORDERS.CREATE,a))}finally{t(!1)}},[]),z=(0,d.useCallback)((a,b,c)=>f.api.post(g.H.BUY_ORDERS.COMPUTE_PRICE,{purity_id:a,currency_id:b,product_id:c||void 0}).then(i),[]),A=(0,d.useCallback)((a,b)=>f.api.post(g.H.BUY_ORDERS.ITEMS(a),b).then(i),[]),B=(0,d.useCallback)((a,b)=>f.api.del(g.H.BUY_ORDERS.ITEM(a,b)),[]),C=(0,d.useCallback)(a=>f.api.post(g.H.BUY_ORDERS.RECALCULATE(a)).then(i),[]);return{items:a,selected:c,support:k,total:m,pages:o,isLoading:q,isSubmitting:s,error:u,list:w,get:x,create:y,quote:z,addItem:A,deleteItem:B,recalculate:C,act:(0,d.useCallback)(async(a,b,c={})=>{let d=g.H.BUY_ORDERS,e={submit:d.SUBMIT_FOR_REVIEW(a),review:d.SUBMIT_FOR_APPROVAL(a),approve:d.APPROVE(a),reject:d.REJECT(a),cancel:d.CANCEL(a),post:d.POST_APPROVAL(a),send:d.SEND_TO_SUPPLIER(a),partial:d.MARK_PARTIALLY_SUPPLIED(a),full:d.MARK_FULLY_SUPPLIED(a),close:d.CLOSE(a),"post-supply":d.POST_SUPPLY(a),"post-buyback":d.POST_BUYBACK(a),reverse:d.REVERSE(a)},h="cancel"===b||"reverse"===b?{reason:c.reason}:"post"===b?void 0:"post-supply"===b?{receiving_vault_id:c.receiving_vault_id||null}:"post-buyback"===b?c.customer_user_id?{customer_user_id:c.customer_user_id}:{}:{note:c.reason||null};t(!0);try{return i(await f.api.post(e[b],h))}finally{t(!1)}},[]),loadSupport:(0,d.useCallback)(async(a,b)=>{let c=g.H.BUY_ORDERS,d=[f.api.get(c.STATUS_HISTORY(a)),f.api.get(c.APPROVALS(a)),f.api.get(c.POSTINGS(a)),f.api.get(g.H.AUDIT_LOGS.LIST,{params:{entity_type:"buy_order",entity_id:a}})],e=await Promise.allSettled(d),h=(a,b)=>"fulfilled"===e[a].status?i(e[a].value):b,j=h(0,[]),k=h(1,[]),m={history:j,approvals:k,postings:h(2,null),walletMovements:[],inventoryMovements:[],journals:[],auditLogs:h(3,{items:[]}).items??[],voucher:b?{order_id:b.id,order_no:b.buy_order_no,order_type:b.buy_order_type,status:b.status,supplier_id:b.supplier_id,customer_id:b.customer_id,currency:b.currency,items:b.items??[],subtotal_amount:b.subtotal_amount,fee_amount:b.fee_amount,tax_amount:b.tax_amount,discount_amount:b.discount_amount,total_amount:b.total_amount,created_at:b.created_at,approved_at:b.approved_at,posted_at:b.posted_at}:null};return l(m),m},[])}}},19121:a=>{"use strict";a.exports=require("next/dist/server/app-render/action-async-storage.external.js")},26713:a=>{"use strict";a.exports=require("next/dist/shared/lib/router/utils/is-bot")},26850:(a,b,c)=>{"use strict";c.d(b,{Cf:()=>j,PM:()=>k,Td:()=>e,Xh:()=>d,df:()=>f,e6:()=>i});let d={draft:"neutral",pending_review:"pending",pending_approval:"warning",approved:"success",posted:"success",sent_to_supplier:"info",partially_supplied:"warning",fully_supplied:"success",rejected:"danger",cancelled:"neutral",closed:"neutral"},e={draft:{en:"Draft",ar:"مسودة"},pending_review:{en:"Pending review",ar:"بانتظار المراجعة"},pending_approval:{en:"Pending approval",ar:"بانتظار الاعتماد"},approved:{en:"Approved",ar:"معتمد"},posted:{en:"Posted",ar:"مرحل"},sent_to_supplier:{en:"Sent to supplier",ar:"مرسل للمورد"},partially_supplied:{en:"Partially supplied",ar:"مورد جزئيا"},fully_supplied:{en:"Fully supplied",ar:"مورد بالكامل"},rejected:{en:"Rejected",ar:"مرفوض"},cancelled:{en:"Cancelled",ar:"ملغي"},closed:{en:"Closed",ar:"مغلق"}},f={supplier:{en:"Supplier purchase",ar:"شراء من مورد"},customer_buyback:{en:"Customer buyback",ar:"شراء من عميل"}},g={submit:"buy_orders:update",review:"buy_orders:review",approve:"buy_orders:approve",reject:"buy_orders:review",cancel:"buy_orders:cancel",post:"buy_orders:post",send:"buy_orders:approve",partial:"buy_orders:update",full:"buy_orders:update",close:"buy_orders:approve","post-supply":"buy_orders:post","post-buyback":"buy_orders:post",reverse:"buy_orders:reverse",recalculate:"buy_orders:update"},h={draft:["recalculate","submit","cancel"],pending_review:["review","reject","cancel"],pending_approval:["approve","reject","cancel"],approved:["send","post","post-buyback","cancel"],posted:["send","reverse"],sent_to_supplier:["partial","cancel"],partially_supplied:["full","post-supply","cancel"],fully_supplied:["post-supply","close"]};function i(a,b=[],c){return(h[a]??[]).filter(a=>"customer_buyback"===c?!["send","partial","full","post-supply"].includes(a):"post-buyback"!==a).filter(a=>b.includes(g[a]))}function j(a){let b=new Set(a?.permissions||[]),c=new Set([a?.role,...(a?.roles||[]).map(a=>a.code)].filter(Boolean));return a?.user_type==="admin"||c.has("super_admin")?[...b,"buy_orders:read","buy_orders:create","buy_orders:update","buy_orders:review","buy_orders:approve","buy_orders:post","buy_orders:cancel","buy_orders:reverse","buy_orders:attachments","buy_orders:print"]:c.has("operations_manager")?[...b,"buy_orders:read","buy_orders:create","buy_orders:update","buy_orders:review","buy_orders:cancel","buy_orders:attachments","buy_orders:print"]:c.has("finance_officer")?[...b,"buy_orders:read","buy_orders:review","buy_orders:approve","buy_orders:post","buy_orders:cancel","buy_orders:reverse","buy_orders:print"]:c.has("warehouse_admin")?[...b,"buy_orders:read","buy_orders:update","buy_orders:post","buy_orders:attachments","buy_orders:print"]:[...b]}function k(a,b="en"){return"customer_buyback"===a.buy_order_type?("ar"===b?a.customer?.full_name_ar:a.customer?.full_name_en)||a.customer?.customer_code||a.customer_id||"-":("ar"===b?a.supplier?.name_ar:a.supplier?.name_en)||a.supplier?.code||a.supplier_id||"-"}},27910:a=>{"use strict";a.exports=require("stream")},28354:a=>{"use strict";a.exports=require("util")},29021:a=>{"use strict";a.exports=require("fs")},29294:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},33873:a=>{"use strict";a.exports=require("path")},34362:(a,b,c)=>{"use strict";c.r(b),c.d(b,{GlobalError:()=>E.a,__next_app__:()=>K,handler:()=>M,pages:()=>J,routeModule:()=>L,tree:()=>I});var d=c(49754),e=c(9117),f=c(46595),g=c(32324),h=c(39326),i=c(38928),j=c(20175),k=c(12),l=c(54290),m=c(12696),n=c(52574),o=c(82802),p=c(77533),q=c(45229),r=c(32822),s=c(261),t=c(26453),u=c(52474),v=c(26713),w=c(51356),x=c(62685),y=c(36225),z=c(63446),A=c(2762),B=c(45742),C=c(86439),D=c(81170),E=c.n(D),F=c(62506),G=c(91203),H={};for(let a in F)0>["default","tree","pages","GlobalError","__next_app__","routeModule","handler"].indexOf(a)&&(H[a]=()=>F[a]);c.d(b,H);let I={children:["",{children:["(admin)",{children:["buy-orders",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(c.bind(c,57259)),"D:\\Arab Ware Dos\\Gold App\\gold_wallet\\gold_wallet-dev\\src\\app\\(admin)\\buy-orders\\page.tsx"]}]},{}]},{layout:[()=>Promise.resolve().then(c.bind(c,43913)),"D:\\Arab Ware Dos\\Gold App\\gold_wallet\\gold_wallet-dev\\src\\app\\(admin)\\layout.tsx"],"not-found":[()=>Promise.resolve().then(c.t.bind(c,87028,23)),"next/dist/client/components/builtin/not-found.js"],forbidden:[()=>Promise.resolve().then(c.t.bind(c,90461,23)),"next/dist/client/components/builtin/forbidden.js"],unauthorized:[()=>Promise.resolve().then(c.t.bind(c,32768,23)),"next/dist/client/components/builtin/unauthorized.js"]}]},{layout:[()=>Promise.resolve().then(c.bind(c,51472)),"D:\\Arab Ware Dos\\Gold App\\gold_wallet\\gold_wallet-dev\\src\\app\\layout.tsx"],"global-error":[()=>Promise.resolve().then(c.t.bind(c,81170,23)),"next/dist/client/components/builtin/global-error.js"],"not-found":[()=>Promise.resolve().then(c.t.bind(c,87028,23)),"next/dist/client/components/builtin/not-found.js"],forbidden:[()=>Promise.resolve().then(c.t.bind(c,90461,23)),"next/dist/client/components/builtin/forbidden.js"],unauthorized:[()=>Promise.resolve().then(c.t.bind(c,32768,23)),"next/dist/client/components/builtin/unauthorized.js"]}]}.children,J=["D:\\Arab Ware Dos\\Gold App\\gold_wallet\\gold_wallet-dev\\src\\app\\(admin)\\buy-orders\\page.tsx"],K={require:c,loadChunk:()=>Promise.resolve()},L=new d.AppPageRouteModule({definition:{kind:e.RouteKind.APP_PAGE,page:"/(admin)/buy-orders/page",pathname:"/buy-orders",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:I},distDir:".next",relativeProjectDir:""});async function M(a,b,d){var D;let H="/(admin)/buy-orders/page";"/index"===H&&(H="/");let N=(0,h.getRequestMeta)(a,"postponed"),O=(0,h.getRequestMeta)(a,"minimalMode"),P=await L.prepare(a,b,{srcPage:H,multiZoneDraftMode:!1});if(!P)return b.statusCode=400,b.end("Bad Request"),null==d.waitUntil||d.waitUntil.call(d,Promise.resolve()),null;let{buildId:Q,query:R,params:S,parsedUrl:T,pageIsDynamic:U,buildManifest:V,nextFontManifest:W,reactLoadableManifest:X,serverActionsManifest:Y,clientReferenceManifest:Z,subresourceIntegrityManifest:$,prerenderManifest:_,isDraftMode:aa,resolvedPathname:ab,revalidateOnlyGenerated:ac,routerServerContext:ad,nextConfig:ae,interceptionRoutePatterns:af}=P,ag=T.pathname||"/",ah=(0,s.normalizeAppPath)(H),{isOnDemandRevalidate:ai}=P,aj=L.match(ag,_),ak=!!_.routes[ab],al=!!(aj||ak||_.routes[ah]),am=a.headers["user-agent"]||"",an=(0,v.getBotType)(am),ao=(0,q.isHtmlBotRequest)(a),ap=(0,h.getRequestMeta)(a,"isPrefetchRSCRequest")??"1"===a.headers[u.NEXT_ROUTER_PREFETCH_HEADER],aq=(0,h.getRequestMeta)(a,"isRSCRequest")??(0,n.f)(a.headers[u.RSC_HEADER]),ar=(0,t.getIsPossibleServerAction)(a),as=(0,m.checkIsAppPPREnabled)(ae.experimental.ppr)&&(null==(D=_.routes[ah]??_.dynamicRoutes[ah])?void 0:D.renderingMode)==="PARTIALLY_STATIC",at=!1,au=!1,av=as?N:void 0,aw=as&&aq&&!ap,ax=(0,h.getRequestMeta)(a,"segmentPrefetchRSCRequest"),ay=!am||(0,q.shouldServeStreamingMetadata)(am,ae.htmlLimitedBots);ao&&as&&(al=!1,ay=!1);let az=!0===L.isDev||!al||"string"==typeof N||aw,aA=ao&&as,aB=null;aa||!al||az||ar||av||aw||(aB=ab);let aC=aB;!aC&&L.isDev&&(aC=ab),L.isDev||aa||!al||!aq||aw||(0,k.d)(a.headers);let aD={...F,tree:I,pages:J,GlobalError:E(),handler:M,routeModule:L,__next_app__:K};Y&&Z&&(0,p.setReferenceManifestsSingleton)({page:H,clientReferenceManifest:Z,serverActionsManifest:Y,serverModuleMap:(0,r.createServerModuleMap)({serverActionsManifest:Y})});let aE=a.method||"GET",aF=(0,g.getTracer)(),aG=aF.getActiveScopeSpan();try{let f=L.getVaryHeader(ab,af);b.setHeader("Vary",f);let k=async(c,d)=>{let e=new l.NodeNextRequest(a),f=new l.NodeNextResponse(b);return L.render(e,f,d).finally(()=>{if(!c)return;c.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let d=aF.getRootSpanAttributes();if(!d)return;if(d.get("next.span_type")!==i.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${d.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let e=d.get("next.route");if(e){let a=`${aE} ${e}`;c.setAttributes({"next.route":e,"http.route":e,"next.span_name":a}),c.updateName(a)}else c.updateName(`${aE} ${a.url}`)})},m=async({span:e,postponed:f,fallbackRouteParams:g})=>{let i={query:R,params:S,page:ah,sharedContext:{buildId:Q},serverComponentsHmrCache:(0,h.getRequestMeta)(a,"serverComponentsHmrCache"),fallbackRouteParams:g,renderOpts:{App:()=>null,Document:()=>null,pageConfig:{},ComponentMod:aD,Component:(0,j.T)(aD),params:S,routeModule:L,page:H,postponed:f,shouldWaitOnAllReady:aA,serveStreamingMetadata:ay,supportsDynamicResponse:"string"==typeof f||az,buildManifest:V,nextFontManifest:W,reactLoadableManifest:X,subresourceIntegrityManifest:$,serverActionsManifest:Y,clientReferenceManifest:Z,setIsrStatus:null==ad?void 0:ad.setIsrStatus,dir:c(33873).join(process.cwd(),L.relativeProjectDir),isDraftMode:aa,isRevalidate:al&&!f&&!aw,botType:an,isOnDemandRevalidate:ai,isPossibleServerAction:ar,assetPrefix:ae.assetPrefix,nextConfigOutput:ae.output,crossOrigin:ae.crossOrigin,trailingSlash:ae.trailingSlash,previewProps:_.preview,deploymentId:ae.deploymentId,enableTainting:ae.experimental.taint,htmlLimitedBots:ae.htmlLimitedBots,devtoolSegmentExplorer:ae.experimental.devtoolSegmentExplorer,reactMaxHeadersLength:ae.reactMaxHeadersLength,multiZoneDraftMode:!1,incrementalCache:(0,h.getRequestMeta)(a,"incrementalCache"),cacheLifeProfiles:ae.experimental.cacheLife,basePath:ae.basePath,serverActions:ae.experimental.serverActions,...at?{nextExport:!0,supportsDynamicResponse:!1,isStaticGeneration:!0,isRevalidate:!0,isDebugDynamicAccesses:at}:{},experimental:{isRoutePPREnabled:as,expireTime:ae.expireTime,staleTimes:ae.experimental.staleTimes,cacheComponents:!!ae.experimental.cacheComponents,clientSegmentCache:!!ae.experimental.clientSegmentCache,clientParamParsing:!!ae.experimental.clientParamParsing,dynamicOnHover:!!ae.experimental.dynamicOnHover,inlineCss:!!ae.experimental.inlineCss,authInterrupts:!!ae.experimental.authInterrupts,clientTraceMetadata:ae.experimental.clientTraceMetadata||[]},waitUntil:d.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:()=>{},onInstrumentationRequestError:(b,c,d)=>L.onRequestError(a,b,d,ad),err:(0,h.getRequestMeta)(a,"invokeError"),dev:L.isDev}},l=await k(e,i),{metadata:m}=l,{cacheControl:n,headers:o={},fetchTags:p}=m;if(p&&(o[z.NEXT_CACHE_TAGS_HEADER]=p),a.fetchMetrics=m.fetchMetrics,al&&(null==n?void 0:n.revalidate)===0&&!L.isDev&&!as){let a=m.staticBailoutInfo,b=Object.defineProperty(Error(`Page changed from static to dynamic at runtime ${ab}${(null==a?void 0:a.description)?`, reason: ${a.description}`:""}
see more here https://nextjs.org/docs/messages/app-static-to-dynamic-error`),"__NEXT_ERROR_CODE",{value:"E132",enumerable:!1,configurable:!0});if(null==a?void 0:a.stack){let c=a.stack;b.stack=b.message+c.substring(c.indexOf("\n"))}throw b}return{value:{kind:w.CachedRouteKind.APP_PAGE,html:l,headers:o,rscData:m.flightData,postponed:m.postponed,status:m.statusCode,segmentData:m.segmentData},cacheControl:n}},n=async({hasResolved:c,previousCacheEntry:f,isRevalidating:g,span:i})=>{let j,k=!1===L.isDev,l=c||b.writableEnded;if(ai&&ac&&!f&&!O)return(null==ad?void 0:ad.render404)?await ad.render404(a,b):(b.statusCode=404,b.end("This page could not be found")),null;if(aj&&(j=(0,x.parseFallbackField)(aj.fallback)),j===x.FallbackMode.PRERENDER&&(0,v.isBot)(am)&&(!as||ao)&&(j=x.FallbackMode.BLOCKING_STATIC_RENDER),(null==f?void 0:f.isStale)===-1&&(ai=!0),ai&&(j!==x.FallbackMode.NOT_FOUND||f)&&(j=x.FallbackMode.BLOCKING_STATIC_RENDER),!O&&j!==x.FallbackMode.BLOCKING_STATIC_RENDER&&aC&&!l&&!aa&&U&&(k||!ak)){let b;if((k||aj)&&j===x.FallbackMode.NOT_FOUND)throw new C.NoFallbackError;if(as&&!aq){let c="string"==typeof(null==aj?void 0:aj.fallback)?aj.fallback:k?ah:null;if(b=await L.handleResponse({cacheKey:c,req:a,nextConfig:ae,routeKind:e.RouteKind.APP_PAGE,isFallback:!0,prerenderManifest:_,isRoutePPREnabled:as,responseGenerator:async()=>m({span:i,postponed:void 0,fallbackRouteParams:k||au?(0,o.u)(ah):null}),waitUntil:d.waitUntil}),null===b)return null;if(b)return delete b.cacheControl,b}}let n=ai||g||!av?void 0:av;if(at&&void 0!==n)return{cacheControl:{revalidate:1,expire:void 0},value:{kind:w.CachedRouteKind.PAGES,html:y.default.EMPTY,pageData:{},headers:void 0,status:void 0}};let p=U&&as&&((0,h.getRequestMeta)(a,"renderFallbackShell")||au)?(0,o.u)(ag):null;return m({span:i,postponed:n,fallbackRouteParams:p})},p=async c=>{var f,g,i,j,k;let l,o=await L.handleResponse({cacheKey:aB,responseGenerator:a=>n({span:c,...a}),routeKind:e.RouteKind.APP_PAGE,isOnDemandRevalidate:ai,isRoutePPREnabled:as,req:a,nextConfig:ae,prerenderManifest:_,waitUntil:d.waitUntil});if(aa&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate"),L.isDev&&b.setHeader("Cache-Control","no-store, must-revalidate"),!o){if(aB)throw Object.defineProperty(Error("invariant: cache entry required but not generated"),"__NEXT_ERROR_CODE",{value:"E62",enumerable:!1,configurable:!0});return null}if((null==(f=o.value)?void 0:f.kind)!==w.CachedRouteKind.APP_PAGE)throw Object.defineProperty(Error(`Invariant app-page handler received invalid cache entry ${null==(i=o.value)?void 0:i.kind}`),"__NEXT_ERROR_CODE",{value:"E707",enumerable:!1,configurable:!0});let p="string"==typeof o.value.postponed;al&&!aw&&(!p||ap)&&(O||b.setHeader("x-nextjs-cache",ai?"REVALIDATED":o.isMiss?"MISS":o.isStale?"STALE":"HIT"),b.setHeader(u.NEXT_IS_PRERENDER_HEADER,"1"));let{value:q}=o;if(av)l={revalidate:0,expire:void 0};else if(O&&aq&&!ap&&as)l={revalidate:0,expire:void 0};else if(!L.isDev)if(aa)l={revalidate:0,expire:void 0};else if(al){if(o.cacheControl)if("number"==typeof o.cacheControl.revalidate){if(o.cacheControl.revalidate<1)throw Object.defineProperty(Error(`Invalid revalidate configuration provided: ${o.cacheControl.revalidate} < 1`),"__NEXT_ERROR_CODE",{value:"E22",enumerable:!1,configurable:!0});l={revalidate:o.cacheControl.revalidate,expire:(null==(j=o.cacheControl)?void 0:j.expire)??ae.expireTime}}else l={revalidate:z.CACHE_ONE_YEAR,expire:void 0}}else b.getHeader("Cache-Control")||(l={revalidate:0,expire:void 0});if(o.cacheControl=l,"string"==typeof ax&&(null==q?void 0:q.kind)===w.CachedRouteKind.APP_PAGE&&q.segmentData){b.setHeader(u.NEXT_DID_POSTPONE_HEADER,"2");let c=null==(k=q.headers)?void 0:k[z.NEXT_CACHE_TAGS_HEADER];O&&al&&c&&"string"==typeof c&&b.setHeader(z.NEXT_CACHE_TAGS_HEADER,c);let d=q.segmentData.get(ax);return void 0!==d?(0,B.sendRenderResult)({req:a,res:b,generateEtags:ae.generateEtags,poweredByHeader:ae.poweredByHeader,result:y.default.fromStatic(d,u.RSC_CONTENT_TYPE_HEADER),cacheControl:o.cacheControl}):(b.statusCode=204,(0,B.sendRenderResult)({req:a,res:b,generateEtags:ae.generateEtags,poweredByHeader:ae.poweredByHeader,result:y.default.EMPTY,cacheControl:o.cacheControl}))}let r=(0,h.getRequestMeta)(a,"onCacheEntry");if(r&&await r({...o,value:{...o.value,kind:"PAGE"}},{url:(0,h.getRequestMeta)(a,"initURL")}))return null;if(p&&av)throw Object.defineProperty(Error("Invariant: postponed state should not be present on a resume request"),"__NEXT_ERROR_CODE",{value:"E396",enumerable:!1,configurable:!0});if(q.headers){let a={...q.headers};for(let[c,d]of(O&&al||delete a[z.NEXT_CACHE_TAGS_HEADER],Object.entries(a)))if(void 0!==d)if(Array.isArray(d))for(let a of d)b.appendHeader(c,a);else"number"==typeof d&&(d=d.toString()),b.appendHeader(c,d)}let s=null==(g=q.headers)?void 0:g[z.NEXT_CACHE_TAGS_HEADER];if(O&&al&&s&&"string"==typeof s&&b.setHeader(z.NEXT_CACHE_TAGS_HEADER,s),!q.status||aq&&as||(b.statusCode=q.status),!O&&q.status&&G.RedirectStatusCode[q.status]&&aq&&(b.statusCode=200),p&&b.setHeader(u.NEXT_DID_POSTPONE_HEADER,"1"),aq&&!aa){if(void 0===q.rscData){if(q.postponed)throw Object.defineProperty(Error("Invariant: Expected postponed to be undefined"),"__NEXT_ERROR_CODE",{value:"E372",enumerable:!1,configurable:!0});return(0,B.sendRenderResult)({req:a,res:b,generateEtags:ae.generateEtags,poweredByHeader:ae.poweredByHeader,result:q.html,cacheControl:aw?{revalidate:0,expire:void 0}:o.cacheControl})}return(0,B.sendRenderResult)({req:a,res:b,generateEtags:ae.generateEtags,poweredByHeader:ae.poweredByHeader,result:y.default.fromStatic(q.rscData,u.RSC_CONTENT_TYPE_HEADER),cacheControl:o.cacheControl})}let t=q.html;if(!p||O||aq)return(0,B.sendRenderResult)({req:a,res:b,generateEtags:ae.generateEtags,poweredByHeader:ae.poweredByHeader,result:t,cacheControl:o.cacheControl});if(at)return t.push(new ReadableStream({start(a){a.enqueue(A.ENCODED_TAGS.CLOSED.BODY_AND_HTML),a.close()}})),(0,B.sendRenderResult)({req:a,res:b,generateEtags:ae.generateEtags,poweredByHeader:ae.poweredByHeader,result:t,cacheControl:{revalidate:0,expire:void 0}});let v=new TransformStream;return t.push(v.readable),m({span:c,postponed:q.postponed,fallbackRouteParams:null}).then(async a=>{var b,c;if(!a)throw Object.defineProperty(Error("Invariant: expected a result to be returned"),"__NEXT_ERROR_CODE",{value:"E463",enumerable:!1,configurable:!0});if((null==(b=a.value)?void 0:b.kind)!==w.CachedRouteKind.APP_PAGE)throw Object.defineProperty(Error(`Invariant: expected a page response, got ${null==(c=a.value)?void 0:c.kind}`),"__NEXT_ERROR_CODE",{value:"E305",enumerable:!1,configurable:!0});await a.value.html.pipeTo(v.writable)}).catch(a=>{v.writable.abort(a).catch(a=>{console.error("couldn't abort transformer",a)})}),(0,B.sendRenderResult)({req:a,res:b,generateEtags:ae.generateEtags,poweredByHeader:ae.poweredByHeader,result:t,cacheControl:{revalidate:0,expire:void 0}})};if(!aG)return await aF.withPropagatedContext(a.headers,()=>aF.trace(i.BaseServerSpan.handleRequest,{spanName:`${aE} ${a.url}`,kind:g.SpanKind.SERVER,attributes:{"http.method":aE,"http.target":a.url}},p));await p(aG)}catch(b){throw b instanceof C.NoFallbackError||await L.onRequestError(a,b,{routerKind:"App Router",routePath:H,routeType:"render",revalidateReason:(0,f.c)({isRevalidate:al,isOnDemandRevalidate:ai})},ad),b}}},34631:a=>{"use strict";a.exports=require("tls")},41025:a=>{"use strict";a.exports=require("next/dist/server/app-render/dynamic-access-async-storage.external.js")},55511:a=>{"use strict";a.exports=require("crypto")},55591:a=>{"use strict";a.exports=require("https")},57259:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>d});let d=(0,c(97954).registerClientReference)(function(){throw Error("Attempted to call the default export of \"D:\\\\Arab Ware Dos\\\\Gold App\\\\gold_wallet\\\\gold_wallet-dev\\\\src\\\\app\\\\(admin)\\\\buy-orders\\\\page.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"D:\\Arab Ware Dos\\Gold App\\gold_wallet\\gold_wallet-dev\\src\\app\\(admin)\\buy-orders\\page.tsx","default")},58783:(a,b,c)=>{Promise.resolve().then(c.bind(c,98025))},63033:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},73496:a=>{"use strict";a.exports=require("http2")},74075:a=>{"use strict";a.exports=require("zlib")},79551:a=>{"use strict";a.exports=require("url")},81630:a=>{"use strict";a.exports=require("http")},83997:a=>{"use strict";a.exports=require("tty")},86439:a=>{"use strict";a.exports=require("next/dist/shared/lib/no-fallback-error.external")},91645:a=>{"use strict";a.exports=require("net")},93287:(a,b,c)=>{Promise.resolve().then(c.bind(c,57259))},94735:a=>{"use strict";a.exports=require("events")},98025:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>B});var d=c(21124),e=c(38301),f=c(42378),g=c(3368),h=c(25345),i=c(8849),j=c(14674),k=c(43027),l=c(20304),m=c(25770),n=c(88285),o=c(43401),p=c(45817),q=c(17693),r=c(26850),s=c(2727),t=c(95360),u=c(29553),v=c(96647),w=c(17584),x=c(35284),y=c(74028),z=c(92155);c(45478),c(64158);let A={submit:{en:"Review",ar:"مراجعة"},review:{en:"Approve",ar:"اعتماد"},approve:{en:"Approve",ar:"اعتماد"},post:{en:"Post",ar:"ترحيل"},send:{en:"Send",ar:"إرسال"},partial:{en:"Partial",ar:"جزئي"},full:{en:"Full",ar:"كامل"},close:{en:"Close",ar:"إغلاق"},"post-buyback":{en:"Post buyback",ar:"ترحيل الشراء"}};function B(){let a=(0,f.useRouter)(),{i18n:b}=(0,o.Bd)(),{user:c}=(0,p.A)(),{items:B,total:C,pages:D,isLoading:E,error:F,list:G}=(0,q.PL)(),[H,I]=(0,e.useState)(1),[J,K]=(0,e.useState)({page:1,page_size:25}),[L,M]=(0,e.useState)([]),[N,O]=(0,e.useState)([]),[P,Q]=(0,e.useState)([]),[R,S]=(0,e.useState)(!0),T=b.language.startsWith("ar")?"ar":"en",U=function(a){if(!a)return!1;let b=new Set(a.permissions||[]),c=new Set([a.role,...(a.roles||[]).map(a=>a.code)].filter(Boolean));return b.has("buy_orders:create")||"admin"===a.user_type||c.has("super_admin")||c.has("operations_manager")||c.has("finance_admin")||c.has("warehouse_manager")}(c),V=(0,e.useMemo)(()=>(0,r.Cf)(c),[c]),W=(0,e.useCallback)(()=>G({...J,page:H}),[J,G,H]),X=(0,e.useCallback)(b=>a.push(`/buy-orders/${b}`),[a]),Y=[{key:"order",header:"ar"===T?"رقم الأمر":"Order",cell:a=>(0,d.jsx)("span",{className:"font-mono font-semibold",children:a.buy_order_no})},{key:"type",header:"ar"===T?"النوع":"Type",cell:a=>(0,d.jsx)("span",{children:r.df[a.buy_order_type]?.[T]??a.buy_order_type})},{key:"party",header:"ar"===T?"الطرف":"Party",cell:a=>(0,d.jsx)("span",{className:"text-[13px]",children:(0,r.PM)(a,T)})},{key:"target",header:"ar"===T?"الفرع / الخزنة":"Branch / Vault",cell:a=>(0,d.jsxs)("div",{children:[(0,d.jsx)("p",{children:("ar"===T?a.target_branch?.name_ar:a.target_branch?.name_en)||a.target_branch_id||"-"}),(0,d.jsx)("p",{className:"text-[11px] text-muted-foreground",children:a.target_vault?.name||a.target_vault_id||"-"})]})},{key:"amount",header:"ar"===T?"الإجمالي":"Total",cell:a=>(0,d.jsx)("span",{className:"font-mono font-semibold",children:(0,z.S8)(Number(a.total_amount),a.currency?.code??void 0)})},{key:"status",header:"ar"===T?"الحالة":"Status",cell:a=>(0,d.jsx)(w.W,{tone:r.Xh[a.status]??"neutral",children:r.Td[a.status]?.[T]??a.status})},{key:"date",header:"ar"===T?"تاريخ الإنشاء":"Created",cell:a=>(0,d.jsx)("span",{className:"text-xs",children:(0,z.r6)(a.created_at)})},{key:"actions",header:"ar"===T?"الإجراء":"Action",align:"end",cell:a=>{let b=(0,r.e6)(a.status,V,a.buy_order_type).find(a=>["submit","review","approve","post","send","partial","full","close","post-buyback"].includes(a));return(0,d.jsxs)("div",{className:"flex justify-end gap-2",onClick:a=>a.stopPropagation(),children:[(0,d.jsxs)(x.$,{size:"sm",variant:"outline",onClick:()=>X(a.id),children:[(0,d.jsx)(g.A,{className:"h-3.5 w-3.5"}),"ar"===T?"عرض":"View"]}),b&&(0,d.jsx)(x.$,{size:"sm",onClick:()=>X(a.id),children:A[b]?.[T]??b})]})}}],Z=(0,e.useMemo)(()=>B.reduce((a,b)=>a+Number(b.total_amount||0),0),[B]),$=(0,e.useMemo)(()=>B.filter(a=>["pending_review","pending_approval","approved","posted","sent_to_supplier","partially_supplied"].includes(a.status)).length,[B]),_=(0,e.useMemo)(()=>B.filter(a=>"posted"===a.status||"closed"===a.status).length,[B]),aa=(a,b)=>{I(1),K(c=>{let d={...c,[a]:b||void 0};return"branch_id"===a&&(d.vault_id=void 0),d})};return(0,d.jsxs)("div",{className:"space-y-6",children:[(0,d.jsx)(s.z,{title:"ar"===T?"أوامر شراء الذهب":"Buy Gold Orders",description:"ar"===T?"إنشاء ومراجعة واعتماد وترحيل عمليات شراء الذهب.":"Create, review, approve, post, and receive gold purchase orders.",breadcrumbs:[{label:"ar"===T?"العمليات المالية":"Financial operations",href:"#"},{label:"ar"===T?"أوامر الشراء":"Buy orders"}],actions:(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(x.$,{variant:"outline",onClick:W,disabled:E,children:(0,d.jsx)(h.A,{className:"h-4 w-4"})}),U&&(0,d.jsxs)(x.$,{onClick:()=>a.push("/buy-orders/create"),children:[(0,d.jsx)(i.A,{className:"h-4 w-4"}),"ar"===T?"أمر شراء جديد":"New buy order"]})]})}),(0,d.jsxs)("div",{className:"grid grid-cols-2 gap-4 lg:grid-cols-4",children:[(0,d.jsx)(u.n,{label:"ar"===T?"إجمالي الأوامر":"Total orders",value:String(C),icon:j.A,tone:"gold",accent:!0}),(0,d.jsx)(u.n,{label:"ar"===T?"قيد الإجراء":"Pending action",value:String($),icon:k.A,tone:"warning"}),(0,d.jsx)(u.n,{label:"ar"===T?"قيمة الصفحة":"Page value",value:(0,z.S8)(Z),icon:l.A,tone:"success"}),(0,d.jsx)(u.n,{label:"ar"===T?"مكتملة":"Posted / closed",value:String(_),icon:m.A,tone:"info"})]}),(0,d.jsxs)(t.i,{title:"ar"===T?"البحث والتصفية":"Search and filters",children:[(0,d.jsxs)("div",{className:"grid gap-3 md:grid-cols-3 xl:grid-cols-8",children:[(0,d.jsxs)("label",{className:"relative xl:col-span-2",children:[(0,d.jsx)(n.A,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),(0,d.jsx)("input",{className:"w-full rounded-lg border border-border bg-background py-2.5 pl-9 pr-3 text-sm",placeholder:"ar"===T?"رقم الأمر أو المرجع":"Order or reference",value:J.search??"",onChange:a=>aa("search",a.target.value)})]}),(0,d.jsxs)("select",{className:"rounded-lg border border-border bg-background px-3 text-sm",value:J.status??"",onChange:a=>aa("status",a.target.value),children:[(0,d.jsx)("option",{value:"",children:"ar"===T?"كل الحالات":"All statuses"}),Object.entries(r.Td).map(([a,b])=>(0,d.jsx)("option",{value:a,children:b[T]},a))]}),(0,d.jsxs)("select",{className:"rounded-lg border border-border bg-background px-3 text-sm",value:J.buy_order_type??"",onChange:a=>aa("buy_order_type",a.target.value),children:[(0,d.jsx)("option",{value:"",children:"ar"===T?"كل الأنواع":"All types"}),Object.entries(r.df).map(([a,b])=>(0,d.jsx)("option",{value:a,children:b[T]},a))]}),(0,d.jsxs)("select",{className:"rounded-lg border border-border bg-background px-3 text-sm",value:J.branch_id??"",onChange:a=>aa("branch_id",a.target.value),disabled:R,children:[(0,d.jsx)("option",{value:"",children:"ar"===T?"كل الفروع":"All branches"}),L.map(a=>(0,d.jsx)("option",{value:a.id,children:"ar"===T?a.name_ar:a.name_en||a.name_ar},a.id))]}),(0,d.jsxs)("select",{className:"rounded-lg border border-border bg-background px-3 text-sm",value:J.vault_id??"",onChange:a=>aa("vault_id",a.target.value),disabled:R,children:[(0,d.jsx)("option",{value:"",children:"ar"===T?"كل الخزن":"All vaults"}),N.filter(a=>!J.branch_id||a.branch_id===J.branch_id).map(a=>(0,d.jsx)("option",{value:a.id,children:a.name},a.id))]}),(0,d.jsxs)("select",{className:"rounded-lg border border-border bg-background px-3 text-sm",value:J.currency_id??"",onChange:a=>aa("currency_id",a.target.value),disabled:R,children:[(0,d.jsx)("option",{value:"",children:"ar"===T?"كل العملات":"All currencies"}),P.map(a=>(0,d.jsxs)("option",{value:a.id,children:[a.code," - ","ar"===T?a.name_ar:a.name_en]},a.id))]}),(0,d.jsx)("input",{type:"date",className:"rounded-lg border border-border bg-background px-3 text-sm",value:J.date_from??"",onChange:a=>aa("date_from",a.target.value)})]}),(0,d.jsx)("div",{className:"mt-3 flex justify-end",children:(0,d.jsx)(x.$,{size:"sm",variant:"ghost",onClick:()=>{I(1),K({page:1,page_size:25})},children:"ar"===T?"مسح الفلاتر":"Clear filters"})})]}),(0,d.jsxs)(t.i,{title:"ar"===T?"قائمة أوامر الشراء":"Buy orders",padded:!1,children:[F&&(0,d.jsx)("div",{className:"m-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700",children:F}),E?(0,d.jsx)("div",{className:"flex h-52 items-center justify-center",children:(0,d.jsx)("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent"})}):(0,d.jsx)(v.b,{columns:Y,data:B,rowKey:a=>a.id,onRowClick:a=>X(a.id),ariaLabel:"Buy orders",empty:(0,d.jsx)("div",{className:"text-center text-sm text-muted-foreground",children:"ar"===T?"لا توجد أوامر شراء مطابقة.":"No matching buy orders."})}),(0,d.jsx)(y.d,{currentPage:H,totalPages:D,onPageChange:I})]})]})}}};var b=require("../../../webpack-runtime.js");b.C(a);var c=b.X(0,[8543,5471,3852,3991,6802,1866,3626,7574,9545,9008],()=>b(b.s=34362));module.exports=c})();