"use strict";(()=>{var e={};e.id=1548,e.ids=[1548],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")},55443:(e,t,r)=>{r.r(t),r.d(t,{originalPathname:()=>y,patchFetch:()=>O,requestAsyncStorage:()=>I,routeModule:()=>l,serverHooks:()=>N,staticGenerationAsyncStorage:()=>p});var a={};r.r(a),r.d(a,{GET:()=>c});var n=r(49303),i=r(88716),s=r(60670),o=r(87070),u=r(95456),d=r(8194),m=r(45239);async function c(e){try{let t=await (0,u.ts)();if(!t)return o.NextResponse.json({error:"Unauthorized"},{status:401});if(!(0,u.MH)(t.role,["owner","admin","manager"]))return o.NextResponse.json({error:"Forbidden"},{status:403});let r=await (0,m.F)(t.tenantId,"advanced_analytics");if(r)return r;let a=e.nextUrl.searchParams.get("storeId"),n=e.nextUrl.searchParams.get("period")||"30d",i=30;"7d"===n&&(i=7),"90d"===n&&(i=90);let s=new Date;s.setDate(s.getDate()-i);let c={tenantId:t.tenantId};t.storeId?c.storeId=t.storeId:a&&(c.storeId=a);let l=t.tenantId,I=t.storeId||a,p=I?"AND o.storeId = ?":"",N=I?[l,s,I]:[l,s],y=(await d._.$queryRawUnsafe(`SELECT
        mi.id,
        mi.name,
        c.name as category,
        SUM(oi.quantity) as quantity,
        SUM(oi.subtotal) as revenue,
        AVG(oi.price) as avgPrice
      FROM order_items oi
      INNER JOIN orders o ON o.id = oi.orderId
      INNER JOIN menu_items mi ON mi.id = oi.menuItemId
      INNER JOIN categories c ON c.id = mi.categoryId
      WHERE o.tenantId = ?
        AND o.status = 'completed'
        AND o.paymentStatus = 'paid'
        AND o.createdAt >= ?
        ${p}
      GROUP BY mi.id, mi.name, c.name
      ORDER BY revenue DESC
      LIMIT 20`,...N)).map(e=>({id:e.id,name:e.name,category:e.category,quantity:Number(e.quantity),revenue:Number(e.revenue),avgPrice:Math.round(Number(e.avgPrice))})),O=(await d._.$queryRawUnsafe(`SELECT
        c.name as category,
        SUM(oi.quantity) as quantity,
        SUM(oi.subtotal) as revenue
      FROM order_items oi
      INNER JOIN orders o ON o.id = oi.orderId
      INNER JOIN menu_items mi ON mi.id = oi.menuItemId
      INNER JOIN categories c ON c.id = mi.categoryId
      WHERE o.tenantId = ?
        AND o.status = 'completed'
        AND o.paymentStatus = 'paid'
        AND o.createdAt >= ?
        ${p}
      GROUP BY c.name
      ORDER BY revenue DESC`,...N)).map(e=>({category:e.category,quantity:Number(e.quantity),revenue:Number(e.revenue)})),g=(await d._.$queryRawUnsafe(`SELECT
        mi.id,
        mi.name,
        c.name as category,
        COALESCE(agg.quantity, 0) as quantity,
        agg.lastOrdered
      FROM menu_items mi
      INNER JOIN categories c ON c.id = mi.categoryId
      LEFT JOIN (
        SELECT
          oi.menuItemId,
          SUM(oi.quantity) as quantity,
          MAX(o.createdAt) as lastOrdered
        FROM order_items oi
        INNER JOIN orders o ON o.id = oi.orderId
        WHERE o.tenantId = ?
          AND o.status = 'completed'
          AND o.paymentStatus = 'paid'
          AND o.createdAt >= ?
          ${p}
        GROUP BY oi.menuItemId
      ) agg ON agg.menuItemId = mi.id
      WHERE mi.tenantId = ?
        AND mi.isActive = 1
        AND (agg.quantity IS NULL OR agg.quantity < 5)
      ORDER BY COALESCE(agg.quantity, 0) ASC
      LIMIT 10`,...N,l)).map(e=>({id:e.id,name:e.name,category:e.category,quantity:Number(e.quantity),lastOrdered:e.lastOrdered?"string"==typeof e.lastOrdered?e.lastOrdered:new Date(e.lastOrdered).toISOString().slice(0,10):null})),R=(await d._.$queryRawUnsafe(`SELECT
        mi1.name as item1,
        mi2.name as item2,
        COUNT(*) as count
      FROM order_items oi1
      INNER JOIN order_items oi2
        ON oi1.orderId = oi2.orderId
        AND oi1.menuItemId < oi2.menuItemId
      INNER JOIN orders o ON o.id = oi1.orderId
      INNER JOIN menu_items mi1 ON mi1.id = oi1.menuItemId
      INNER JOIN menu_items mi2 ON mi2.id = oi2.menuItemId
      WHERE o.tenantId = ?
        AND o.status = 'completed'
        AND o.paymentStatus = 'paid'
        AND o.createdAt >= ?
        ${p}
      GROUP BY oi1.menuItemId, oi2.menuItemId, mi1.name, mi2.name
      ORDER BY count DESC
      LIMIT 10`,...N)).map(e=>({item1:e.item1,item2:e.item2,count:Number(e.count)}));return o.NextResponse.json({menuPerformance:y,categoryBreakdown:O,slowMoving:g,topCombos:R})}catch(e){return console.error("Products analytics error:",e),o.NextResponse.json({error:"Internal server error"},{status:500})}}let l=new n.AppRouteRouteModule({definition:{kind:i.x.APP_ROUTE,page:"/api/analytics/products/route",pathname:"/api/analytics/products",filename:"route",bundlePath:"app/api/analytics/products/route"},resolvedPagePath:"D:\\PROJECT\\resto-saas\\src\\app\\api\\analytics\\products\\route.ts",nextConfigOutput:"",userland:a}),{requestAsyncStorage:I,staticGenerationAsyncStorage:p,serverHooks:N}=l,y="/api/analytics/products/route";function O(){return(0,s.patchFetch)({serverHooks:N,staticGenerationAsyncStorage:p})}},95456:(e,t,r)=>{r.d(t,{Gv:()=>c,MH:()=>N,PT:()=>y,RA:()=>l,WX:()=>I,c_:()=>m,ts:()=>p});var a=r(41482),n=r.n(a),i=r(42023),s=r.n(i),o=r(71615),u=r(8194);let d=process.env.JWT_SECRET||"fallback-secret-change-me";async function m(e){return s().hash(e,12)}async function c(e,t){return s().compare(e,t)}function l(e){return n().sign(e,d,{expiresIn:"7d"})}function I(e){try{return n().verify(e,d)}catch{return null}}async function p(){let e=await (0,o.cookies)(),t=e.get("token")?.value;if(!t)return null;let r=I(t);return r?await u._.user.findUnique({where:{id:r.userId},include:{tenant:!0,store:!0}}):null}function N(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,r)=>{r.d(t,{_:()=>n});let a=require("@prisma/client"),n=globalThis.prisma??new a.PrismaClient},45239:(e,t,r)=>{r.d(t,{F:()=>i});var a=r(87070),n=r(15230);async function i(e,t){let r=await (0,n.p6)(e);return(0,n.U6)(r.features,t)?null:a.NextResponse.json({error:"Fitur ini tidak tersedia pada paket Anda. Silakan upgrade."},{status:403})}},15230:(e,t,r)=>{r.d(t,{MN:()=>i,U6:()=>s,p6:()=>n});var a=r(8194);async function n(e){let t=await a._.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 i(e,t){let r=await n(e),i=0,s=0;switch(t){case"stores":i=await a._.store.count({where:{tenantId:e,isActive:!0}}),s=r.maxStores;break;case"staff":i=await a._.user.count({where:{tenantId:e,isActive:!0}}),s=r.maxStaff;break;case"menuItems":i=await a._.menuItem.count({where:{tenantId:e,isActive:!0}}),s=r.maxMenuItems;break;case"orders":let o=new Date;o.setDate(1),o.setHours(0,0,0,0),i=await a._.order.count({where:{tenantId:e,createdAt:{gte:o}}}),s=r.maxOrders}return 0===s?{allowed:!0,current:i,max:s}:{allowed:i<s,current:i,max:s}}function s(e,t){return e.includes(t)}}};var t=require("../../../../webpack-runtime.js");t.C(e);var r=e=>t(t.s=e),a=t.X(0,[8948,5972,4261,2023],()=>r(55443));module.exports=a})();