module.exports=[29173,(e,t,r)=>{t.exports=e.x("@prisma/client",()=>require("@prisma/client"))},15270,e=>{"use strict";var t=e.i(29173);let r=globalThis.prisma??new t.PrismaClient({log:["error"]});e.s(["prisma",0,r])},193695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},918622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},556704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},832319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},324725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},270406,(e,t,r)=>{t.exports=e.x("next/dist/compiled/@opentelemetry/api",()=>require("next/dist/compiled/@opentelemetry/api"))},222378,e=>{"use strict";async function t(t,r){try{let{prisma:o}=await e.A(324191),a=await o.configuracion.findUnique({where:{clave:t}});if(!a)return r;switch(a.tipo){case"number":return Number(a.valor);case"boolean":return"true"===a.valor;default:return a.valor||r}}catch(e){return console.error(`Error al obtener configuraci\xf3n '${t}':`,e),r}}process.env.NEXT_PUBLIC_STOCK_MINIMO_DEFAULT,e.s(["getConfigValue",()=>t])},158388,e=>{"use strict";var t=e.i(747909),r=e.i(174017),o=e.i(996250),a=e.i(759756),n=e.i(561916),i=e.i(114444),s=e.i(837092),l=e.i(869741),c=e.i(316795),d=e.i(487718),u=e.i(995169),p=e.i(47587),m=e.i(666012),g=e.i(570101),v=e.i(626937),h=e.i(10372),x=e.i(193695);e.i(52474);var f=e.i(600220),R=e.i(89171),w=e.i(15270),_=e.i(222378);async function E(){console.log("🔍 Verificando lotes próximos a vencer...");let e=await (0,_.getConfigValue)("dias_alerta_vencimiento",7),t=new Date,r=new Date(t.getTime()+24*e*36e5);t.getTime();try{let o=await w.prisma.lotes_productos.findMany({where:{estado:"disponible",cantidad:{gt:0},fecha_vencimiento:{gte:t,lte:r}},include:{producto:{select:{id:!0,nombre:!0,es_perecedero:!0}}}});for(let r of o){let o=Math.ceil((new Date(r.fecha_vencimiento).getTime()-t.getTime())/864e5),a="baja",n="";o<=1?(a="alta",n=`\xa1URGENTE! Lote ${r.codigo_lote} vence HOY`):o<=3?(a="alta",n=`Lote ${r.codigo_lote} vence en ${o} d\xedas`):o<=e&&(a="media",n=`Lote ${r.codigo_lote} vence en ${o} d\xedas`);try{let e=r.producto?.nombre||"Producto desconocido",t=`El lote ${r.codigo_lote} del producto "${e}" vencer\xe1 el ${new Date(r.fecha_vencimiento).toLocaleDateString()}. Cantidad: ${r.cantidad}`;await w.prisma.$executeRaw`
          INSERT INTO alertas (tipo_alerta, severidad, titulo, mensaje, producto_id, leida, resuelta, detalles, created_at)
          VALUES (
            'vencimiento_lote',
            ${a},
            ${n},
            ${t},
            ${r.producto_id},
            false,
            false,
            ${JSON.stringify({lote_id:r.id,codigo_lote:r.codigo_lote,fecha_vencimiento:r.fecha_vencimiento,cantidad:Number(r.cantidad),dias_restantes:o})}::jsonb,
            NOW()
          )
          ON CONFLICT DO NOTHING
        `,console.log(`⚠️ Alerta creada: ${n}`)}catch(e){console.log(`⚠️ ${n} (alerta no guardada - tabla no existe)`)}}let a=await w.prisma.$transaction(async e=>{let r=await e.lotes_productos.findMany({where:{estado:"disponible",fecha_vencimiento:{lt:t}},include:{producto:{select:{id:!0,nombre:!0,stock_actual:!0}}}});return 0===r.length?{count:0,detalles:[]}:(console.log("\n📊 Estado ANTES de marcar lotes como vencidos:"),r.forEach(e=>{console.log(`  - Lote ${e.codigo_lote}: cantidad=${e.cantidad}, producto="${e.producto?.nombre}", stock_actual=${e.producto?.stock_actual}`)}),await e.lotes_productos.updateMany({where:{id:{in:r.map(e=>e.id)}},data:{estado:"vencido"}}),console.log(`
🚫 ${r.length} lotes marcados como vencidos`),console.log("✅ Trigger SQL sync_stock_on_lote_update() ejecutará automáticamente:"),console.log("   1. Descontar stock de productos afectados"),console.log("   2. Crear registros en historial_inventario"),console.log("   3. Evitar doble descuento (solo resta si cantidad > 0)\n"),{count:r.length,detalles:r.map(e=>({codigo_lote:e.codigo_lote,producto:e.producto?.nombre,cantidad:Number(e.cantidad),stock_antes:Number(e.producto?.stock_actual)}))})});return console.log(`✅ Verificaci\xf3n completada: ${o.length} lotes pr\xf3ximos a vencer, ${a.count} lotes vencidos`),{proximosVencer:o.length,vencidos:a.count}}catch(e){throw console.error("❌ Error al verificar lotes próximos a vencer:",e),e}}async function b(e){try{let t=e.headers.get("authorization")===`Bearer ${process.env.CRON_SECRET}`,r=e.headers.get("user-agent")||"";console.log("🔍 Iniciando verificación de lotes vencidos..."),console.log("📍 Origen:",t?"Vercel Cron (automático)":`Usuario (${r.substring(0,50)})`);let o=await E();return console.log("✅ Verificación completada:",{proximosVencer:o.proximosVencer,vencidos:o.vencidos,timestamp:new Date().toISOString()}),R.NextResponse.json({success:!0,message:"Verificación de lotes completada",proximosVencer:o.proximosVencer,vencidos:o.vencidos,ejecutadoPor:t?"cron":"usuario",timestamp:new Date().toISOString()})}catch(e){return console.error("❌ Error al verificar lotes:",e),R.NextResponse.json({error:"Error al verificar lotes vencidos",details:e instanceof Error?e.message:"Error desconocido"},{status:500})}}e.s(["GET",()=>b],447033);var y=e.i(447033);let C=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/lotes/check-vencimientos/route",pathname:"/api/lotes/check-vencimientos",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/lotes/check-vencimientos/route.ts",nextConfigOutput:"standalone",userland:y}),{workAsyncStorage:N,workUnitAsyncStorage:T,serverHooks:$}=C;function O(){return(0,o.patchFetch)({workAsyncStorage:N,workUnitAsyncStorage:T})}async function A(e,t,o){C.isDev&&(0,a.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let R="/api/lotes/check-vencimientos/route";R=R.replace(/\/index$/,"")||"/";let w=await C.prepare(e,t,{srcPage:R,multiZoneDraftMode:!1});if(!w)return t.statusCode=400,t.end("Bad Request"),null==o.waitUntil||o.waitUntil.call(o,Promise.resolve()),null;let{buildId:_,params:E,nextConfig:b,parsedUrl:y,isDraftMode:N,prerenderManifest:T,routerServerContext:$,isOnDemandRevalidate:O,revalidateOnlyGenerated:A,resolvedPathname:k,clientReferenceManifest:S,serverActionsManifest:P}=w,I=(0,l.normalizeAppPath)(R),j=!!(T.dynamicRoutes[I]||T.routes[k]),D=async()=>((null==$?void 0:$.render404)?await $.render404(e,t,y,!1):t.end("This page could not be found"),null);if(j&&!N){let e=!!T.routes[k],t=T.dynamicRoutes[I];if(t&&!1===t.fallback&&!e){if(b.experimental.adapterPath)return await D();throw new x.NoFallbackError}}let q=null;!j||C.isDev||N||(q="/index"===(q=k)?"/":q);let M=!0===C.isDev||!j,U=j&&!M;P&&S&&(0,i.setReferenceManifestsSingleton)({page:R,clientReferenceManifest:S,serverActionsManifest:P,serverModuleMap:(0,s.createServerModuleMap)({serverActionsManifest:P})});let H=e.method||"GET",V=(0,n.getTracer)(),L=V.getActiveScopeSpan(),F={params:E,prerenderManifest:T,renderOpts:{experimental:{authInterrupts:!!b.experimental.authInterrupts},cacheComponents:!!b.cacheComponents,supportsDynamicResponse:M,incrementalCache:(0,a.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:b.cacheLife,waitUntil:o.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,o)=>C.onRequestError(e,t,o,$)},sharedContext:{buildId:_}},K=new c.NodeNextRequest(e),B=new c.NodeNextResponse(t),G=d.NextRequestAdapter.fromNodeNextRequest(K,(0,d.signalFromNodeResponse)(t));try{let i=async e=>C.handle(G,F).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=V.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==u.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let o=r.get("next.route");if(o){let t=`${H} ${o}`;e.setAttributes({"next.route":o,"http.route":o,"next.span_name":t}),e.updateName(t)}else e.updateName(`${H} ${R}`)}),s=!!(0,a.getRequestMeta)(e,"minimalMode"),l=async a=>{var n,l;let c=async({previousCacheEntry:r})=>{try{if(!s&&O&&A&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=await i(a);e.fetchMetrics=F.renderOpts.fetchMetrics;let l=F.renderOpts.pendingWaitUntil;l&&o.waitUntil&&(o.waitUntil(l),l=void 0);let c=F.renderOpts.collectedTags;if(!j)return await (0,m.sendResponse)(K,B,n,F.renderOpts.pendingWaitUntil),null;{let e=await n.blob(),t=(0,g.toNodeOutgoingHttpHeaders)(n.headers);c&&(t[h.NEXT_CACHE_TAGS_HEADER]=c),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==F.renderOpts.collectedRevalidate&&!(F.renderOpts.collectedRevalidate>=h.INFINITE_CACHE)&&F.renderOpts.collectedRevalidate,o=void 0===F.renderOpts.collectedExpire||F.renderOpts.collectedExpire>=h.INFINITE_CACHE?void 0:F.renderOpts.collectedExpire;return{value:{kind:f.CachedRouteKind.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:o}}}}catch(t){throw(null==r?void 0:r.isStale)&&await C.onRequestError(e,t,{routerKind:"App Router",routePath:R,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:U,isOnDemandRevalidate:O})},$),t}},d=await C.handleResponse({req:e,nextConfig:b,cacheKey:q,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:T,isRoutePPREnabled:!1,isOnDemandRevalidate:O,revalidateOnlyGenerated:A,responseGenerator:c,waitUntil:o.waitUntil,isMinimalMode:s});if(!j)return null;if((null==d||null==(n=d.value)?void 0:n.kind)!==f.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==d||null==(l=d.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});s||t.setHeader("x-nextjs-cache",O?"REVALIDATED":d.isMiss?"MISS":d.isStale?"STALE":"HIT"),N&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let u=(0,g.fromNodeOutgoingHttpHeaders)(d.value.headers);return s&&j||u.delete(h.NEXT_CACHE_TAGS_HEADER),!d.cacheControl||t.getHeader("Cache-Control")||u.get("Cache-Control")||u.set("Cache-Control",(0,v.getCacheControlHeader)(d.cacheControl)),await (0,m.sendResponse)(K,B,new Response(d.value.body,{headers:u,status:d.value.status||200})),null};L?await l(L):await V.withPropagatedContext(e.headers,()=>V.trace(u.BaseServerSpan.handleRequest,{spanName:`${H} ${R}`,kind:n.SpanKind.SERVER,attributes:{"http.method":H,"http.target":e.url}},l))}catch(t){if(t instanceof x.NoFallbackError||await C.onRequestError(e,t,{routerKind:"App Router",routePath:I,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:U,isOnDemandRevalidate:O})}),j)throw t;return await (0,m.sendResponse)(K,B,new Response(null,{status:500})),null}}e.s(["handler",()=>A,"patchFetch",()=>O,"routeModule",()=>C,"serverHooks",()=>$,"workAsyncStorage",()=>N,"workUnitAsyncStorage",()=>T],158388)},324191,e=>{e.v(e=>Promise.resolve().then(()=>e(15270)))}];

//# sourceMappingURL=%5Broot-of-the-server%5D__c6f546fa._.js.map