"use strict";(()=>{var e={};e.id=1483,e.ids=[1483],e.modules={72934:e=>{e.exports=require("next/dist/client/components/action-async-storage.external.js")},54580:e=>{e.exports=require("next/dist/client/components/request-async-storage.external.js")},45869:e=>{e.exports=require("next/dist/client/components/static-generation-async-storage.external.js")},20399:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},30517:e=>{e.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},78893:e=>{e.exports=require("buffer")},84770:e=>{e.exports=require("crypto")},76162:e=>{e.exports=require("stream")},21764:e=>{e.exports=require("util")},9919:(e,t,a)=>{a.r(t),a.d(t,{originalPathname:()=>h,patchFetch:()=>x,requestAsyncStorage:()=>p,routeModule:()=>_,serverHooks:()=>y,staticGenerationAsyncStorage:()=>f});var n={};a.r(n),a.d(n,{GET:()=>m});var r=a(49303),s=a(88716),o=a(60670),i=a(87070),u=a(95456),l=a(8194),d=a(45239),c=a(5564);async function m(e){try{let t,a;let n=await (0,u.ts)();if(!n)return i.NextResponse.json({error:"Unauthorized"},{status:401});if(!["owner","admin","manager","finance"].includes(n.role))return i.NextResponse.json({error:"Forbidden"},{status:403});let r=await (0,d.F)(n.tenantId,"expenses");if(r)return r;let s=e.nextUrl.searchParams.get("storeId"),o=e.nextUrl.searchParams.get("dateFrom"),m=e.nextUrl.searchParams.get("dateTo"),_={tenantId:n.tenantId,status:"approved"};if(s&&(_.storeId=s),o||m){let e={};o&&(e.gte=(0,c.uq)(o)),m&&(e.lte=(0,c.uq)(m)),_.date=e}let p=await l._.expense.groupBy({by:["categoryId"],where:_,_sum:{amount:!0},_count:!0}),f=p.map(e=>e.categoryId),y=await l._.expenseCategory.findMany({where:{id:{in:f},tenantId:n.tenantId},select:{id:!0,name:!0}}),h=new Map(y.map(e=>[e.id,e.name])),x=p.map(e=>({categoryId:e.categoryId,categoryName:h.get(e.categoryId)||"Unknown",total:parseFloat((e._sum.amount||0).toString()),count:e._count})).sort((e,t)=>t.total-e.total);if(o)t=(0,c.uq)(o);else{let e=new Date;e.setMonth(e.getMonth()-12),t=e}if(s&&m){let e=(0,c.uq)(m);a=await l._.$queryRaw`
        SELECT
          DATE_FORMAT(date, '%Y-%m') AS month,
          SUM(amount) AS total,
          COUNT(*) AS count
        FROM expenses
        WHERE tenantId = ${n.tenantId}
          AND status = 'approved'
          AND storeId = ${s}
          AND date >= ${t}
          AND date <= ${e}
        GROUP BY DATE_FORMAT(date, '%Y-%m')
        ORDER BY month ASC
      `}else if(s)a=await l._.$queryRaw`
        SELECT
          DATE_FORMAT(date, '%Y-%m') AS month,
          SUM(amount) AS total,
          COUNT(*) AS count
        FROM expenses
        WHERE tenantId = ${n.tenantId}
          AND status = 'approved'
          AND storeId = ${s}
          AND date >= ${t}
        GROUP BY DATE_FORMAT(date, '%Y-%m')
        ORDER BY month ASC
      `;else if(m){let e=(0,c.uq)(m);a=await l._.$queryRaw`
        SELECT
          DATE_FORMAT(date, '%Y-%m') AS month,
          SUM(amount) AS total,
          COUNT(*) AS count
        FROM expenses
        WHERE tenantId = ${n.tenantId}
          AND status = 'approved'
          AND date >= ${t}
          AND date <= ${e}
        GROUP BY DATE_FORMAT(date, '%Y-%m')
        ORDER BY month ASC
      `}else a=await l._.$queryRaw`
        SELECT
          DATE_FORMAT(date, '%Y-%m') AS month,
          SUM(amount) AS total,
          COUNT(*) AS count
        FROM expenses
        WHERE tenantId = ${n.tenantId}
          AND status = 'approved'
          AND date >= ${t}
        GROUP BY DATE_FORMAT(date, '%Y-%m')
        ORDER BY month ASC
      `;let g=a.map(e=>({month:e.month,total:parseFloat((e.total||0).toString()),count:Number(e.count)})),A=await l._.expense.aggregate({where:_,_sum:{amount:!0},_count:!0}),v=parseFloat((A._sum.amount||0).toString()),w=A._count||0;return i.NextResponse.json({byCategory:x,byMonth:g,grandTotal:v,totalCount:w})}catch(e){return console.error("Expense summary error:",e),i.NextResponse.json({error:"Server error"},{status:500})}}let _=new r.AppRouteRouteModule({definition:{kind:s.x.APP_ROUTE,page:"/api/expenses/summary/route",pathname:"/api/expenses/summary",filename:"route",bundlePath:"app/api/expenses/summary/route"},resolvedPagePath:"D:\\PROJECT\\resto-saas\\src\\app\\api\\expenses\\summary\\route.ts",nextConfigOutput:"",userland:n}),{requestAsyncStorage:p,staticGenerationAsyncStorage:f,serverHooks:y}=_,h="/api/expenses/summary/route";function x(){return(0,o.patchFetch)({serverHooks:y,staticGenerationAsyncStorage:f})}},95456:(e,t,a)=>{a.d(t,{Gv:()=>c,MH:()=>f,PT:()=>y,RA:()=>m,WX:()=>_,c_:()=>d,ts:()=>p});var n=a(41482),r=a.n(n),s=a(42023),o=a.n(s),i=a(71615),u=a(8194);let l=process.env.JWT_SECRET||"fallback-secret-change-me";async function d(e){return o().hash(e,12)}async function c(e,t){return o().compare(e,t)}function m(e){return r().sign(e,l,{expiresIn:"7d"})}function _(e){try{return r().verify(e,l)}catch{return null}}async function p(){let e=await (0,i.cookies)(),t=e.get("token")?.value;if(!t)return null;let a=_(t);return a?await u._.user.findUnique({where:{id:a.userId},include:{tenant:!0,store:!0}}):null}function f(e,t){return t.includes(e)}function y(e){return!["owner","admin"].includes(e.role)&&!!e.storeId&&!!e.store&&!e.store.isActive}},8194:(e,t,a)=>{a.d(t,{_:()=>r});let n=require("@prisma/client"),r=globalThis.prisma??new n.PrismaClient},45239:(e,t,a)=>{a.d(t,{F:()=>s});var n=a(87070),r=a(15230);async function s(e,t){let a=await (0,r.p6)(e);return(0,r.U6)(a.features,t)?null:n.NextResponse.json({error:"Fitur ini tidak tersedia pada paket Anda. Silakan upgrade."},{status:403})}},15230:(e,t,a)=>{a.d(t,{MN:()=>s,U6:()=>o,p6:()=>r});var n=a(8194);async function r(e){let t=await n._.subscription.findFirst({where:{tenantId:e,status:{in:["active","trial"]}},include:{plan:!0},orderBy:{createdAt:"desc"}});return t?{maxStores:t.plan.maxStores,maxStaff:t.plan.maxStaff,maxMenuItems:t.plan.maxMenuItems,maxOrders:t.plan.maxOrders,features:JSON.parse(t.plan.features)}:{maxStores:1,maxStaff:3,maxMenuItems:30,maxOrders:100,features:["pos","qr_menu"]}}async function s(e,t){let a=await r(e),s=0,o=0;switch(t){case"stores":s=await n._.store.count({where:{tenantId:e,isActive:!0}}),o=a.maxStores;break;case"staff":s=await n._.user.count({where:{tenantId:e,isActive:!0}}),o=a.maxStaff;break;case"menuItems":s=await n._.menuItem.count({where:{tenantId:e,isActive:!0}}),o=a.maxMenuItems;break;case"orders":let i=new Date;i.setDate(1),i.setHours(0,0,0,0),s=await n._.order.count({where:{tenantId:e,createdAt:{gte:i}}}),o=a.maxOrders}return 0===o?{allowed:!0,current:s,max:o}:{allowed:s<o,current:s,max:o}}function o(e,t){return e.includes(t)}},5564:(e,t,a)=>{a.d(t,{Je:()=>o,Ri:()=>c,fc:()=>u,n:()=>d,n2:()=>i,nA:()=>l,uq:()=>s});var n=a(8194),r=a(14709);function s(e){return new Date("string"==typeof e?e+"T00:00:00.000Z":Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}async function o(e){let t=await (0,r.fO)(e);return{enabled:"true"===t.reservation_enabled,slotDuration:parseInt(t.reservation_slot_duration||"120"),maxAdvanceDays:parseInt(t.reservation_max_advance_days||"30"),minAdvanceHours:parseInt(t.reservation_min_advance_hours||"2"),autoConfirm:"true"===t.reservation_auto_confirm}}function i(){let e=new Date,t=e.getFullYear(),a=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",s="";for(let e=0;e<4;e++)s+=r.charAt(Math.floor(Math.random()*r.length));return`RSV-${t}${a}${n}-${s}`}function u(e,t){let[a,n]=e.split(":").map(Number),r=60*a+n+t;return`${String(Math.floor(r/60)%24).padStart(2,"0")}:${String(r%60).padStart(2,"0")}`}async function l(e,t,a,r,s,o){let i={storeId:e,tableId:t,date:a,status:{in:["pending","confirmed","seated"]},startTime:{lt:s},endTime:{gt:r}};return o&&(i.id={not:o}),!!await n._.reservation.findFirst({where:i})}async function d(e,t,a,r,s){let o=u(a,r),i=await n._.restTable.findMany({where:{storeId:e,isActive:!0,capacity:{gte:s}},orderBy:[{capacity:"asc"},{number:"asc"}]}),l=new Set((await n._.reservation.findMany({where:{storeId:e,date:t,status:{in:["pending","confirmed","seated"]},startTime:{lt:o},endTime:{gt:a}},select:{tableId:!0}})).map(e=>e.tableId));return i.filter(e=>!l.has(e.id))}function c(e,t,a){let n=new Date,[r,s]=t.split(":").map(Number),o=new Date(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),r,s,0,0),i=36e5*a.minAdvanceHours;if(o.getTime()-n.getTime()<i)return{valid:!1,error:`Reservasi harus dibuat minimal ${a.minAdvanceHours} jam sebelumnya`};let u=864e5*a.maxAdvanceDays;return o.getTime()-n.getTime()>u?{valid:!1,error:`Reservasi maksimal ${a.maxAdvanceDays} hari ke depan`}:{valid:!0}}},14709:(e,t,a)=>{a.d(t,{C5:()=>s,LK:()=>r,a3:()=>i,fO:()=>o});var n=a(8194);let r={order_protection_enabled:"false",session_duration_hours:"4",rate_limit_enabled:"false",rate_limit_max_orders:"5",online_payment_enabled:"true",bank_name:"",bank_account:"",bank_holder:"",tax_enabled:"true",tax_rate:"11",service_charge_enabled:"false",service_charge_rate:"5",auto_disable_menu_on_stock_out:"false",loyalty_enabled:"false",loyalty_points_per_amount:"1",loyalty_amount_per_point:"10000",loyalty_redemption_value:"500",loyalty_min_redemption:"10",loyalty_max_redemption:"0",reservation_enabled:"false",reservation_slot_duration:"120",reservation_max_advance_days:"30",reservation_min_advance_hours:"2",reservation_auto_confirm:"false",expense_approval_required:"true",expense_approval_min_amount:"0",attendance_clock_in_tolerance_minutes:"15",attendance_auto_clock_out_hours:"12",thermal_printer_enabled:"false",thermal_paper_width:"80mm",thermal_auto_print_receipt:"false",thermal_auto_print_kitchen:"false",receipt_show_browser_popup:"true",dine_in_require_table:"false",pos_order_flow:"default",receipt_header_line1:"",receipt_header_line2:"",receipt_header_line3:"",receipt_footer_line1:"Terima kasih!",receipt_footer_line2:"Silahkan datang lagi",receipt_footer_line3:"",receipt_feedback_qr:"true",menu_primary_color:"#4F46E5",menu_bg_color:"#F9FAFB",menu_card_color:"#FFFFFF",menu_text_color:"#111827",menu_banner_image:"",menu_font:"default",menu_layout:"card"};async function s(e,t){let a=await n._.tenantSetting.findUnique({where:{tenantId_key:{tenantId:e,key:t}}});return a?.value??r[t]??""}async function o(e){let t=await n._.tenantSetting.findMany({where:{tenantId:e}}),a={...r};for(let e of t)a[e.key]=e.value;return a}async function i(e,t){let a=Object.entries(t).map(([t,a])=>n._.tenantSetting.upsert({where:{tenantId_key:{tenantId:e,key:t}},update:{value:a},create:{tenantId:e,key:t,value:a}}));await n._.$transaction(a)}}};var t=require("../../../../webpack-runtime.js");t.C(e);var a=e=>t(t.s=e),n=t.X(0,[8948,5972,4261,2023],()=>a(9919));module.exports=n})();