@aiquants/daily-report 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -0
  3. package/dist/client.d.mts +449 -0
  4. package/dist/client.d.ts +449 -0
  5. package/dist/client.js +7 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/client.mjs +7 -0
  8. package/dist/client.mjs.map +1 -0
  9. package/dist/index.d.mts +42 -0
  10. package/dist/index.d.ts +42 -0
  11. package/dist/index.js +2 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/index.mjs +2 -0
  14. package/dist/index.mjs.map +1 -0
  15. package/dist/logger-D3krZrNK.d.mts +29 -0
  16. package/dist/logger-D3krZrNK.d.ts +29 -0
  17. package/dist/server.d.mts +1515 -0
  18. package/dist/server.d.ts +1515 -0
  19. package/dist/server.js +10 -0
  20. package/dist/server.js.map +1 -0
  21. package/dist/server.mjs +10 -0
  22. package/dist/server.mjs.map +1 -0
  23. package/dist/sse-schema-CK7cUnEo.d.ts +1986 -0
  24. package/dist/sse-schema-yl5AaSsj.d.mts +1986 -0
  25. package/dist/types-CVhwLhSN.d.mts +76 -0
  26. package/dist/types-CVhwLhSN.d.ts +76 -0
  27. package/package.json +108 -0
  28. package/src/client/components/business-day-thumb-overlay.tsx +19 -0
  29. package/src/client/components/daily-report-comment-item.tsx +81 -0
  30. package/src/client/components/daily-report-comment-section.tsx +166 -0
  31. package/src/client/components/daily-report-detail-list.tsx +676 -0
  32. package/src/client/components/daily-report-edit-form.tsx +81 -0
  33. package/src/client/components/daily-report-list.tsx +1024 -0
  34. package/src/client/components/daily-report-page.tsx +147 -0
  35. package/src/client/components/daily-report-resolved-content.tsx +139 -0
  36. package/src/client/components/unread-indicator.tsx +13 -0
  37. package/src/client/config-context.tsx +129 -0
  38. package/src/client/contexts/daily-report-action-context.tsx +910 -0
  39. package/src/client/hooks/use-daily-report-comments.ts +73 -0
  40. package/src/client/hooks/use-daily-report-sse-connection.ts +86 -0
  41. package/src/client/hooks/use-daily-report.spec.ts +155 -0
  42. package/src/client/hooks/use-daily-report.ts +426 -0
  43. package/src/client/hooks/use-dynamic-viewport-height.ts +127 -0
  44. package/src/client/route-helpers.ts +76 -0
  45. package/src/client/ui/button.tsx +42 -0
  46. package/src/client/ui/cn.ts +14 -0
  47. package/src/client/ui/input.tsx +21 -0
  48. package/src/client/ui/label.tsx +16 -0
  49. package/src/client/ui/switch.tsx +19 -0
  50. package/src/client/ui/tabs.tsx +40 -0
  51. package/src/client/ui/textarea.tsx +19 -0
  52. package/src/client/utils/constants.ts +29 -0
  53. package/src/client.ts +21 -0
  54. package/src/index.ts +10 -0
  55. package/src/server/cache.ts +165 -0
  56. package/src/server/etag.ts +18 -0
  57. package/src/server/external-source.ts +60 -0
  58. package/src/server/handlers.ts +543 -0
  59. package/src/server/ports.ts +68 -0
  60. package/src/server/response.ts +37 -0
  61. package/src/server/schema.ts +266 -0
  62. package/src/server/service.spec.ts +97 -0
  63. package/src/server/service.ts +1308 -0
  64. package/src/server/sse-reader.spec.ts +55 -0
  65. package/src/server/sse-reader.ts +223 -0
  66. package/src/server.ts +83 -0
  67. package/src/shared/business-date.spec.ts +61 -0
  68. package/src/shared/business-date.ts +84 -0
  69. package/src/shared/comment-adapter.ts +78 -0
  70. package/src/shared/logger.ts +47 -0
  71. package/src/shared/sse-schema.ts +147 -0
  72. package/src/shared/text-utils.ts +57 -0
  73. package/src/shared/types.ts +76 -0
package/dist/server.js ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";var Se=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var tt=(r,t)=>{for(var i in t)Se(r,i,{get:t[i],enumerable:!0})},rt=(r,t,i,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let m of Ze(t))!et.call(r,m)&&m!==i&&Se(r,m,{get:()=>t[m],enumerable:!(l=Ve(t,m))||l.enumerable});return r};var nt=r=>rt(Se({},"__esModule",{value:!0}),r);var gt={};tt(gt,{DailyReportSseReader:()=>pe,SqlResultCache:()=>ce,createDailyReportHandlers:()=>Ne,createDailyReportServer:()=>yt,createDailyReportService:()=>Ee,createEpochStore:()=>Ie,defineDailyReportSchema:()=>mt,generateETag:()=>Re,isStreamIdLte:()=>me,jsonResponseWithETag:()=>Z,transformJsonArray:()=>pt});module.exports=nt(gt);var Ie=r=>({async getEpoch(t){try{let i=await r?.getClient();if(!i)return 0;let l=await i.get(t);return l?Number(l):0}catch{return 0}},async incrementEpoch(t){try{let i=await r?.getClient();if(!i)return;await i.incr(t)}catch{}}}),ce=class{constructor(t,i){this.config=t;this.epochStore=i;this.buckets=new Map;this.inFlight=new Map;this.invalidate=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.getOrFetch=async t=>{let{cacheKey:i,forceRefresh:l,snapshot:m}=t,f=this.buckets.get(i);if(l&&(this.buckets.delete(i),this.inFlight.delete(i)),!l&&f&&f.expireAt>Date.now())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(f.epoch===c)return m?f.records.map(W=>structuredClone(W)):f.records;this.buckets.delete(i)}else return m?f.records.map(c=>structuredClone(c)):f.records;if(!l&&this.inFlight.has(i)){let c=await this.inFlight.get(i);return m?c.map(W=>structuredClone(W)):c}let O;O=(async()=>{let c=await t.fetcher();if(l||this.inFlight.get(i)===O){let W=Date.now()+(t.ttlMsOverride??this.config.defaultTtlMs),p=t.epochKey?await this.epochStore.getEpoch(t.epochKey):0;this.buckets.set(i,{records:c,expireAt:W,epoch:p})}return c})(),l||this.inFlight.set(i,O);try{let c=await O;return m?c.map(W=>structuredClone(W)):c}finally{this.inFlight.delete(i)}};this.flush=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.invalidatePrefix=t=>{for(let i of this.buckets.keys())i.startsWith(t)&&this.buckets.delete(i);for(let i of this.inFlight.keys())i.startsWith(t)&&this.inFlight.delete(i)}}};var at=/^\d{4}-\d{2}-\d{2}$/,ot=/^\d{4}\/\d{2}\/\d{2}$/,ke=r=>r<10?`0${r}`:`${r}`,Be=r=>{if(Number.isNaN(r.getTime()))return null;let t=r.getFullYear(),i=ke(r.getMonth()+1),l=ke(r.getDate());return`${t}-${i}-${l}`},G=r=>{if(r==null)return null;if(r instanceof Date)return Be(r);let t=r.trim();if(t==="")return null;if(at.test(t))return t;if(ot.test(t))return t.replaceAll("/","-");let i=new Date(t);return Be(i)};var te=(r,t,i=console)=>{let l=m=>typeof m=="string"?[`${t} ${m}`]:[t,m];return{debug:(m,...f)=>{r<=0&&i.debug(...l(m),...f)},info:(m,...f)=>{r<=1&&i.info(...l(m),...f)},warn:(m,...f)=>{r<=2&&i.warn(...l(m),...f)},error:(m,...f)=>{r<=3&&i.error(...l(m),...f)}}};var s=require("zod"),it=s.z.object({name:s.z.string(),affiliation:s.z.string().nullable()}),st=s.z.object({name:s.z.string().nullable(),text:s.z.string().nullable(),color:s.z.string().nullable()}),lt=s.z.object({id:s.z.number(),name:s.z.string(),color:s.z.string().nullable()}),Ue=s.z.object({id:s.z.number(),userId:s.z.string(),userName:s.z.string(),content:s.z.string(),createdAt:s.z.string(),isMine:s.z.boolean()}),_e=s.z.object({reportHubId:s.z.number(),date:s.z.string().nullable(),createdAt:s.z.string().nullable(),author:s.z.string(),userId:s.z.string(),employeeName:s.z.string().nullable(),updatedBy:s.z.string().nullable(),updatedAt:s.z.string().nullable(),category:s.z.string().nullable(),creationCategory:s.z.string().nullable(),visitTimeFrom:s.z.string().nullable(),visitTimeTo:s.z.string().nullable(),customerName:s.z.string().nullable(),interviewers:s.z.array(it),subject:s.z.string().nullable(),content:s.z.string().nullable(),comments:s.z.array(st),isRead:s.z.boolean(),isStarred:s.z.boolean(),labels:s.z.array(lt),commentItems:s.z.array(Ue)}),dt=s.z.object({type:s.z.literal("connected")}),he=s.z.object({type:s.z.literal("status-update"),reportHubId:s.z.number(),statusType:s.z.enum(["star","read"]),value:s.z.boolean(),clientTempId:s.z.string(),recipientRawUserId:s.z.number().optional()}),Ce=s.z.object({type:s.z.literal("comment-add"),reportHubId:s.z.number(),comment:Ue,clientTempId:s.z.string()}),Ae=s.z.object({type:s.z.literal("comment-delete"),reportHubId:s.z.number(),commentId:s.z.number(),clientTempId:s.z.string()}),Te=s.z.object({type:s.z.literal("report-create"),reportHubId:s.z.number(),report:_e,clientTempId:s.z.string(),recipientRawUserId:s.z.number().optional()}),Me=s.z.object({type:s.z.literal("report-update"),reportHubId:s.z.number(),report:_e,clientTempId:s.z.string(),recipientRawUserId:s.z.number().optional()}),ve=s.z.object({type:s.z.literal("report-publish"),reportHubId:s.z.number(),report:_e,clientTempId:s.z.string()}),xe=s.z.object({type:s.z.literal("report-delete"),reportHubId:s.z.number(),clientTempId:s.z.string()}),He=s.z.discriminatedUnion("type",[dt,he,Ce,Ae,Te,Me,ve,xe]);var Ye=require("crypto"),Re=r=>{let t=JSON.stringify(r);return`"${(0,Ye.createHash)("sha256").update(t).digest("hex")}"`};var ut=te(1,"[Response]"),Z=(r,t,i,l=200,m=ut)=>{let f=Re(i),O=r.headers.get("If-None-Match");m.info(`[jsonResponseWithETag] ETag: ${f}, If-None-Match: ${O}`);let c=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:f});return t&&c.append("Set-Cookie",t),r.method==="GET"&&l===200&&O===f?new Response(null,{status:304,headers:c}):new Response(JSON.stringify(i),{status:l,headers:c})};var qe=require("events");var me=(r,t)=>{let[i,l]=r.split("-").map(Number),[m,f]=t.split("-").map(Number);return i!==m?i<m:l<=f},pe=class{constructor(t){this.config=t;this._emitter=new qe.EventEmitter;this._state="idle";this._refCount=0;this._lastId="0-0";this._emitter.setMaxListeners(0),this._logger=t.logger??te(1,"[SSE Reader]")}subscribe(t,i){return this._emitter.on("entry",t),i&&this._emitter.on("error",i),this._refCount++,this._refCount===1&&this._startLoop(),()=>{this._emitter.removeListener("entry",t),i&&this._emitter.removeListener("error",i),this._refCount--,this._refCount<=0&&(this._refCount=0,this._stopLoop())}}async destroy(){this._refCount=0,await this._stopLoop(),this._emitter.removeAllListeners(),this._lastId="0-0"}async _startLoop(){for(;this._state==="stopping";)await new Promise(t=>setTimeout(t,50));if(this._state!=="running"){this._state="running";try{this._client=await this.config.redis?.createClient()}catch(t){this._state="idle",this._emitter.emit("error",t instanceof Error?t:new Error("Failed to create Redis client for SSE reader"));return}if(!this._client){this._state="idle",this._emitter.emit("error",new Error("Failed to create Redis client for SSE reader"));return}this._client.on("error",t=>{this._logger.error("Redis client error:",t)});try{for(;this._state==="running"&&this._client?.isOpen;){let t=await this._client.xRead([{key:this.config.streamKey,id:this._lastId}],{BLOCK:5e3,COUNT:100});if(t)for(let i of t)for(let l of i.messages){this._lastId=l.id;try{let m=l.message?.data?JSON.parse(l.message.data):null,f=m?.type;if((f==="report-create"||f==="report-delete"||f==="report-publish")&&this.config.cache.invalidatePrefix("daily-report:ids"),f==="comment-add"||f==="comment-delete"||f==="status-update"){let O=m?.reportHubId;typeof O=="number"&&(this.config.cache.invalidate(`daily-report:detail:${O}`),this.config.cache.invalidatePrefix(`daily-report:detail:${O}:user:`))}}catch{}this._emitter.emit("entry",{id:l.id,message:l.message})}}}catch(t){!(t?.constructor?.name==="ClientClosedError")&&this._state==="running"&&(this._logger.error("xRead loop error:",t),this._emitter.emit("error",t))}finally{if(this._client?.isOpen)try{await this._client.quit()}catch{}this._client=void 0,this._state="idle",this._refCount>0&&this._startLoop()}}}async _stopLoop(){if(this._state==="running"){if(this._state="stopping",this._client?.isOpen)try{await this._client.quit()}catch{}for(;this._state!=="idle";)await new Promise(t=>setTimeout(t,50))}}};var v=(r,t)=>new Response(JSON.stringify(r),{status:t?.status??200,headers:{"Content-Type":"application/json"}});function Ne(r){let{authenticate:t,service:i,encodeUserId:l,redis:m,sseReader:f,streamKey:O}=r,c=r.loginRedirectPath??"/auth/login",W=r.logger??te(3,"[DailyReportAPI]"),p=r.logger??te(1,"[DailyReportSSE]"),g=async({request:A})=>{let{user:k,cookie:_}=await t(A,{failureRedirect:c}),P=new Headers;_&&P.append("Set-Cookie",_);let C=null;k&&(C=await i.getUserIdByExternalId(k.id));let S=C?l(C):null;return{data:{user:k,userId:S},headers:P}},$={"business-date":async(A,k,_,P)=>{let C=G(A.searchParams.get("businessDate")),S=A.searchParams.get("forceRefresh")==="true";if(!C)return Z(_,k,{error:{message:"Invalid business date"}},400);let B=await i.getDailyReportsByBusinessDateByExternalId(C,P.id,{forceRefresh:S});return Z(_,k,{businessDate:C,reports:B},200)},ids:async(A,k,_,P)=>{let C=A.searchParams.get("forceRefresh")==="true",S=await i.getDailyReportIdsByExternalId(P.id,{forceRefresh:C});return Z(_,k,{ids:S},200)},report:async(A,k,_,P)=>{let C=A.searchParams.get("reportHubId"),S=A.searchParams.get("forceRefresh")==="true",B=C?Number.parseInt(C,10):NaN;if(!Number.isFinite(B)||B<=0)return Z(_,k,{error:{message:"Invalid reportHubId"}},400);let x=await i.getDailyReportDetailByIdByExternalId(B,P.id,{snapshot:!0,forceRefresh:S});return x?Z(_,k,{report:x},200):Z(_,k,{error:{message:"Report not found"}},404)}};return{index:{loader:g},api:{loader:async({request:A,params:k})=>{let{user:_,cookie:P}=await t(A,{failureRedirect:null}),C=P??null;if(!_)return Z(A,C,{error:{message:"Unauthorized"}},401);if(A.method!=="GET")return Z(A,C,{error:{message:"Method not allowed"}},405);let S=k.endpoint??"",B=$[S];if(!B)return Z(A,C,{error:{message:"Unknown endpoint"}},404);let x=Date.now();try{let w=new URL(A.url);return await B(w,C,A,_)}catch(w){let q=Date.now()-x,j=w instanceof Error?w:new Error(String(w));return W.error(`500 endpoint=${S} elapsed=${q}ms name=${j.name} code=${"code"in j?j.code:"N/A"} message=${j.message}`),W.error("Stack:",j.stack),Z(A,C,{error:{message:"Internal Server Error"}},500)}},action:async({request:A,params:k})=>{let{user:_}=await t(A,{failureRedirect:null});if(!_)return v({error:"Unauthorized"},{status:401});if(k.endpoint!=="action")return v({error:"Unknown endpoint"},{status:404});let C=await i.getUserIdByExternalId(_.id);if(!C)return v({error:"User not found"},{status:404});let S=await A.formData(),B=S.get("intent"),x=S.get("reportHubId"),w=x?Number(x):NaN,q=S.get("businessDate"),j=Number(S.get("operationTimestamp")),N=S.get("clientTempId");if(!N)return v({error:"clientTempId required"},{status:400});if(B!=="create"&&(!w||Number.isNaN(w)))return v({error:"Invalid reportHubId"},{status:400});switch(B){case"create":{if(!q)return v({error:"businessDate required"},{status:400});let y=await i.createDailyReport(C,q,N);return v({status:"OK",intent:"create",report:y,reportHubId:String(y.reportHubId),clientTempId:N})}case"update":{let y=S.get("title"),L=S.get("content");try{return await i.updateDailyReport(w,C,{title:y,content:L},N),v({status:"OK",intent:"update",reportHubId:String(w),clientTempId:N})}catch(T){if(T instanceof Error){if(T.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if(T.message==="Not Found")return v({error:"Report not found"},{status:404})}throw T}}case"publish":try{let y=await i.publishDailyReport(w,C,N);return v({status:"OK",intent:"publish",reportHubId:String(w),clientTempId:N,report:y})}catch(y){if(y instanceof Error){if(y.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if(y.message==="Not Found")return v({error:"Report not found"},{status:404})}throw y}case"delete":try{return await i.deleteDailyReport(w,C,N),v({status:"OK",intent:"delete",reportHubId:String(w),clientTempId:N})}catch(y){if(y instanceof Error){if(y.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if(y.message==="Not Found")return v({error:"Report not found"},{status:404})}throw y}case"toggleStar":{let y=S.get("isStarred");if(y===null)return v({error:"isStarred required"},{status:400});let L=y==="true",T=await i.setStarStatus(C,w,q,L,N);return v({status:"OK",intent:"toggleStar",updatedStatus:{isStarred:T.isStarred,isRead:T.isRead},operationTimestamp:j,reportHubId:String(w),clientTempId:N})}case"toggleRead":{let y=S.get("isRead");if(y===null)return v({error:"isRead required"},{status:400});let L=y==="true",T=await i.setReadStatus(C,w,q,L,N);return v({status:"OK",intent:"toggleRead",updatedStatus:{isStarred:T.isStarred,isRead:T.isRead},operationTimestamp:j,reportHubId:String(w),clientTempId:N})}case"addComment":{let y=S.get("content");if(!y)return v({error:"Content required"},{status:400});let L=await i.addComment(C,w,y,q,N),T={...L,userId:L.userId};return v({status:"OK",intent:"addComment",newComment:T,reportHubId:String(w),clientTempId:N})}case"deleteComment":{let y=Number(S.get("commentId"));if(!y||Number.isNaN(y))return v({error:"Invalid commentId"},{status:400});try{return await i.deleteComment(C,w,y,q,N),v({status:"OK",reportHubId:String(w),deletedCommentId:String(y),clientTempId:N})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return v({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return v({error:"Comment not found"},{status:404})}throw L}}default:return v({error:"Invalid intent"},{status:400})}}},sse:{loader:async({request:A,params:k})=>{let{user:_}=await t(A,{failureRedirect:null});if(!_)return new Response("Unauthorized",{status:401});let P=await i.getUserIdByExternalId(_.id);if(!P)return new Response("Forbidden",{status:403});if(k.endpoint!=="updates")return new Response("Not Found",{status:404});let S=new URL(A.url).searchParams.get("lastEventId")||A.headers.get("Last-Event-ID"),B=new TextEncoder,x=null,w=null,q=null,j=!1,N=()=>{if(!j){if(j=!0,w&&(clearInterval(w),w=null),q&&(q(),q=null),x)try{x.desiredSize!==null&&x.close()}catch{}finally{x=null}j=!1}},y=(T,K)=>{if(K.data)try{let M=JSON.parse(K.data),Q=He.safeParse(M);if(!Q.success){p.error("SSE message validation failed:",Q.error.format());return}let ee=Q.data,ae=typeof M.recipientRawUserId=="number"?M.recipientRawUserId:void 0;if(ee.type==="status-update"){if(ae===void 0||ae!==P)return}else if(ae!==void 0&&ae!==P)return;let se;if("recipientRawUserId"in M){let{recipientRawUserId:$e,...le}=M;se=JSON.stringify(le)}else se=K.data;x&&x.desiredSize!==null&&x.enqueue(B.encode(`id: ${T}
2
+ data: ${se}
3
+
4
+ `))}catch(M){p.error(`[SSE:${P}] processEntry error:`,M)}},L=new ReadableStream({async start(T){x=T,w=setInterval(()=>{try{x&&x.desiredSize!==null?x.enqueue(B.encode(`: keep-alive
5
+
6
+ `)):N()}catch{N()}},5e3),A.signal.addEventListener("abort",()=>{N()});let K=S||"0-0";if(q=f.subscribe(M=>{me(M.id,K)||(K=M.id,y(M.id,M.message))},M=>{p.error(`[SSE:${P}] Fan-Out reader error:`,M),N()}),!S)try{let M=await m?.getClient();if(M){let Q=await M.xRevRange(O,"+","-",{COUNT:1});Q.length>0&&!me(Q[0].id,K)&&(K=Q[0].id)}}catch{}if(x&&x.desiredSize!==null){let M=`data: ${JSON.stringify({type:"connected"})}
7
+
8
+ `,Q=K!=="0-0"?`id: ${K}
9
+ ${M}`:M;x.enqueue(B.encode(Q))}if(S)try{let M=await m?.getClient();if(M){let Q=await M.xRange(O,S,"+",{COUNT:1e3});for(let ee of Q)ee.id!==S&&(me(ee.id,K)||(K=ee.id,y(ee.id,ee.message)))}}catch(M){p.error(`[SSE:${P}] catch-up xRange error:`,M)}},cancel(){N()}});return new Response(L,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}})}}}}var a=require("drizzle-orm");var ne=r=>(0,a.getColumns)(r);function Ee(r){let{db:t,tables:i,userTable:l,resolveUserId:m,encodeUserId:f,redis:O,cache:c,epochs:W}=r,{hub:p,internal:g,comment:$,label:F,hubLabel:X,userStatus:E}=i,A=r.externalSources??[],k=r.draftLabelName,_=r.logger??te(1,"[DailyReportService]"),P="daily-report:ids",C=r.idsTtlMs??18e4,S="daily-report:ids:epoch",B="daily-report:business-date:",x=r.businessDateTtlMs??3e5,w="daily-report:date-epoch:",q="daily-report:detail-epoch:",j=r.streamKey??"daily-report:sse-stream",N=r.streamMaxLen??1e4,y=e=>W.incrementEpoch(e),L=async(e,n)=>{let d=await O?.getClient();if(!d){_.warn(`[SSE] Redis client unavailable (${n})`);return}let u=Date.now();try{await d.xAdd(j,"*",{data:JSON.stringify(e)},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:N}});let b=Date.now()-u;b>1e3&&_.warn(`[SSE] Slow publish (${n}): ${b}ms`)}catch(b){_.error(`[SSE] Redis publish failed (${n}):`,b)}},T=(e,n)=>{if(!e)return null;let d=e instanceof Date?e:new Date(e);if(Number.isNaN(d.getTime()))return typeof e=="string"?e:null;let u=n==="YYYY-MM-DD HH:mm:ss"?{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}:{year:"numeric",month:"2-digit",day:"2-digit"};return(n==="YYYY-MM-DD HH:mm:ss"?d.toLocaleString("ja-JP",u):d.toLocaleDateString("ja-JP",u)).replace(/\//g,"-")},K=e=>e==null||e===""?null:/^\d+$/.test(e)?f(Number(e)):e,M=()=>{let e={};for(let n of A)e[`ext_${n.sourceType}`]=ne(n.table);return e},Q=e=>{let n=e;for(let d of A)n=n.leftJoin(d.table,(0,a.and)((0,a.eq)(p.sourceType,d.sourceType),(0,a.eq)(p.sourceIdNum,d.idColumn)));return n},ee=(e,n)=>{let{hub:d,internal:u}=e,b=d.summary,h=[],R=null,I=null,U=null,z=null,H=null,V=null,re=[],J=A.find(D=>D.sourceType===d.sourceType),ie=J?e[`ext_${J.sourceType}`]:void 0;if(J&&ie){let D=J.mapRow(ie);D.content!==void 0&&(b=D.content),D.employeeName!==void 0&&(V=D.employeeName),D.category!==void 0&&(R=D.category),D.creationCategory!==void 0&&(I=D.creationCategory),D.visitTimeFrom!==void 0&&(U=D.visitTimeFrom),D.visitTimeTo!==void 0&&(z=D.visitTimeTo),D.customerName!==void 0&&(H=D.customerName),D.interviewers!==void 0&&(h=D.interviewers),D.comments!==void 0&&(re=D.comments)}else d.sourceType==="Internal"&&u&&(b=u.body);let ue=e.labels??[],Y=e.comments??[];return{reportHubId:d.id,date:T(d.businessDate,"YYYY-MM-DD"),author:e.creatorName??K(d.createdBy)??"",userId:d.userId?f(d.userId):"",createdAt:T(d.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:T(d.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:K(d.updatedBy),employeeName:V??e.creatorName??K(d.createdBy),category:R,creationCategory:I,visitTimeFrom:U,visitTimeTo:z,customerName:H,interviewers:h,subject:d.title,content:b,comments:re,isRead:e.isRead??!1,isStarred:e.isStarred??!1,labels:ue.map(D=>({id:D.id,name:D.name,color:D.color})),commentItems:Y.map(D=>({...D,userId:f(D.userId),isMine:n?D.userId===n:!1}))}},ae=async e=>{let n=(0,a.aliasedTable)(X,"draft_label");return(await t.select({reportHubId:p.id,businessDate:p.businessDate}).from(p).leftJoin(n,(0,a.and)((0,a.eq)(n.hubId,p.id),(0,a.eq)(n.labelId,t.select({id:F.id}).top(1).from(F).where((0,a.eq)(F.name,k))))).where((0,a.and)((0,a.isNull)(p.deletedAt),(0,a.or)((0,a.eq)(p.userId,e),(0,a.isNull)(n.hubId)))).orderBy((0,a.desc)(p.businessDate),(0,a.desc)(p.id))).map(u=>({...u,businessDate:T(u.businessDate,"YYYY-MM-DD")}))},se=async e=>(await Q(t.select({hub:ne(p),internal:ne(g),creatorName:l.displayName,...M()}).from(p)).leftJoin(g,(0,a.eq)(p.id,g.hubId)).leftJoin(l,(0,a.eq)(p.userId,l.id)).where((0,a.and)((0,a.eq)(p.businessDate,a.sql`${e}`),(0,a.isNull)(p.deletedAt))).orderBy((0,a.desc)(p.id))).map(d=>ee(d)),$e=e=>`${B}${e}`,le=new Map,ge=async e=>{if(!r.disableUserIdCache&&le.has(e))return le.get(e)??null;let n=await m(e);return n!==null&&!r.disableUserIdCache&&le.set(e,n),n},Oe=async(e,{forceRefresh:n=!1,snapshot:d=!1,ttlMsOverride:u}={})=>{let b=await ge(e);if(!b)return[];let h=`${P}:user:${b}`;return c.getOrFetch({cacheKey:h,fetcher:async()=>await ae(b),forceRefresh:n,snapshot:d,ttlMsOverride:u??C,epochKey:S})},Fe=(e,{forceRefresh:n=!1,snapshot:d=!1,ttlMsOverride:u}={})=>{let b=G(e);return b?c.getOrFetch({cacheKey:$e(b),fetcher:()=>se(b),forceRefresh:n,snapshot:d,ttlMsOverride:u??x}):Promise.resolve([])},fe=null,oe=async()=>{if(fe!==null)return fe;let[e]=await t.select({id:F.id}).top(1).from(F).where((0,a.eq)(F.name,k));return e?(fe=e.id,fe):null},ze=async(e,n,{forceRefresh:d=!1,snapshot:u=!1,ttlMsOverride:b}={})=>{let h=await ge(n);if(!h)return[];let R=G(e);if(!R)return[];let I=`daily-report:date:${R}:user:${h}`;return c.getOrFetch({cacheKey:I,fetcher:async()=>{let U=await oe(),z=(0,a.aliasedTable)(X,"draft_label"),H=await Q(t.select({hub:ne(p),internal:ne(g),isRead:E.isRead,isStarred:E.isStarred,creatorName:l.displayName,...M()}).from(p)).leftJoin(g,(0,a.eq)(p.id,g.hubId)).leftJoin(E,(0,a.and)((0,a.eq)(p.id,E.hubId),(0,a.eq)(E.userId,h))).leftJoin(z,(0,a.and)((0,a.eq)(z.hubId,p.id),(0,a.eq)(z.labelId,U??-1))).leftJoin(l,(0,a.eq)(p.userId,l.id)).where((0,a.and)((0,a.eq)(p.businessDate,a.sql`${R}`),(0,a.isNull)(p.deletedAt),(0,a.or)((0,a.eq)(p.userId,h),(0,a.isNull)(z.hubId)))).orderBy((0,a.desc)(p.id));if(H.length===0)return[];let V=H.map(Y=>Y.hub.id),re=await t.select({hubId:X.hubId,id:F.id,name:F.name,color:F.color}).from(X).innerJoin(F,(0,a.eq)(X.labelId,F.id)).where((0,a.inArray)(X.hubId,V)),J=await t.select({hubId:$.hubId,id:$.id,body:$.body,createdAt:$.createdAt,userId:$.userId,userName:l.displayName}).from($).leftJoin(l,(0,a.eq)($.userId,l.id)).where((0,a.inArray)($.hubId,V)).orderBy((0,a.asc)($.createdAt)),ie=new Map,ue=new Map;for(let Y of re){let D=ie.get(Y.hubId);D||(D=[],ie.set(Y.hubId,D)),D.push({id:Y.id,name:Y.name,color:Y.color})}for(let Y of J){let D=ue.get(Y.hubId);D||(D=[],ue.set(Y.hubId,D)),D.push({id:Y.id,content:Y.body,createdAt:T(Y.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Y.userId,userName:Y.userName||""})}return H.map(Y=>{let D=Y.hub.id;return ee({...Y,labels:ie.get(D)||[],comments:ue.get(D)||[]},h)})},forceRefresh:d,snapshot:u,ttlMsOverride:b??x,epochKey:`${w}${R}`})},de=async(e,n,{forceRefresh:d=!1,snapshot:u=!1,ttlMsOverride:b}={})=>{let h=`daily-report:detail:${e}:user:${n}`;return(await c.getOrFetch({cacheKey:h,fetcher:async()=>{let I=await Q(t.select({hub:ne(p),internal:ne(g),isRead:E.isRead,isStarred:E.isStarred,creatorName:l.displayName,...M()}).from(p)).leftJoin(g,(0,a.eq)(p.id,g.hubId)).leftJoin(E,(0,a.and)((0,a.eq)(p.id,E.hubId),(0,a.eq)(E.userId,n))).leftJoin(l,(0,a.eq)(p.userId,l.id)).where((0,a.and)((0,a.eq)(p.id,e),(0,a.isNull)(p.deletedAt)));if(I.length===0)return[];let U=I[0].hub.id,z=await t.select({id:F.id,name:F.name,color:F.color}).from(X).innerJoin(F,(0,a.eq)(X.labelId,F.id)).where((0,a.eq)(X.hubId,U)),H=await t.select({id:$.id,body:$.body,createdAt:$.createdAt,userId:$.userId,userName:l.displayName}).from($).leftJoin(l,(0,a.eq)($.userId,l.id)).where((0,a.eq)($.hubId,U)).orderBy((0,a.asc)($.createdAt)),V=z.map(J=>({id:J.id,name:J.name,color:J.color})),re=H.map(J=>({id:J.id,content:J.body,createdAt:T(J.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:J.userId,userName:J.userName||""}));return[ee({...I[0],labels:V,comments:re},n)]},forceRefresh:d,snapshot:u,ttlMsOverride:b??x,epochKey:`${q}${e}`}))[0]??null},Ke=async(e,n,d={})=>{let u=await ge(n);return u?de(e,u,d):null},Je=async(e,n,d,u,b)=>{let h=await t.select().top(1).from(E).where((0,a.and)((0,a.eq)(E.hubId,n),(0,a.eq)(E.userId,e))),R;if(h.length>0?h[0].isStarred!==u?R=(await t.update(E).set({isStarred:u,updatedAt:new Date,updatedBy:String(e)}).output().where((0,a.and)((0,a.eq)(E.hubId,n),(0,a.eq)(E.userId,e))))[0]:R=h[0]:R=(await t.insert(E).output().values({hubId:n,userId:e,isStarred:u,isRead:!1,createdAt:new Date,createdBy:String(e),updatedAt:new Date,updatedBy:String(e)}))[0],d){let I=G(d);I&&(c.invalidate(`daily-report:date:${I}:user:${e}`),await y(`${w}${I}`))}return c.invalidate(`daily-report:detail:${n}`),c.invalidate(`daily-report:detail:${n}:user:${e}`),await y(`${q}${n}`),await L(he.parse({type:"status-update",reportHubId:n,recipientRawUserId:e,statusType:"star",value:u,clientTempId:b}),"setStarStatus"),R},je=async(e,n,d,u,b)=>{let h=await t.select().top(1).from(E).where((0,a.and)((0,a.eq)(E.hubId,n),(0,a.eq)(E.userId,e))),R;if(h.length>0?h[0].isRead!==u?R=(await t.update(E).set({isRead:u,updatedAt:new Date,updatedBy:String(e)}).output().where((0,a.and)((0,a.eq)(E.hubId,n),(0,a.eq)(E.userId,e))))[0]:R=h[0]:R=(await t.insert(E).output().values({hubId:n,userId:e,isRead:u,isStarred:!1,createdAt:new Date,createdBy:String(e),updatedAt:new Date,updatedBy:String(e)}))[0],d){let I=G(d);I&&(c.invalidate(`daily-report:date:${I}:user:${e}`),await y(`${w}${I}`))}return c.invalidate(`daily-report:detail:${n}`),c.invalidate(`daily-report:detail:${n}:user:${e}`),await y(`${q}${n}`),await L(he.parse({type:"status-update",reportHubId:n,recipientRawUserId:e,statusType:"read",value:u,clientTempId:b}),"setReadStatus"),R},Qe=async(e,n,d,u,b)=>{let[h]=await t.insert($).output().values({hubId:n,userId:e,body:d,createdAt:new Date,createdBy:String(e),updatedAt:new Date,updatedBy:String(e)}),[R]=await t.select({displayName:l.displayName}).top(1).from(l).where((0,a.eq)(l.id,e)),I=R?.displayName??"Unknown";if(u){let z=G(u);z&&(c.invalidatePrefix(`daily-report:date:${z}:user:`),await y(`${w}${z}`))}c.invalidate(`daily-report:detail:${n}`),c.invalidatePrefix(`daily-report:detail:${n}:user:`),await y(`${q}${n}`);let U={id:h.id,userId:f(h.userId),userName:I,content:h.body,createdAt:T(h.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await L(Ce.parse({type:"comment-add",reportHubId:n,comment:U,clientTempId:b}),"addComment"),U},We=async(e,n)=>await e.select().top(1).from($).where((0,a.eq)($.id,n)),Xe=async(e,n,d,u,b)=>{let h=await We(t,d);if(h.length===0)throw new Error("Not Found");if(h[0].userId!==e)throw new Error("Unauthorized");if(await t.delete($).where((0,a.eq)($.id,d)),u){let R=G(u);R&&(c.invalidatePrefix(`daily-report:date:${R}:user:`),await y(`${w}${R}`))}c.invalidate(`daily-report:detail:${n}`),c.invalidatePrefix(`daily-report:detail:${n}:user:`),await y(`${q}${n}`),await L(Ae.parse({type:"comment-delete",reportHubId:n,commentId:d,clientTempId:b}),"deleteComment")},Ge=async(e,n,d)=>{_.info("createDailyReport called",{userId:e,businessDate:n});let[u]=await t.select({displayName:l.displayName}).from(l).where((0,a.eq)(l.id,e)),b=u?.displayName??f(e);try{let h=await t.transaction(async U=>{_.info("Starting transaction");let z=`internal-temp-${Date.now()}-${Math.random()}`,[H]=await U.insert(p).output().values({sourceType:"Internal",sourceId:z,businessDate:new Date(n),userId:e,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(e),updatedAt:new Date,updatedBy:String(e)});await U.update(p).set({sourceId:String(H.id)}).where((0,a.eq)(p.id,H.id)),_.info("Hub created",H),await U.insert(g).values({hubId:H.id,body:"",createdAt:new Date,createdBy:String(e),updatedAt:new Date,updatedBy:String(e)}),_.info("Internal created"),_.info("Calling getDraftLabelId");let V=await oe();_.info("draftLabelId",V);let re=[];return V&&(await U.insert(X).values({hubId:H.id,labelId:V,createdAt:new Date,createdBy:String(e)}),re.push({id:V,name:k,color:null})),_.info("Label assigned"),{reportHubId:H.id,date:n,createdAt:T(H.createdAt,"YYYY-MM-DD HH:mm:ss"),author:b,userId:f(e),employeeName:b,updatedBy:f(e),updatedAt:T(H.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:H.title,content:"",comments:[],isRead:!0,isStarred:!1,labels:re,commentItems:[]}}),R=G(n);R&&c.invalidate(`daily-report:date:${R}:user:${e}`),c.invalidatePrefix(B),c.invalidate(`${P}:user:${e}`),await y(S),R&&await y(`${w}${R}`);let I=await de(h.reportHubId,e,{forceRefresh:!0});if(I){let U=await oe(),z=U?I.labels.some(H=>H.id===U):!1;await L(Te.parse({type:"report-create",reportHubId:I.reportHubId,report:I,clientTempId:d,recipientRawUserId:z?e:void 0}),"createDailyReport")}return I??h}catch(h){throw _.error("Error in createDailyReport",h),h}},be=async(e,n)=>await e.select().top(1).from(p).where((0,a.eq)(p.id,n)),we=async(e,n,d)=>{await e.update(p).set(d).where((0,a.eq)(p.id,n))},Le=async(e,n,d)=>{await e.update(g).set(d).where((0,a.eq)(g.hubId,n))},Pe=async(e,n,d)=>{await e.delete(X).where((0,a.and)((0,a.eq)(X.hubId,n),(0,a.eq)(X.labelId,d)))};return{streamKey:j,streamMaxLen:N,getUserIdByExternalId:ge,getDailyReportIdsByExternalId:Oe,getDailyReportsByBusinessDate:Fe,getDailyReportsByBusinessDateByExternalId:ze,getDailyReportDetailById:de,getDailyReportDetailByIdByExternalId:Ke,getDraftLabelId:oe,setStarStatus:Je,setReadStatus:je,addComment:Qe,deleteComment:Xe,createDailyReport:Ge,updateDailyReport:async(e,n,d,u)=>{let b=await be(t,e);if(!b.length||b[0].deletedAt)throw new Error("Not Found");if(b[0].userId!==n)throw new Error("Unauthorized");await t.transaction(async R=>{d.title!==void 0&&await we(R,e,{title:d.title,updatedAt:new Date,updatedBy:String(n)}),d.content!==void 0&&await Le(R,e,{body:d.content,updatedAt:new Date,updatedBy:String(n)})}),c.invalidatePrefix(`daily-report:detail:${e}:user:`),c.invalidatePrefix(B);let h=await de(e,n,{forceRefresh:!0});if(h){let R=await oe(),I=R?h.labels.some(U=>U.id===R):!1;await L(Me.parse({type:"report-update",reportHubId:h.reportHubId,report:h,clientTempId:u,recipientRawUserId:I?n:void 0}),"updateDailyReport")}},publishDailyReport:async(e,n,d)=>{let u=await be(t,e);if(!u.length)throw new Error("Not Found");if(u[0].userId!==n)throw new Error("Unauthorized");let b=await oe();if(!b)return null;if(await Pe(t,e,b),c.invalidatePrefix(`daily-report:detail:${e}:user:`),c.invalidatePrefix(B),c.invalidatePrefix(P),await y(S),u[0].businessDate){let I=G(T(u[0].businessDate,"YYYY-MM-DD"));I&&await y(`${w}${I}`)}let h=G(T(u[0].businessDate,"YYYY-MM-DD"));h&&c.invalidate(`daily-report:date:${h}:user:${n}`);let R=await de(e,n,{forceRefresh:!0});return R&&await L(ve.parse({type:"report-publish",reportHubId:R.reportHubId,report:R,clientTempId:d}),"publishDailyReport"),R??null},deleteDailyReport:async(e,n,d)=>{let u=await be(t,e);if(!u.length||u[0].deletedAt)throw new Error("Not Found");if(u[0].userId!==n)throw new Error("Unauthorized");if(await we(t,e,{deletedAt:new Date,deletedBy:String(n),updatedAt:new Date,updatedBy:String(n)}),c.invalidatePrefix(`daily-report:detail:${e}:user:`),c.invalidatePrefix(B),c.invalidatePrefix(P),await y(S),u[0].businessDate){let b=G(T(u[0].businessDate,"YYYY-MM-DD"));b&&await y(`${w}${b}`)}await L(xe.parse({type:"report-delete",reportHubId:e,clientTempId:d}),"deleteDailyReport")},findDailyReportHubById:be,updateDailyReportHub:we,updateDailyReportInternal:Le,deleteDailyReportLabel:Pe}}var ct=te(1,"[DailyReportExternalSource]"),pt=(r,t,i,l=ct)=>{if(!r)return[];try{let m=JSON.parse(r);return Array.isArray(m)?m.map(i).filter(f=>f!==null):(l.warn(`Unexpected ${t} format: not an array`),[])}catch(m){return l.warn(`Failed to parse ${t}:`,m),[]}};var ye=require("drizzle-orm"),o=require("drizzle-orm/mssql-core");function mt(r,t){let i=(0,o.mssqlSchema)(r),l=t.userTable,m=i.table("DailyReportHub",{id:(0,o.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,o.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,o.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,o.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(ye.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,o.date)("business_date"),userId:(0,o.bigint)("user_id",{mode:"number"}),title:(0,o.nvarchar)("title",{length:200}),summary:(0,o.nvarchar)("summary",{length:"max"}),createdAt:(0,o.datetime2)("created_at").notNull(),createdBy:(0,o.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,o.datetime2)("updated_at").notNull(),updatedBy:(0,o.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,o.datetime2)("deleted_at"),deletedBy:(0,o.nvarchar)("deleted_by",{length:50})},g=>[(0,o.primaryKey)({name:`${r}_DailyReportHub_pk`,columns:[g.id]}),(0,o.foreignKey)({name:`${r}_DailyReportHub_user_id_fk`,columns:[g.userId],foreignColumns:[l.id]}),(0,o.index)(`${r}_DailyReportHub_business_date_index`).on(g.businessDate),(0,o.index)(`${r}_DailyReportHub_updated_at_index`).on(g.updatedAt),(0,o.index)(`${r}_DailyReportHub_source_index`).on(g.sourceType,g.sourceId),(0,o.index)(`${r}_DailyReportHub_user_id_index`).on(g.userId),(0,o.index)(`${r}_DailyReportHub_business_date_id_index`).on((0,ye.desc)(g.businessDate),(0,ye.desc)(g.id)),(0,o.index)(`${r}_DailyReportHub_deleted_at_index`).on(g.deletedAt)]),f=i.table("DailyReportInternal",{hubId:(0,o.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,o.nvarchar)("body",{length:"max"}),metadata:(0,o.nvarchar)("metadata",{length:"max"}),createdAt:(0,o.datetime2)("created_at").notNull(),createdBy:(0,o.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,o.datetime2)("updated_at").notNull(),updatedBy:(0,o.nvarchar)("updated_by",{length:50}).notNull()},g=>[(0,o.primaryKey)({name:`${r}_DailyReportInternal_pk`,columns:[g.hubId]}),(0,o.foreignKey)({name:`${r}_DailyReportInternal_hub_id_fk`,columns:[g.hubId],foreignColumns:[m.id]})]),O=i.table("DailyReportComment",{id:(0,o.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,o.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,o.bigint)("user_id",{mode:"number"}).notNull(),body:(0,o.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,o.datetime2)("created_at").notNull(),createdBy:(0,o.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,o.datetime2)("updated_at").notNull(),updatedBy:(0,o.nvarchar)("updated_by",{length:50}).notNull()},g=>[(0,o.primaryKey)({name:`${r}_DailyReportComment_pk`,columns:[g.id]}),(0,o.foreignKey)({name:`${r}_DailyReportComment_hub_id_fk`,columns:[g.hubId],foreignColumns:[m.id]}),(0,o.foreignKey)({name:`${r}_DailyReportComment_user_id_fk`,columns:[g.userId],foreignColumns:[l.id]}),(0,o.index)(`${r}_DailyReportComment_hub_id_index`).on(g.hubId)]),c=i.table("DailyReportLabel",{id:(0,o.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,o.bigint)("user_id",{mode:"number"}),name:(0,o.nvarchar)("name",{length:50}).notNull(),color:(0,o.nvarchar)("color",{length:20}),sortOrder:(0,o.int)("sort_order"),createdAt:(0,o.datetime2)("created_at").notNull(),createdBy:(0,o.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,o.datetime2)("updated_at").notNull(),updatedBy:(0,o.nvarchar)("updated_by",{length:50}).notNull()},g=>[(0,o.primaryKey)({name:`${r}_DailyReportLabel_pk`,columns:[g.id]}),(0,o.foreignKey)({name:`${r}_DailyReportLabel_user_id_fk`,columns:[g.userId],foreignColumns:[l.id]})]),W=i.table("DailyReportHub_Label",{hubId:(0,o.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,o.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,o.datetime2)("created_at").notNull(),createdBy:(0,o.nvarchar)("created_by",{length:50}).notNull()},g=>[(0,o.primaryKey)({name:`${r}_DailyReportHub_Label_pk`,columns:[g.hubId,g.labelId]}),(0,o.foreignKey)({name:`${r}_DailyReportHub_Label_hub_id_fk`,columns:[g.hubId],foreignColumns:[m.id]}),(0,o.foreignKey)({name:`${r}_DailyReportHub_Label_label_id_fk`,columns:[g.labelId],foreignColumns:[c.id]})]),p=i.table("DailyReportUserStatus",{hubId:(0,o.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,o.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,o.bit)("is_read").default(!1).notNull(),isStarred:(0,o.bit)("is_starred").default(!1).notNull(),createdAt:(0,o.datetime2)("created_at").notNull(),createdBy:(0,o.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,o.datetime2)("updated_at").notNull(),updatedBy:(0,o.nvarchar)("updated_by",{length:50}).notNull()},g=>[(0,o.primaryKey)({name:`${r}_DailyReportUserStatus_pk`,columns:[g.hubId,g.userId]}),(0,o.foreignKey)({name:`${r}_DailyReportUserStatus_hub_id_fk`,columns:[g.hubId],foreignColumns:[m.id]}),(0,o.foreignKey)({name:`${r}_DailyReportUserStatus_user_id_fk`,columns:[g.userId],foreignColumns:[l.id]})]);return{hub:m,internal:f,comment:O,label:c,hubLabel:W,userStatus:p}}function yt(r){let t=Ie(r.redis),i=new ce({defaultTtlMs:r.cacheDefaultTtlMs??6e4},t),l=Ee({...r,cache:i,epochs:t}),m=new pe({redis:r.redis,streamKey:l.streamKey,cache:i,logger:r.logger}),f=Ne({authenticate:r.authenticate,service:l,encodeUserId:r.encodeUserId,redis:r.redis,sseReader:m,streamKey:l.streamKey,loginRedirectPath:r.loginRedirectPath,logger:r.logger});return{service:l,cache:i,epochs:t,sseReader:m,streamKey:l.streamKey,...f}}0&&(module.exports={DailyReportSseReader,SqlResultCache,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,defineDailyReportSchema,generateETag,isStreamIdLte,jsonResponseWithETag,transformJsonArray});
10
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts","../src/server/cache.ts","../src/shared/business-date.ts","../src/shared/logger.ts","../src/shared/sse-schema.ts","../src/server/etag.ts","../src/server/response.ts","../src/server/sse-reader.ts","../src/server/handlers.ts","../src/server/service.ts","../src/server/external-source.ts","../src/server/schema.ts"],"sourcesContent":["/**\n * Server entry of @aiquants/daily-report: schema factory, service, SSE reader, and handler factories.\n * @aiquants/daily-report の server エントリ。スキーマファクトリ・サービス・SSE リーダー・ハンドラ工場を公開。\n */\nimport { createEpochStore, SqlResultCache } from \"./server/cache\"\nimport type { DailyReportExternalSource } from \"./server/external-source\"\nimport { createDailyReportHandlers } from \"./server/handlers\"\nimport type { DailyReportAuthenticate } from \"./server/ports\"\nimport { createDailyReportService, type DailyReportServiceConfig } from \"./server/service\"\nimport { DailyReportSseReader } from \"./server/sse-reader\"\n\nexport * from \"./server/cache\"\nexport { generateETag } from \"./server/etag\"\nexport * from \"./server/external-source\"\nexport * from \"./server/handlers\"\nexport * from \"./server/ports\"\nexport * from \"./server/response\"\nexport * from \"./server/schema\"\nexport * from \"./server/service\"\nexport * from \"./server/sse-reader\"\n\n/** createDailyReportServer の設定 (サービス設定 + 認証ポート + ハンドラ設定)。 */\nexport type DailyReportServerConfig = Omit<DailyReportServiceConfig, \"cache\" | \"epochs\"> & {\n /** リクエスト認証ポート。 */\n authenticate: DailyReportAuthenticate\n /** 未ログイン時のリダイレクト先 (index.loader 用、既定 \"/auth/login\")。 */\n loginRedirectPath?: string\n /** SQL 結果キャッシュの既定 TTL (既定 60,000ms)。 */\n cacheDefaultTtlMs?: number\n /** 外部ソースアダプタ群 (レガシー日報テーブル等)。 */\n externalSources?: DailyReportExternalSource[]\n}\n\n/**\n * One-stop factory wiring cache, service, SSE fan-out reader, and route handlers.\n * キャッシュ・サービス・SSE Fan-Out リーダー・ルートハンドラを一括結線するファクトリ。\n *\n * @example\n * const server = createDailyReportServer({ db, tables, userTable, resolveUserId, encodeUserId, authenticate, redis })\n * // routes:\n * // daily_report._index → server.index.loader (+ data() ラップ)\n * // daily_report.api.$endpoint → server.api.loader / server.api.action\n * // sse.daily_report.$endpoint → server.sse.loader\n */\nexport function createDailyReportServer(config: DailyReportServerConfig) {\n // epoch ストアと SQL 結果キャッシュ (サービスと SSE リーダーで同一インスタンスを共有する)\n const epochs = createEpochStore(config.redis)\n const cache = new SqlResultCache({ defaultTtlMs: config.cacheDefaultTtlMs ?? 60_000 }, epochs)\n\n const service = createDailyReportService({ ...config, cache, epochs })\n\n const sseReader = new DailyReportSseReader({\n redis: config.redis,\n streamKey: service.streamKey,\n cache,\n logger: config.logger,\n })\n\n const handlers = createDailyReportHandlers({\n authenticate: config.authenticate,\n service,\n encodeUserId: config.encodeUserId,\n redis: config.redis,\n sseReader,\n streamKey: service.streamKey,\n loginRedirectPath: config.loginRedirectPath,\n logger: config.logger,\n })\n\n return {\n /** データアクセスサービス (CRUD + キャッシュ + SSE publish)。 */\n service,\n /** SQL 結果キャッシュ (サービス・SSE リーダー共有インスタンス)。 */\n cache,\n /** クロスワーカー epoch ストア。 */\n epochs,\n /** SSE Fan-Out 共有リーダー。 */\n sseReader,\n /** SSE Redis Stream キー。 */\n streamKey: service.streamKey,\n ...handlers,\n }\n}\n","/**\n * In-memory SQL result cache with TTL, snapshot, and cross-worker epoch (via redis) support.\n * TTL・スナップショット・クロスワーカー epoch (redis 経由) を備えた SQL 結果のインメモリキャッシュ。\n *\n * epoch は任意注入の redis ポート経由で取得・更新する (未注入時は常に 0 = epoch 無効)。\n */\nimport type { DailyReportRedisProvider } from \"./ports\"\n\nexport type SqlResultCacheQueryOptions = {\n forceRefresh?: boolean\n snapshot?: boolean\n ttlMsOverride?: number\n epochKey?: string\n}\n\n/**\n * Creates epoch helpers bound to an optional redis provider.\n * 任意の redis プロバイダーに束縛された epoch ヘルパーを生成する処理。\n */\nexport const createEpochStore = (redis?: DailyReportRedisProvider) => ({\n /**\n * Gets the current epoch value from Redis.\n * Redis からエポック値を取得する。エラー時は 0 を返す (常に re-fetch = safe 方向)。\n */\n async getEpoch(epochKey: string): Promise<number> {\n try {\n const client = await redis?.getClient()\n if (!client) return 0\n const val = await client.get(epochKey)\n return val ? Number(val) : 0\n } catch {\n return 0\n }\n },\n /**\n * Increments the epoch counter in Redis.\n * Redis のエポックカウンターをインクリメントする。\n */\n async incrementEpoch(epochKey: string): Promise<void> {\n try {\n const client = await redis?.getClient()\n if (!client) return\n await client.incr(epochKey)\n } catch {\n // Redis エラー時は epoch 更新をスキップ (次回 GET で 0 → stale 扱い → re-fetch)\n }\n },\n})\n\nexport type EpochStore = ReturnType<typeof createEpochStore>\n\n/**\n * In-memory cache for SQL query results with TTL and snapshot support.\n * TTLとスナップショット機能を備えたSQLクエリ結果のインメモリキャッシュ。\n */\nexport class SqlResultCache {\n private readonly buckets = new Map<string, { records: readonly unknown[]; expireAt: number; epoch: number }>()\n private readonly inFlight = new Map<string, Promise<readonly unknown[]>>()\n\n constructor(\n private readonly config: { defaultTtlMs: number },\n private readonly epochStore: EpochStore,\n ) {}\n\n /**\n * Invalidates a specific cache bucket.\n * 指定されたキャッシュバケットを無効化します。\n */\n invalidate = (cacheKey: string): void => {\n this.buckets.delete(cacheKey)\n this.inFlight.delete(cacheKey)\n }\n\n /**\n * Retrieves records from cache or fetches them if expired/missing.\n * キャッシュからレコードを取得するか、期限切れや未存在の場合はフェッチします。\n */\n getOrFetch = async <T>(\n opts: {\n cacheKey: string\n fetcher: () => Promise<readonly T[]>\n } & SqlResultCacheQueryOptions,\n ): Promise<readonly T[]> => {\n const { cacheKey, forceRefresh, snapshot } = opts\n const bucket = this.buckets.get(cacheKey)\n\n // 強制リフレッシュ時はキャッシュと進行中のリクエストをクリア\n if (forceRefresh) {\n this.buckets.delete(cacheKey)\n this.inFlight.delete(cacheKey)\n }\n\n // 有効なキャッシュがあれば返却 (epoch check 込み)\n if (!forceRefresh && bucket && bucket.expireAt > Date.now()) {\n if (opts.epochKey) {\n // epochKey 指定時は Redis の epoch と比較して stale を検出\n const currentEpoch = await this.epochStore.getEpoch(opts.epochKey)\n if (bucket.epoch === currentEpoch) {\n return snapshot ? (bucket.records.map((r) => structuredClone(r)) as T[]) : (bucket.records as T[])\n }\n // epoch 不一致 → stale bucket を除去して re-fetch へ\n this.buckets.delete(cacheKey)\n } else {\n return snapshot ? (bucket.records.map((r) => structuredClone(r)) as T[]) : (bucket.records as T[])\n }\n }\n\n // 進行中のリクエストがあれば相乗り\n if (!forceRefresh && this.inFlight.has(cacheKey)) {\n const shared = (await this.inFlight.get(cacheKey)) as readonly T[]\n return snapshot ? shared.map((r) => structuredClone(r)) : shared\n }\n\n // 新規フェッチとキャッシュ更新\n // 自己参照 (this.inFlight.get(cacheKey) === promise) のため、定義前参照を回避する確定代入アサーション\n let promise!: Promise<readonly T[]>\n promise = (async () => {\n const records = await opts.fetcher()\n // invalidation 中に完了したリクエストはキャッシュに書き込まない(レース防止)\n // ただし forceRefresh の場合は常に書き込む\n if (forceRefresh || this.inFlight.get(cacheKey) === promise) {\n const expireAt = Date.now() + (opts.ttlMsOverride ?? this.config.defaultTtlMs)\n // キャッシュ保存時に現在の epoch を記録\n const epoch = opts.epochKey ? await this.epochStore.getEpoch(opts.epochKey) : 0\n this.buckets.set(cacheKey, { records, expireAt, epoch })\n }\n return records\n })()\n\n if (!forceRefresh) this.inFlight.set(cacheKey, promise as Promise<readonly unknown[]>)\n\n try {\n const result = await promise\n return snapshot ? result.map((r) => structuredClone(r)) : result\n } finally {\n this.inFlight.delete(cacheKey)\n }\n }\n\n /**\n * Clears the cache for a specific key.\n * 指定されたキーのキャッシュをクリアします。\n */\n flush = (cacheKey: string): void => {\n this.buckets.delete(cacheKey)\n this.inFlight.delete(cacheKey)\n }\n\n /**\n * Invalidates cache buckets matching a prefix.\n * 指定されたプレフィックスに一致するキャッシュバケットを無効化します。\n */\n invalidatePrefix = (prefix: string): void => {\n for (const key of this.buckets.keys()) {\n if (key.startsWith(prefix)) {\n this.buckets.delete(key)\n }\n }\n for (const key of this.inFlight.keys()) {\n if (key.startsWith(prefix)) {\n this.inFlight.delete(key)\n }\n }\n }\n}\n","/**\n * Business date normalization and formatting helper functions.\n * 営業日の正規化とフォーマットを支援するユーティリティ群。\n */\n\ntype BusinessDateInput = string | Date | null | undefined\n\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\nconst SLASH_DATE_PATTERN = /^\\d{4}\\/\\d{2}\\/\\d{2}$/\n\nconst zeroPad = (value: number): string => {\n return value < 10 ? `0${value}` : `${value}`\n}\n\nconst normalizeFromDate = (value: Date): string | null => {\n if (Number.isNaN(value.getTime())) {\n return null\n }\n\n const year = value.getFullYear()\n const month = zeroPad(value.getMonth() + 1)\n const day = zeroPad(value.getDate())\n return `${year}-${month}-${day}`\n}\n\n/**\n * Normalizes business date input into YYYY-MM-DD format string.\n * 営業日を YYYY-MM-DD 形式の文字列へ正規化する。\n */\nexport const normalizeBusinessDateKey = (value: BusinessDateInput): string | null => {\n if (value === null || value === undefined) {\n return null\n }\n\n if (value instanceof Date) {\n return normalizeFromDate(value)\n }\n\n const trimmed = value.trim()\n if (trimmed === \"\") {\n return null\n }\n\n if (ISO_DATE_PATTERN.test(trimmed)) {\n return trimmed\n }\n\n if (SLASH_DATE_PATTERN.test(trimmed)) {\n return trimmed.replaceAll(\"/\", \"-\")\n }\n\n const parsed = new Date(trimmed)\n return normalizeFromDate(parsed)\n}\n\n/**\n * Converts normalized business date into display format YYYY-MM-DD.\n * 正規化済みの営業日を YYYY-MM-DD 形式の表示文字列へ変換する。\n */\nexport const formatBusinessDateDisplay = (value: BusinessDateInput): string | null => {\n const normalized = normalizeBusinessDateKey(value)\n if (!normalized) {\n return null\n }\n return normalized\n}\n\n/**\n * Parses normalized business date into Date object.\n * 正規化した営業日を Date オブジェクトへ変換する。\n */\nexport const parseBusinessDateKeyToDate = (value: BusinessDateInput): Date | null => {\n const normalized = normalizeBusinessDateKey(value)\n if (!normalized) {\n return null\n }\n\n const [year, month, day] = normalized.split(\"-\").map((part) => Number.parseInt(part, 10))\n if ([year, month, day].some((component) => Number.isNaN(component))) {\n return null\n }\n\n return new Date(year, month - 1, day)\n}\n","/**\n * Minimal level-filtered logger used internally by the daily-report package.\n * daily-report パッケージ内部で使う最小のレベルフィルタ付きロガー。\n *\n * 消費アプリのロガー実装 (console 互換の debug/info/warn/error) を注入でき、\n * 未注入時は console にフォールバックする。\n */\n\n/** 出力フィルタリング用のログレベル。 */\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n NONE = 4,\n}\n\n/** Console 互換のロガーインターフェース。 */\nexport interface DailyReportLogger {\n debug(message?: unknown, ...optionalParams: unknown[]): void\n info(message?: unknown, ...optionalParams: unknown[]): void\n warn(message?: unknown, ...optionalParams: unknown[]): void\n error(message?: unknown, ...optionalParams: unknown[]): void\n}\n\n/**\n * Creates a prefixed, level-filtered logger delegating to the given implementation.\n * 指定実装へ委譲するプレフィックス付き・レベルフィルタ付きロガーを生成する処理。\n */\nexport const createLogger = (level: LogLevel, prefix: string, impl: DailyReportLogger = console): DailyReportLogger => {\n // 文字列メッセージはプレフィックスを連結、それ以外は先頭引数として付加する\n const format = (message: unknown): unknown[] => (typeof message === \"string\" ? [`${prefix} ${message}`] : [prefix, message])\n return {\n debug: (message?: unknown, ...rest: unknown[]) => {\n if (level <= LogLevel.DEBUG) impl.debug(...format(message), ...rest)\n },\n info: (message?: unknown, ...rest: unknown[]) => {\n if (level <= LogLevel.INFO) impl.info(...format(message), ...rest)\n },\n warn: (message?: unknown, ...rest: unknown[]) => {\n if (level <= LogLevel.WARN) impl.warn(...format(message), ...rest)\n },\n error: (message?: unknown, ...rest: unknown[]) => {\n if (level <= LogLevel.ERROR) impl.error(...format(message), ...rest)\n },\n }\n}\n","/**\n * Zod schemas for daily-report SSE messages (client/server shared contract).\n * 日報 SSE メッセージの zod スキーマ (client / server 共有契約)。\n */\nimport { z } from \"zod\"\nimport type { DailyReportCommentItem as DeclaredComment, DailyReportDetail as DeclaredDetail } from \"./types\"\n\n// --- サブスキーマ(types.ts の型と構造的に一致させる) ---\n\nexport const dailyReportInterviewerSchema = z.object({\n name: z.string(),\n affiliation: z.string().nullable(),\n})\n\nexport const dailyReportCommentSchema = z.object({\n name: z.string().nullable(),\n text: z.string().nullable(),\n color: z.string().nullable(),\n})\n\nexport const dailyReportLabelDefSchema = z.object({\n id: z.number(),\n name: z.string(),\n color: z.string().nullable(),\n})\n\nexport const dailyReportCommentItemSchema = z.object({\n id: z.number(),\n userId: z.string(),\n userName: z.string(),\n content: z.string(),\n createdAt: z.string(),\n isMine: z.boolean(),\n})\n\nexport const dailyReportDetailSchema = z.object({\n reportHubId: z.number(),\n date: z.string().nullable(),\n createdAt: z.string().nullable(),\n author: z.string(),\n userId: z.string(),\n employeeName: z.string().nullable(),\n updatedBy: z.string().nullable(),\n updatedAt: z.string().nullable(),\n category: z.string().nullable(),\n creationCategory: z.string().nullable(),\n visitTimeFrom: z.string().nullable(),\n visitTimeTo: z.string().nullable(),\n customerName: z.string().nullable(),\n interviewers: z.array(dailyReportInterviewerSchema),\n subject: z.string().nullable(),\n content: z.string().nullable(),\n comments: z.array(dailyReportCommentSchema),\n isRead: z.boolean(),\n isStarred: z.boolean(),\n labels: z.array(dailyReportLabelDefSchema),\n commentItems: z.array(dailyReportCommentItemSchema),\n})\n\n// --- SSE メッセージスキーマ(8種) ---\n\nexport const connectedMessageSchema = z.object({\n type: z.literal(\"connected\"),\n})\n\nexport const statusUpdateMessageSchema = z.object({\n type: z.literal(\"status-update\"),\n reportHubId: z.number(),\n statusType: z.enum([\"star\", \"read\"]),\n value: z.boolean(),\n clientTempId: z.string(),\n // recipientRawUserId はサーバーサイドフィルタリング専用。\n // SSE ルートが raw JSON から取得してフィルタ後に除去する。\n // クライアントには到達しないが、サーバー側の publish で .parse() を通すため定義が必要。\n recipientRawUserId: z.number().optional(),\n})\n\nexport const commentAddMessageSchema = z.object({\n type: z.literal(\"comment-add\"),\n reportHubId: z.number(),\n comment: dailyReportCommentItemSchema,\n clientTempId: z.string(),\n})\n\nexport const commentDeleteMessageSchema = z.object({\n type: z.literal(\"comment-delete\"),\n reportHubId: z.number(),\n commentId: z.number(),\n clientTempId: z.string(),\n})\n\nexport const reportCreateMessageSchema = z.object({\n type: z.literal(\"report-create\"),\n reportHubId: z.number(),\n report: dailyReportDetailSchema,\n clientTempId: z.string(),\n recipientRawUserId: z.number().optional(),\n})\n\nexport const reportUpdateMessageSchema = z.object({\n type: z.literal(\"report-update\"),\n reportHubId: z.number(),\n report: dailyReportDetailSchema,\n clientTempId: z.string(),\n recipientRawUserId: z.number().optional(),\n})\n\nexport const reportPublishMessageSchema = z.object({\n type: z.literal(\"report-publish\"),\n reportHubId: z.number(),\n report: dailyReportDetailSchema,\n clientTempId: z.string(),\n})\n\nexport const reportDeleteMessageSchema = z.object({\n type: z.literal(\"report-delete\"),\n reportHubId: z.number(),\n clientTempId: z.string(),\n})\n\n// --- Discriminated Union ---\n\nexport const dailyReportSseMessageSchema = z.discriminatedUnion(\"type\", [\n connectedMessageSchema,\n statusUpdateMessageSchema,\n commentAddMessageSchema,\n commentDeleteMessageSchema,\n reportCreateMessageSchema,\n reportUpdateMessageSchema,\n reportPublishMessageSchema,\n reportDeleteMessageSchema,\n])\n\n// --- 型エクスポート ---\n\nexport type DailyReportSseMessage = z.infer<typeof dailyReportSseMessageSchema>\n\n// --- コンパイル時の型互換チェック ---\n// Zod推論型が既存の型定義に代入可能であることを保証する。\n// ここでエラーが出たらスキーマと types.ts がずれている。\n\ntype _AssertDetailCompat = z.infer<typeof dailyReportDetailSchema> extends DeclaredDetail ? true : never\ntype _AssertCommentCompat = z.infer<typeof dailyReportCommentItemSchema> extends DeclaredComment ? true : never\nconst _detailCheck: _AssertDetailCompat = true\nconst _commentCheck: _AssertCommentCompat = true\nvoid _detailCheck\nvoid _commentCheck\n","/**\n * ETag generation helper for JSON payloads.\n * JSON ペイロード向けの ETag 生成ヘルパー。\n */\nimport { createHash } from \"node:crypto\"\n\n/**\n * Generates a SHA-256 ETag for the given data.\n * 指定されたデータの SHA-256 ETag を生成します。\n *\n * @param data The data to hash (will be JSON stringified).\n * @returns The ETag string (wrapped in quotes).\n */\nexport const generateETag = (data: unknown): string => {\n const json = JSON.stringify(data)\n const hash = createHash(\"sha256\").update(json).digest(\"hex\")\n return `\"${hash}\"`\n}\n","/**\n * JSON response helper with shared security headers and ETag support.\n * 共有セキュリティヘッダーと ETag 対応を備えた JSON レスポンスヘルパー。\n */\nimport { createLogger, type DailyReportLogger, LogLevel } from \"../shared/logger\"\nimport { generateETag } from \"./etag\"\n\nconst defaultLogger = createLogger(LogLevel.INFO, \"[Response]\")\n\n/**\n * Creates JSON response with shared security headers and ETag support.\n * 共有のセキュリティヘッダーと ETag サポート付き JSON レスポンスを生成。\n */\nexport const jsonResponseWithETag = (request: Request, cookie: string | null, payload: Record<string, unknown>, status = 200, logger: DailyReportLogger = defaultLogger): Response => {\n const etag = generateETag(payload)\n const ifNoneMatch = request.headers.get(\"If-None-Match\")\n\n logger.info(`[jsonResponseWithETag] ETag: ${etag}, If-None-Match: ${ifNoneMatch}`)\n\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"private, max-age=0, must-revalidate\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"X-Frame-Options\": \"DENY\",\n \"Content-Security-Policy\": \"default-src 'none'\",\n ETag: etag,\n })\n if (cookie) {\n headers.append(\"Set-Cookie\", cookie)\n }\n\n if (request.method === \"GET\" && status === 200 && ifNoneMatch === etag) {\n return new Response(null, { status: 304, headers })\n }\n\n return new Response(JSON.stringify(payload), { status, headers })\n}\n","/**\n * Fan-Out shared reader for the daily report SSE Redis Stream.\n * 日報 SSE 用 Redis Stream の共有リーダーモジュール。\n *\n * 単一の xRead BLOCK ループで全接続にメッセージをブロードキャストし、\n * 接続ごとに Redis TCP を張る問題を解消する。\n */\n\nimport { EventEmitter } from \"node:events\"\nimport { createLogger, type DailyReportLogger, LogLevel } from \"../shared/logger\"\nimport type { SqlResultCache } from \"./cache\"\nimport type { DailyReportRedisBlockingClient, DailyReportRedisProvider } from \"./ports\"\n\n/**\n * Compares two Redis Stream IDs numerically.\n * Redis Stream ID を数値比較し、a <= b なら true を返す。\n *\n * Stream ID は `<timestamp_ms>-<sequence>` 形式。\n * 辞書順比較では sequence が可変長のとき不正確になるため、数値分割で比較する。\n */\nexport const isStreamIdLte = (a: string, b: string): boolean => {\n const [aMs, aSeq] = a.split(\"-\").map(Number)\n const [bMs, bSeq] = b.split(\"-\").map(Number)\n if (aMs !== bMs) return aMs < bMs\n return aSeq <= bSeq\n}\n\n/** xRead 結果の 1 エントリに相当する型。 */\nexport type StreamEntry = {\n id: string\n message: Record<string, string>\n}\n\nexport type DailyReportSseReaderConfig = {\n /** ブロッキング xRead 用の専用クライアントを生成する redis プロバイダー。 */\n redis?: DailyReportRedisProvider\n /** SSE Redis Stream キー。 */\n streamKey: string\n /** 受信メッセージに応じてローカル SQL キャッシュを無効化する対象キャッシュ。 */\n cache: SqlResultCache\n /** ロガー (既定は console ベース)。 */\n logger?: DailyReportLogger\n}\n\n/**\n * Shared xRead loop that fans out entries to all active SSE connections.\n * 全 SSE 接続に対してメッセージをファンアウトする共有 xRead ループ。\n *\n * - \"entry\" イベント: 新着エントリ (StreamEntry) をブロードキャスト\n * - \"error\" イベント: 回復不能エラーをブロードキャスト\n * */\nexport class DailyReportSseReader {\n private _emitter = new EventEmitter()\n private _state: \"idle\" | \"running\" | \"stopping\" = \"idle\"\n private _refCount = 0\n private _lastId = \"0-0\"\n private _client: DailyReportRedisBlockingClient | undefined\n private readonly _logger: DailyReportLogger\n\n constructor(private readonly config: DailyReportSseReaderConfig) {\n // リスナー上限を緩和 (接続数分)\n this._emitter.setMaxListeners(0)\n this._logger = config.logger ?? createLogger(LogLevel.INFO, \"[SSE Reader]\")\n }\n\n /**\n * Subscribes to the shared reader. Starts the loop on first subscriber.\n * 共有リーダーを購読する。最初の購読者でループを開始する。\n *\n * @param onEntry - 新着エントリのコールバック\n * @param onError - 回復不能エラーのコールバック (省略可)\n * @returns unsubscribe 関数。呼び出すと両リスナーを解除し、最後の購読者解除でループを停止する。\n */\n subscribe(onEntry: (entry: StreamEntry) => void, onError?: (err: Error) => void): () => void {\n this._emitter.on(\"entry\", onEntry)\n if (onError) {\n this._emitter.on(\"error\", onError)\n }\n this._refCount++\n\n // 最初の購読者でループ開始\n if (this._refCount === 1) {\n void this._startLoop()\n }\n\n // unsubscribe\n return () => {\n this._emitter.removeListener(\"entry\", onEntry)\n if (onError) {\n this._emitter.removeListener(\"error\", onError)\n }\n this._refCount--\n if (this._refCount <= 0) {\n this._refCount = 0\n void this._stopLoop()\n }\n }\n }\n\n /**\n * Destroys the reader for test cleanup.\n * テストクリーンアップ用のデストラクタ。\n */\n async destroy(): Promise<void> {\n this._refCount = 0\n await this._stopLoop()\n this._emitter.removeAllListeners()\n this._lastId = \"0-0\"\n }\n\n /**\n * Internal xRead BLOCK loop.\n * 内部 xRead BLOCK ループ。\n */\n private async _startLoop(): Promise<void> {\n // stopping 中なら完了を待つ\n while (this._state === \"stopping\") {\n await new Promise((resolve) => setTimeout(resolve, 50))\n }\n if (this._state === \"running\") return\n\n this._state = \"running\"\n\n // 専用クライアント取得。createClient が reject した場合も _state を idle へ戻し、\n // 再購読でループを再開できるようにする (注入 redis 実装が例外を投げても state-stuck しない)。\n try {\n this._client = await this.config.redis?.createClient()\n } catch (err) {\n this._state = \"idle\"\n this._emitter.emit(\"error\", err instanceof Error ? err : new Error(\"Failed to create Redis client for SSE reader\"))\n return\n }\n if (!this._client) {\n this._state = \"idle\"\n this._emitter.emit(\"error\", new Error(\"Failed to create Redis client for SSE reader\"))\n return\n }\n\n // エラーリスナー\n this._client.on(\"error\", (err) => {\n this._logger.error(\"Redis client error:\", err)\n })\n\n try {\n while (this._state === \"running\" && this._client?.isOpen) {\n const results = await this._client.xRead([{ key: this.config.streamKey, id: this._lastId }], { BLOCK: 5000, COUNT: 100 })\n if (!results) continue\n\n for (const stream of results) {\n for (const msg of stream.messages) {\n this._lastId = msg.id\n // epoch check の補完: SSE 経由でもローカルキャッシュを即座にクリア\n // (epoch check が主防御線。SSE は Redis ダウン時や非 epoch 対象キャッシュへのフォールバック)\n try {\n const parsed = msg.message?.data ? JSON.parse(msg.message.data) : null\n const msgType = parsed?.type\n if (msgType === \"report-create\" || msgType === \"report-delete\" || msgType === \"report-publish\") {\n this.config.cache.invalidatePrefix(\"daily-report:ids\")\n }\n // コメント・ステータス変更時は対象レポートの詳細キャッシュを無効化\n if (msgType === \"comment-add\" || msgType === \"comment-delete\" || msgType === \"status-update\") {\n const reportHubId = parsed?.reportHubId\n if (typeof reportHubId === \"number\") {\n this.config.cache.invalidate(`daily-report:detail:${reportHubId}`)\n this.config.cache.invalidatePrefix(`daily-report:detail:${reportHubId}:user:`)\n }\n }\n } catch {\n // JSON パースエラーは無視 (invalidation スキップ = safe 方向)\n }\n this._emitter.emit(\"entry\", { id: msg.id, message: msg.message as Record<string, string> })\n }\n }\n }\n } catch (err) {\n // ClientClosedError は正常停止時に発生する\n const isClientClosed = (err as Error)?.constructor?.name === \"ClientClosedError\"\n if (!isClientClosed && this._state === \"running\") {\n this._logger.error(\"xRead loop error:\", err)\n this._emitter.emit(\"error\", err)\n }\n } finally {\n // クライアント切断\n if (this._client?.isOpen) {\n try {\n await this._client.quit()\n } catch (_e) {\n // 切断エラーは無視\n }\n }\n this._client = undefined\n this._state = \"idle\"\n\n // ループ終了後に購読者が残っていれば自動再起動\n if (this._refCount > 0) {\n void this._startLoop()\n }\n }\n }\n\n /**\n * Stops the xRead loop by closing the client.\n * クライアントを閉じて xRead ループを停止する。\n */\n private async _stopLoop(): Promise<void> {\n if (this._state !== \"running\") return\n this._state = \"stopping\"\n\n if (this._client?.isOpen) {\n try {\n await this._client.quit()\n } catch (_e) {\n // 切断エラーは無視\n }\n }\n\n // idle になるまで待機。_state は別の非同期ループ (connect の run ループ) が \"idle\" に戻すが、\n // TS は await を跨いだクラスフィールドの変化を追えず \"stopping\" に過剰 narrowing するため、宣言型へキャストして比較する。\n while ((this._state as \"idle\" | \"running\" | \"stopping\") !== \"idle\") {\n await new Promise((resolve) => setTimeout(resolve, 50))\n }\n }\n}\n","/**\n * React Router loader/action factories for the daily-report HTTP surface.\n * 日報 HTTP サーフェス向けの React Router loader / action 工場。\n *\n * - index.loader: 画面ルートの認証 + 難読化ユーザー ID 解決\n * - api.loader / api.action: `:endpoint` パラメータ式の認証付き API ルーター\n * - sse.loader: Redis Streams ベースのリアルタイム更新 SSE エンドポイント\n */\nimport { normalizeBusinessDateKey } from \"../shared/business-date\"\nimport { createLogger, type DailyReportLogger, LogLevel } from \"../shared/logger\"\nimport { dailyReportSseMessageSchema } from \"../shared/sse-schema\"\nimport type { DailyReportAuthenticate, DailyReportEncodeUserId, DailyReportRedisProvider } from \"./ports\"\nimport { jsonResponseWithETag } from \"./response\"\nimport type { DailyReportService } from \"./service\"\nimport type { DailyReportSseReader, StreamEntry } from \"./sse-reader\"\nimport { isStreamIdLte } from \"./sse-reader\"\n\ntype LoaderArgs = { request: Request; params: Record<string, string | undefined> }\n\n/** `data()` 相当の JSON レスポンス生成 (react-router 非依存)。 */\nconst jsonData = (payload: unknown, init?: { status?: number }): Response =>\n new Response(JSON.stringify(payload), {\n status: init?.status ?? 200,\n headers: { \"Content-Type\": \"application/json\" },\n })\n\nexport type DailyReportHandlersConfig = {\n /** リクエスト認証ポート。 */\n authenticate: DailyReportAuthenticate\n /** データアクセスサービス。 */\n service: DailyReportService\n /** 内部数値 ID の難読化ポート。 */\n encodeUserId: DailyReportEncodeUserId\n /** SSE 用 redis プロバイダー (catch-up の xRange / xRevRange に使用)。 */\n redis?: DailyReportRedisProvider\n /** SSE Fan-Out 共有リーダー。 */\n sseReader: DailyReportSseReader\n /** SSE Redis Stream キー。 */\n streamKey: string\n /** 未ログイン時のリダイレクト先 (index.loader 用、既定 \"/auth/login\")。 */\n loginRedirectPath?: string\n /** ロガー (既定は console ベース)。 */\n logger?: DailyReportLogger\n}\n\n/**\n * Creates the daily-report loaders/actions bound to the injected dependencies.\n * 注入依存に束縛された日報 loader / action 群を生成する処理。\n */\nexport function createDailyReportHandlers(config: DailyReportHandlersConfig) {\n const { authenticate, service, encodeUserId, redis, sseReader, streamKey } = config\n const loginRedirectPath = config.loginRedirectPath ?? \"/auth/login\"\n const apiLogger = config.logger ?? createLogger(LogLevel.ERROR, \"[DailyReportAPI]\")\n const sseLogger = config.logger ?? createLogger(LogLevel.INFO, \"[DailyReportSSE]\")\n\n // ---------------- index (画面ルート) ----------------\n\n /**\n * Document loader that authenticates and resolves the obfuscated internal user id.\n * 認証と難読化済み内部ユーザー ID の解決を行うドキュメントローダー。\n */\n const indexLoader = async ({ request }: LoaderArgs) => {\n const { user, cookie } = await authenticate(request, { failureRedirect: loginRedirectPath })\n const headers = new Headers()\n if (cookie) {\n headers.append(\"Set-Cookie\", cookie)\n }\n\n let userId: number | null = null\n if (user) {\n userId = await service.getUserIdByExternalId(user.id)\n }\n\n const hashedUserId = userId ? encodeUserId(userId) : null\n\n return { data: { user, userId: hashedUserId }, headers }\n }\n\n // ---------------- api (:endpoint ルーター) ----------------\n\n type User = { id: string }\n type EndpointHandler = (url: URL, cookie: string | null, request: Request, user: User) => Promise<Response>\n\n /**\n * Handlers for each API endpoint.\n * 各 API エンドポイントのハンドラー定義。\n */\n const endpointHandlers: Record<string, EndpointHandler> = {\n /**\n * Retrieves daily reports for a specific business date.\n * 指定された営業日の日報一覧を取得する。\n */\n \"business-date\": async (url, cookie, request, user) => {\n const normalizedBusinessDate = normalizeBusinessDateKey(url.searchParams.get(\"businessDate\"))\n const forceRefresh = url.searchParams.get(\"forceRefresh\") === \"true\"\n\n if (!normalizedBusinessDate) {\n return jsonResponseWithETag(request, cookie, { error: { message: \"Invalid business date\" } }, 400)\n }\n const reports = await service.getDailyReportsByBusinessDateByExternalId(normalizedBusinessDate, user.id, { forceRefresh })\n return jsonResponseWithETag(request, cookie, { businessDate: normalizedBusinessDate, reports }, 200)\n },\n /**\n * Retrieves a list of all daily report IDs.\n * 全ての日報 ID の一覧を取得する。\n */\n ids: async (url, cookie, request, user) => {\n const forceRefresh = url.searchParams.get(\"forceRefresh\") === \"true\"\n const dailyReportIds = await service.getDailyReportIdsByExternalId(user.id, { forceRefresh })\n return jsonResponseWithETag(request, cookie, { ids: dailyReportIds }, 200)\n },\n /**\n * Retrieves details for a specific daily report.\n * 指定された日報の詳細情報を取得する。\n */\n report: async (url, cookie, request, user) => {\n const param = url.searchParams.get(\"reportHubId\")\n const forceRefresh = url.searchParams.get(\"forceRefresh\") === \"true\"\n const parsedId = param ? Number.parseInt(param, 10) : NaN\n\n if (!Number.isFinite(parsedId) || parsedId <= 0) {\n return jsonResponseWithETag(request, cookie, { error: { message: \"Invalid reportHubId\" } }, 400)\n }\n const detail = await service.getDailyReportDetailByIdByExternalId(parsedId, user.id, { snapshot: true, forceRefresh })\n if (!detail) {\n return jsonResponseWithETag(request, cookie, { error: { message: \"Report not found\" } }, 404)\n }\n return jsonResponseWithETag(request, cookie, { report: detail }, 200)\n },\n }\n\n /**\n * Routes authenticated daily report API requests by endpoint.\n * エンドポイントごとに認証済みの日報 API リクエストを振り分ける。\n */\n const apiLoader = async ({ request, params }: LoaderArgs) => {\n const { user, cookie } = await authenticate(request, { failureRedirect: null })\n const sanitizedCookie = cookie ?? null\n\n if (!user) {\n return jsonResponseWithETag(request, sanitizedCookie, { error: { message: \"Unauthorized\" } }, 401)\n }\n\n if (request.method !== \"GET\") {\n return jsonResponseWithETag(request, sanitizedCookie, { error: { message: \"Method not allowed\" } }, 405)\n }\n const endpoint = params.endpoint ?? \"\"\n const handler = endpointHandlers[endpoint]\n if (!handler) {\n return jsonResponseWithETag(request, sanitizedCookie, { error: { message: \"Unknown endpoint\" } }, 404)\n }\n const startTime = Date.now()\n try {\n const url = new URL(request.url)\n return await handler(url, sanitizedCookie, request, user)\n } catch (error) {\n const elapsed = Date.now() - startTime\n const err = error instanceof Error ? error : new Error(String(error))\n apiLogger.error(`500 endpoint=${endpoint} elapsed=${elapsed}ms name=${err.name} code=${\"code\" in err ? (err as { code: unknown }).code : \"N/A\"} message=${err.message}`)\n apiLogger.error(\"Stack:\", err.stack)\n return jsonResponseWithETag(request, sanitizedCookie, { error: { message: \"Internal Server Error\" } }, 500)\n }\n }\n\n /**\n * Handles data mutations for daily reports.\n * 日報データの変更操作を処理するアクション。\n */\n const apiAction = async ({ request, params }: LoaderArgs) => {\n const { user } = await authenticate(request, { failureRedirect: null })\n if (!user) {\n return jsonData({ error: \"Unauthorized\" }, { status: 401 })\n }\n\n const endpoint = params.endpoint\n if (endpoint !== \"action\") {\n return jsonData({ error: \"Unknown endpoint\" }, { status: 404 })\n }\n\n const userId = await service.getUserIdByExternalId(user.id)\n if (!userId) {\n return jsonData({ error: \"User not found\" }, { status: 404 })\n }\n\n const formData = await request.formData()\n const intent = formData.get(\"intent\")\n const reportHubIdRaw = formData.get(\"reportHubId\")\n const reportHubId = reportHubIdRaw ? Number(reportHubIdRaw) : NaN\n const businessDate = formData.get(\"businessDate\") as string | null\n const operationTimestamp = Number(formData.get(\"operationTimestamp\"))\n const clientTempId = formData.get(\"clientTempId\") as string | null\n\n if (!clientTempId) {\n return jsonData({ error: \"clientTempId required\" }, { status: 400 })\n }\n\n if (intent !== \"create\" && (!reportHubId || Number.isNaN(reportHubId))) {\n return jsonData({ error: \"Invalid reportHubId\" }, { status: 400 })\n }\n\n switch (intent) {\n case \"create\": {\n if (!businessDate) {\n return jsonData({ error: \"businessDate required\" }, { status: 400 })\n }\n const newReport = await service.createDailyReport(userId, businessDate, clientTempId)\n return jsonData({\n status: \"OK\",\n intent: \"create\",\n report: newReport,\n reportHubId: String(newReport.reportHubId),\n clientTempId, // Echo back for validation\n })\n }\n case \"update\": {\n const title = formData.get(\"title\") as string | undefined\n const content = formData.get(\"content\") as string | undefined\n try {\n await service.updateDailyReport(reportHubId, userId, { title, content }, clientTempId)\n return jsonData({ status: \"OK\", intent: \"update\", reportHubId: String(reportHubId), clientTempId })\n } catch (e: unknown) {\n if (e instanceof Error) {\n if (e.message === \"Unauthorized\") {\n return jsonData({ error: \"Unauthorized\" }, { status: 403 })\n }\n if (e.message === \"Not Found\") {\n return jsonData({ error: \"Report not found\" }, { status: 404 })\n }\n }\n throw e\n }\n }\n case \"publish\": {\n try {\n const publishedReport = await service.publishDailyReport(reportHubId, userId, clientTempId)\n return jsonData({ status: \"OK\", intent: \"publish\", reportHubId: String(reportHubId), clientTempId, report: publishedReport })\n } catch (e: unknown) {\n if (e instanceof Error) {\n if (e.message === \"Unauthorized\") {\n return jsonData({ error: \"Unauthorized\" }, { status: 403 })\n }\n if (e.message === \"Not Found\") {\n return jsonData({ error: \"Report not found\" }, { status: 404 })\n }\n }\n throw e\n }\n }\n case \"delete\": {\n try {\n await service.deleteDailyReport(reportHubId, userId, clientTempId)\n return jsonData({\n status: \"OK\",\n intent: \"delete\",\n reportHubId: String(reportHubId),\n clientTempId, // Echo back for validation even on delete\n })\n } catch (e: unknown) {\n if (e instanceof Error) {\n if (e.message === \"Unauthorized\") {\n return jsonData({ error: \"Unauthorized\" }, { status: 403 })\n }\n if (e.message === \"Not Found\") {\n return jsonData({ error: \"Report not found\" }, { status: 404 })\n }\n }\n throw e\n }\n }\n case \"toggleStar\": {\n const isStarredRaw = formData.get(\"isStarred\")\n if (isStarredRaw === null) {\n return jsonData({ error: \"isStarred required\" }, { status: 400 })\n }\n const isStarred = isStarredRaw === \"true\"\n const updatedStatus = await service.setStarStatus(userId, reportHubId, businessDate, isStarred, clientTempId)\n // クライアントは isStarred/isRead のみ参照する。生内部 ID (userId/created_by/updated_by) を\n // 含む行全体は返さず、必要なフラグだけに絞る (内部 ID の自己開示防止)。\n return jsonData({ status: \"OK\", intent: \"toggleStar\", updatedStatus: { isStarred: updatedStatus.isStarred, isRead: updatedStatus.isRead }, operationTimestamp, reportHubId: String(reportHubId), clientTempId })\n }\n case \"toggleRead\": {\n const isReadRaw = formData.get(\"isRead\")\n if (isReadRaw === null) {\n return jsonData({ error: \"isRead required\" }, { status: 400 })\n }\n const isRead = isReadRaw === \"true\"\n const updatedStatus = await service.setReadStatus(userId, reportHubId, businessDate, isRead, clientTempId)\n // クライアントは isStarred/isRead のみ参照する (内部 ID の自己開示防止)。\n return jsonData({ status: \"OK\", intent: \"toggleRead\", updatedStatus: { isStarred: updatedStatus.isStarred, isRead: updatedStatus.isRead }, operationTimestamp, reportHubId: String(reportHubId), clientTempId })\n }\n case \"addComment\": {\n const content = formData.get(\"content\") as string\n if (!content) {\n return jsonData({ error: \"Content required\" }, { status: 400 })\n }\n const newComment = await service.addComment(userId, reportHubId, content, businessDate, clientTempId)\n const safeComment = { ...newComment, userId: newComment.userId }\n return jsonData({ status: \"OK\", intent: \"addComment\", newComment: safeComment, reportHubId: String(reportHubId), clientTempId })\n }\n case \"deleteComment\": {\n const commentId = Number(formData.get(\"commentId\"))\n if (!commentId || Number.isNaN(commentId)) {\n return jsonData({ error: \"Invalid commentId\" }, { status: 400 })\n }\n try {\n await service.deleteComment(userId, reportHubId, commentId, businessDate, clientTempId)\n return jsonData({ status: \"OK\", reportHubId: String(reportHubId), deletedCommentId: String(commentId), clientTempId })\n } catch (e: unknown) {\n if (e instanceof Error) {\n if (e.message === \"Unauthorized\") {\n return jsonData({ error: \"Unauthorized\" }, { status: 403 })\n }\n if (e.message === \"Not Found\") {\n return jsonData({ error: \"Comment not found\" }, { status: 404 })\n }\n }\n throw e\n }\n }\n default:\n return jsonData({ error: \"Invalid intent\" }, { status: 400 })\n }\n }\n\n // ---------------- sse (リアルタイム更新) ----------------\n\n /**\n * SSE endpoint for real-time daily report updates via Redis Streams.\n * Redis Streams を使用した日報リアルタイム更新の SSE エンドポイント。\n */\n const sseLoader = async ({ request, params }: LoaderArgs) => {\n // 認証チェック\n const { user } = await authenticate(request, { failureRedirect: null })\n if (!user) {\n return new Response(\"Unauthorized\", { status: 401 })\n }\n\n // 内部ユーザー ID の解決\n const internalUserId = await service.getUserIdByExternalId(user.id)\n if (!internalUserId) {\n return new Response(\"Forbidden\", { status: 403 })\n }\n\n // エンドポイントの検証\n if (params.endpoint !== \"updates\") {\n return new Response(\"Not Found\", { status: 404 })\n }\n\n // URL から lastEventId を取得 (再接続時の catch-up 用)\n // クエリパラメータ優先、EventSource 自動再接続時の Last-Event-ID ヘッダーにフォールバック\n const url = new URL(request.url)\n const lastEventId = url.searchParams.get(\"lastEventId\") || request.headers.get(\"Last-Event-ID\")\n\n const encoder = new TextEncoder()\n let controllerRef: ReadableStreamDefaultController<Uint8Array> | null = null\n let keepAliveInterval: ReturnType<typeof setInterval> | null = null\n let unsubscribe: (() => void) | null = null\n let isCleaningUp = false\n\n // クリーンアップ処理\n const cleanup = () => {\n if (isCleaningUp) return\n isCleaningUp = true\n\n // keep-alive タイマー停止\n if (keepAliveInterval) {\n clearInterval(keepAliveInterval)\n keepAliveInterval = null\n }\n\n // Fan-Out 購読解除 (entry / error 両リスナーを解除)\n if (unsubscribe) {\n unsubscribe()\n unsubscribe = null\n }\n\n // SSE ストリームの終了\n if (controllerRef) {\n try {\n if (controllerRef.desiredSize !== null) {\n controllerRef.close()\n }\n } catch (_e) {\n // ストリームが既に閉じている場合は無視\n } finally {\n controllerRef = null\n }\n }\n\n isCleaningUp = false\n }\n\n /**\n * Processes a single Redis Stream entry and sends it to the SSE client.\n * Redis Stream のエントリを処理し、SSE クライアントに送信する。\n */\n const processEntry = (entryId: string, fields: Record<string, string>) => {\n // data フィールドの存在チェック\n if (!fields.data) return\n\n try {\n const raw = JSON.parse(fields.data)\n const result = dailyReportSseMessageSchema.safeParse(raw)\n if (!result.success) {\n sseLogger.error(\"SSE message validation failed:\", result.error.format())\n return // Fail-Closed: 不正なメッセージは送信しない\n }\n const parsed = result.data\n\n // recipientRawUserId によるフィルタリング\n const recipientRawUserId = typeof raw.recipientRawUserId === \"number\" ? raw.recipientRawUserId : undefined\n\n if (parsed.type === \"status-update\") {\n if (recipientRawUserId === undefined || recipientRawUserId !== internalUserId) {\n return\n }\n } else if (recipientRawUserId !== undefined && recipientRawUserId !== internalUserId) {\n return\n }\n\n // recipientRawUserId をクライアントに送信しない (内部 ID 漏洩防止)\n let sanitizedMessage: string\n if (\"recipientRawUserId\" in raw) {\n const { recipientRawUserId: _, ...rest } = raw\n sanitizedMessage = JSON.stringify(rest)\n } else {\n sanitizedMessage = fields.data\n }\n\n // SSE フォーマットで送信 (id フィールド付き)\n if (controllerRef && controllerRef.desiredSize !== null) {\n controllerRef.enqueue(encoder.encode(`id: ${entryId}\\ndata: ${sanitizedMessage}\\n\\n`))\n }\n } catch (e) {\n sseLogger.error(`[SSE:${internalUserId}] processEntry error:`, e)\n }\n }\n\n const stream = new ReadableStream({\n async start(controller) {\n // 1. controllerRef 設定\n controllerRef = controller\n\n // 2. Keep-Alive: 5 秒ごとにコメントを送信して接続維持\n keepAliveInterval = setInterval(() => {\n try {\n if (controllerRef && controllerRef.desiredSize !== null) {\n controllerRef.enqueue(encoder.encode(\": keep-alive\\n\\n\"))\n } else {\n cleanup()\n }\n } catch (_e) {\n cleanup()\n }\n }, 5000)\n\n // 3. クライアント切断時のクリーンアップ (全 await の前に登録)\n request.signal.addEventListener(\"abort\", () => {\n cleanup()\n })\n\n // catch-up の基準 ID (Fan-Out エントリとの重複排除に使用)\n let lastProcessedId = lastEventId || \"0-0\"\n\n // 4. Fan-Out 共有リーダーを購読 (catch-up より先に登録して取りこぼしを防止)\n unsubscribe = sseReader.subscribe(\n (entry: StreamEntry) => {\n // catch-up 済みエントリはスキップ (重複排除)\n if (isStreamIdLte(entry.id, lastProcessedId)) return\n lastProcessedId = entry.id\n processEntry(entry.id, entry.message)\n },\n (err: Error) => {\n sseLogger.error(`[SSE:${internalUserId}] Fan-Out reader error:`, err)\n cleanup()\n },\n )\n\n // 5. 初回接続時: 最新 Stream ID を取得して connected の id: に使用\n // (再接続時は lastEventId が既にあるためスキップ)\n if (!lastEventId) {\n try {\n const client = await redis?.getClient()\n if (client) {\n const latest = await client.xRevRange(streamKey, \"+\", \"-\", { COUNT: 1 })\n // Fan-Out が既に lastProcessedId を進めている場合は巻き戻さない\n if (latest.length > 0 && !isStreamIdLte(latest[0].id, lastProcessedId)) {\n lastProcessedId = latest[0].id\n }\n }\n } catch {\n /* 取得失敗時は現在の lastProcessedId を維持 */\n }\n }\n\n // 6. 接続完了通知 (id: 付きで再接続時の catch-up アンカーを提供)\n if (controllerRef && controllerRef.desiredSize !== null) {\n const connectedPayload = `data: ${JSON.stringify({ type: \"connected\" })}\\n\\n`\n const sseMessage = lastProcessedId !== \"0-0\" ? `id: ${lastProcessedId}\\n${connectedPayload}` : connectedPayload\n controllerRef.enqueue(encoder.encode(sseMessage))\n }\n\n // 7. catch-up: lastEventId が指定されている場合、それ以降のエントリを一括取得\n if (lastEventId) {\n try {\n const client = await redis?.getClient()\n if (client) {\n const catchUpEntries = await client.xRange(streamKey, lastEventId, \"+\", { COUNT: 1000 })\n for (const entry of catchUpEntries) {\n // xRange は inclusive なので lastEventId 自身はスキップ\n if (entry.id === lastEventId) continue\n // Fan-Out が xRange await 中に処理済みのエントリはスキップ (重複排除)\n if (isStreamIdLte(entry.id, lastProcessedId)) continue\n lastProcessedId = entry.id\n processEntry(entry.id, entry.message as Record<string, string>)\n }\n }\n } catch (e) {\n sseLogger.error(`[SSE:${internalUserId}] catch-up xRange error:`, e)\n // catch-up 失敗時は Fan-Out のみで継続\n }\n }\n },\n cancel() {\n cleanup()\n },\n })\n\n return new Response(stream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n Connection: \"keep-alive\",\n },\n })\n }\n\n return {\n index: { loader: indexLoader },\n api: { loader: apiLoader, action: apiAction },\n sse: { loader: sseLoader },\n }\n}\n","/**\n * Data-access service for daily reports (drizzle mssql), fully DI-configured.\n * 日報データアクセスサービス (drizzle mssql)。依存はすべて DI で注入する。\n *\n * キャッシュキー・無効化順序・SSE publish 順序を含むデータアクセスロジックの中核。\n */\nimport { aliasedTable, and, asc, desc, eq, getColumns, inArray, isNull, or, sql } from \"drizzle-orm\"\nimport { normalizeBusinessDateKey } from \"../shared/business-date\"\nimport { createLogger, type DailyReportLogger, LogLevel } from \"../shared/logger\"\nimport { commentAddMessageSchema, commentDeleteMessageSchema, reportCreateMessageSchema, reportDeleteMessageSchema, reportPublishMessageSchema, reportUpdateMessageSchema, statusUpdateMessageSchema } from \"../shared/sse-schema\"\nimport type { DailyReportComment, DailyReportCommentItem, DailyReportDetail, DailyReportInterviewer, DailyReportItem, DailyReportLabelDef } from \"../shared/types\"\nimport type { EpochStore, SqlResultCache, SqlResultCacheQueryOptions } from \"./cache\"\nimport type { DailyReportExternalSource } from \"./external-source\"\nimport type { DailyReportEncodeUserId, DailyReportRedisProvider, DailyReportResolveUserId } from \"./ports\"\nimport type { DailyReportTables, DailyReportUserTable } from \"./schema\"\n\nexport type { SqlResultCacheQueryOptions }\n\n// ---- 行型 (drizzle $inferSelect の構造的置き換え) ----\n\n/** DailyReportHub の行型。 */\nexport type DailyReportHubRow = {\n id: number\n sourceType: string\n sourceId: string\n sourceIdNum: number | null\n businessDate: Date | string | null\n userId: number | null\n title: string | null\n summary: string | null\n createdAt: Date | string\n createdBy: string\n updatedAt: Date | string\n updatedBy: string\n deletedAt: Date | string | null\n deletedBy: string | null\n}\n\n/** DailyReportInternal の行型。 */\nexport type DailyReportInternalRow = {\n hubId: number\n body: string | null\n metadata: string | null\n createdAt: Date | string\n createdBy: string\n updatedAt: Date | string\n updatedBy: string\n}\n\n/** DailyReportUserStatus の行型。 */\nexport type DailyReportUserStatusRow = {\n hubId: number\n userId: number\n isRead: boolean\n isStarred: boolean\n createdAt: Date | string\n createdBy: string\n updatedAt: Date | string\n updatedBy: string\n}\n\n/** DailyReportComment の行型。 */\nexport type DailyReportCommentRow = {\n id: number\n hubId: number\n userId: number\n body: string\n createdAt: Date | string\n createdBy: string\n updatedAt: Date | string\n updatedBy: string\n}\n\n// ---- 必要最小の drizzle ビルダ形 (公開契約はサービス関数のシグネチャで厳格化) ----\n\ntype Rows<T> = PromiseLike<T[]>\ninterface SelectChain<T> extends Rows<T> {\n from(t: unknown): SelectChain<T>\n innerJoin(t: unknown, on: unknown): SelectChain<T>\n leftJoin(t: unknown, on: unknown): SelectChain<T>\n where(cond: unknown): SelectChain<T>\n orderBy(...cols: unknown[]): SelectChain<T>\n top(n: number): SelectChain<T>\n}\ninterface InsertChain<T> {\n output(): { values(v: unknown): PromiseLike<T[]> }\n values(v: unknown): PromiseLike<unknown>\n}\ninterface UpdateChain<T> {\n set(v: unknown): {\n where(cond: unknown): PromiseLike<unknown>\n output(): { where(cond: unknown): PromiseLike<T[]> }\n }\n}\ninterface DeleteChain {\n where(cond: unknown): PromiseLike<unknown>\n}\n\n/** サービスが要求する drizzle mssql データベースの最小面 (トランザクション込み)。 */\nexport interface DailyReportDb {\n select<T = Record<string, unknown>>(fields?: unknown): SelectChain<T>\n insert<T = Record<string, unknown>>(t: unknown): InsertChain<T>\n update<T = Record<string, unknown>>(t: unknown): UpdateChain<T>\n delete(t: unknown): DeleteChain\n transaction<T>(fn: (tx: DailyReportDb) => Promise<T>, config?: unknown): Promise<T>\n}\n\n/** getColumns へ構造型テーブルを渡すための境界キャスト。 */\nconst cols = (t: unknown) => getColumns(t as Parameters<typeof getColumns>[0])\n\n// ---- サービス設定 ----\n\nexport type DailyReportServiceConfig = {\n /** drizzle mssql データベースハンドル。 */\n db: DailyReportDb\n /** 日報 6 テーブル (アプリ既存モデルまたは defineDailyReportSchema 生成物)。 */\n tables: DailyReportTables\n /** 表示名解決に使う外部ユーザーテーブル ({ id, displayName })。 */\n userTable: DailyReportUserTable\n /** 外部ユーザー ID → 内部数値 ID の解決ポート。 */\n resolveUserId: DailyReportResolveUserId\n /** 内部数値 ID の難読化ポート。 */\n encodeUserId: DailyReportEncodeUserId\n /** SSE publish / epoch 用 redis (省略時は SSE publish スキップ・epoch 無効)。 */\n redis?: DailyReportRedisProvider\n /** レガシー等の外部ソースアダプタ群。 */\n externalSources?: DailyReportExternalSource[]\n /** SQL 結果キャッシュ (facade が生成して注入)。 */\n cache: SqlResultCache\n /** クロスワーカー epoch ストア (facade が生成して注入)。 */\n epochs: EpochStore\n /**\n * 下書きラベル名 (必須)。ドラフトのクロスユーザー可視性フィルタに使うため、\n * サイレントな既定値を持たせず消費アプリが自 DB のラベル名を必ず注入する。\n */\n draftLabelName: string\n /** SSE Redis Stream キー (既定 \"daily-report:sse-stream\")。 */\n streamKey?: string\n /** SSE Stream の MAXLEN (既定 10000)。 */\n streamMaxLen?: number\n /** IDs 一覧キャッシュ TTL (既定 180,000ms)。 */\n idsTtlMs?: number\n /** 営業日別キャッシュ TTL (既定 300,000ms)。 */\n businessDateTtlMs?: number\n /** 外部 ID → 内部 ID のプロセス内キャッシュを無効化 (テスト用)。 */\n disableUserIdCache?: boolean\n /** ロガー (既定は console ベース)。 */\n logger?: DailyReportLogger\n}\n\n/** createDailyReportService の返却型。 */\nexport type DailyReportService = ReturnType<typeof createDailyReportService>\n\n/**\n * Creates the daily-report data-access service bound to the injected dependencies.\n * 注入された依存に束縛された日報データアクセスサービスを生成する処理。\n */\nexport function createDailyReportService(config: DailyReportServiceConfig) {\n const { db, tables, userTable: users, resolveUserId, encodeUserId, redis, cache: sqlResultCache, epochs } = config\n const { hub: DailyReportHub, internal: DailyReportInternal, comment: DailyReportCommentModel, label: DailyReportLabel, hubLabel: DailyReportHub_Label, userStatus: DailyReportUserStatus } = tables\n const externalSources = config.externalSources ?? []\n const draftLabelName = config.draftLabelName\n const logger = config.logger ?? createLogger(LogLevel.INFO, \"[DailyReportService]\")\n\n const DAILY_REPORT_IDS_CACHE_KEY = \"daily-report:ids\"\n const DAILY_REPORT_IDS_TTL_MS = config.idsTtlMs ?? 180_000\n const DAILY_REPORT_IDS_EPOCH_KEY = \"daily-report:ids:epoch\"\n\n const DAILY_REPORT_BUSINESS_DATE_CACHE_PREFIX = \"daily-report:business-date:\"\n const DAILY_REPORT_BUSINESS_DATE_TTL_MS = config.businessDateTtlMs ?? 300_000\n\n /** 営業日キャッシュのクロスワーカー epoch プレフィックス */\n const DAILY_REPORT_DATE_EPOCH_PREFIX = \"daily-report:date-epoch:\"\n /** レポート詳細キャッシュのクロスワーカー epoch プレフィックス */\n const DAILY_REPORT_DETAIL_EPOCH_PREFIX = \"daily-report:detail-epoch:\"\n\n const DAILY_REPORT_SSE_STREAM_KEY = config.streamKey ?? \"daily-report:sse-stream\"\n const DAILY_REPORT_SSE_STREAM_MAXLEN = config.streamMaxLen ?? 10000\n\n const incrementRedisEpoch = (key: string) => epochs.incrementEpoch(key)\n\n /**\n * Publishes a message to the SSE Redis Stream.\n * SSE 用の Redis Stream にメッセージを追加する。\n */\n const publishToSseStream = async (message: Record<string, unknown>, callerName: string): Promise<void> => {\n const client = await redis?.getClient()\n if (!client) {\n logger.warn(`[SSE] Redis client unavailable (${callerName})`)\n return\n }\n const publishStartMs = Date.now()\n try {\n await client.xAdd(DAILY_REPORT_SSE_STREAM_KEY, \"*\", { data: JSON.stringify(message) }, { TRIM: { strategy: \"MAXLEN\", strategyModifier: \"~\", threshold: DAILY_REPORT_SSE_STREAM_MAXLEN } })\n const publishDurationMs = Date.now() - publishStartMs\n if (publishDurationMs > 1000) {\n logger.warn(`[SSE] Slow publish (${callerName}): ${publishDurationMs}ms`)\n }\n } catch (e) {\n logger.error(`[SSE] Redis publish failed (${callerName}):`, e)\n }\n }\n\n type DatePattern = \"YYYY-MM-DD HH:mm:ss\" | \"YYYY-MM-DD\"\n\n /**\n * Formats date-like values to a given pattern (ja-JP locale semantics preserved).\n * 日付相当の値を指定パターンに整形する処理。\n */\n const formatDateValue = (value: Date | string | null | undefined, pattern: DatePattern): string | null => {\n if (!value) {\n return null\n }\n\n const dateValue = value instanceof Date ? value : new Date(value)\n if (Number.isNaN(dateValue.getTime())) {\n return typeof value === \"string\" ? value : null\n }\n\n // ja-JP ロケールの YYYY/MM/DD (HH:mm:ss) を生成しハイフン区切りへ正規化する\n const opts: Intl.DateTimeFormatOptions = pattern === \"YYYY-MM-DD HH:mm:ss\" ? { year: \"numeric\", month: \"2-digit\", day: \"2-digit\", hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\" } : { year: \"numeric\", month: \"2-digit\", day: \"2-digit\" }\n const formatted = pattern === \"YYYY-MM-DD HH:mm:ss\" ? dateValue.toLocaleString(\"ja-JP\", opts) : dateValue.toLocaleDateString(\"ja-JP\", opts)\n return formatted.replace(/\\//g, \"-\")\n }\n\n /**\n * Masks a raw audit-actor value (created_by / updated_by) before client exposure.\n * 監査列 (created_by / updated_by) をクライアント公開前にマスクする処理。\n *\n * Internal 由来の値は String(userId) の生内部 ID のため、数値なら encodeUserId で難読化する。\n * 非数値 (外部ソース由来の氏名やシステム文字列) はそのまま返す。null / 空文字は null。\n * userId フィールドと同じ難読化を監査列にも適用し、内部 ID の横流し漏洩を防ぐ。\n */\n const maskAuditActor = (value: string | null | undefined): string | null => {\n if (value == null || value === \"\") return null\n return /^\\d+$/.test(value) ? encodeUserId(Number(value)) : value\n }\n\n type RawJsonComment = {\n id: number\n content: string\n createdAt: string\n userId: number\n userName: string\n }\n\n type RawJsonLabel = {\n id: number\n name: string\n color: string | null\n }\n\n /** 詳細クエリ 1 行 (外部ソース列は `ext_<sourceType>` キーで同居)。 */\n type HubQueryRow = {\n hub: DailyReportHubRow\n internal: DailyReportInternalRow | null\n isRead?: boolean | null\n isStarred?: boolean | null\n creatorName?: string | null\n } & Record<string, unknown>\n\n type HubRecord = HubQueryRow & {\n labels?: RawJsonLabel[]\n comments?: RawJsonComment[]\n }\n\n /** 外部ソースアダプタの select 追加フィールドを構築する。 */\n const externalSelections = (): Record<string, unknown> => {\n const out: Record<string, unknown> = {}\n for (const adapter of externalSources) {\n out[`ext_${adapter.sourceType}`] = cols(adapter.table)\n }\n return out\n }\n\n /** 外部ソースアダプタの LEFT JOIN を select チェーンへ適用する。 */\n const applyExternalJoins = <T>(chain: SelectChain<T>): SelectChain<T> => {\n let c = chain\n for (const adapter of externalSources) {\n c = c.leftJoin(adapter.table, and(eq(DailyReportHub.sourceType, adapter.sourceType), eq(DailyReportHub.sourceIdNum, adapter.idColumn)))\n }\n return c\n }\n\n /**\n * Converts a Hub record into a DailyReportDetail structure.\n * Hub レコードを DailyReportDetail に変換する処理。\n */\n const mapHubRecord = (row: HubRecord, currentUserId?: number): DailyReportDetail => {\n const { hub, internal } = row\n\n let content = hub.summary\n let interviewers: DailyReportInterviewer[] = []\n let category: string | null = null\n let creationCategory: string | null = null\n let visitTimeFrom: string | null = null\n let visitTimeTo: string | null = null\n let customerName: string | null = null\n let employeeName: string | null = null\n let comments: DailyReportComment[] = []\n\n // 外部ソースアダプタ優先 → Internal の順で表示フィールドを解決する\n const adapter = externalSources.find((a) => a.sourceType === hub.sourceType)\n const externalRow = adapter ? (row[`ext_${adapter.sourceType}`] as Record<string, unknown> | null | undefined) : undefined\n if (adapter && externalRow) {\n const fields = adapter.mapRow(externalRow)\n if (fields.content !== undefined) content = fields.content\n if (fields.employeeName !== undefined) employeeName = fields.employeeName\n if (fields.category !== undefined) category = fields.category\n if (fields.creationCategory !== undefined) creationCategory = fields.creationCategory\n if (fields.visitTimeFrom !== undefined) visitTimeFrom = fields.visitTimeFrom\n if (fields.visitTimeTo !== undefined) visitTimeTo = fields.visitTimeTo\n if (fields.customerName !== undefined) customerName = fields.customerName\n if (fields.interviewers !== undefined) interviewers = fields.interviewers\n if (fields.comments !== undefined) comments = fields.comments\n } else if (hub.sourceType === \"Internal\" && internal) {\n content = internal.body\n // Internal specific mappings if any\n }\n\n const labelsRaw = row.labels ?? []\n const commentItemsRaw = row.comments ?? []\n\n return {\n reportHubId: hub.id,\n date: formatDateValue(hub.businessDate, \"YYYY-MM-DD\"),\n author: row.creatorName ?? maskAuditActor(hub.createdBy) ?? \"\",\n userId: hub.userId ? encodeUserId(hub.userId) : \"\",\n createdAt: formatDateValue(hub.createdAt, \"YYYY-MM-DD HH:mm:ss\"),\n updatedAt: formatDateValue(hub.updatedAt, \"YYYY-MM-DD HH:mm:ss\"),\n updatedBy: maskAuditActor(hub.updatedBy),\n employeeName: employeeName ?? row.creatorName ?? maskAuditActor(hub.createdBy),\n category,\n creationCategory,\n visitTimeFrom,\n visitTimeTo,\n customerName,\n interviewers,\n subject: hub.title,\n content,\n comments,\n isRead: row.isRead ?? false,\n isStarred: row.isStarred ?? false,\n labels: labelsRaw.map((l) => ({\n id: l.id,\n name: l.name,\n color: l.color,\n })),\n commentItems: commentItemsRaw.map((c) => ({\n ...c,\n userId: encodeUserId(c.userId),\n isMine: currentUserId ? c.userId === currentUserId : false,\n })),\n }\n }\n\n /**\n * Fetches daily report IDs alongside normalized business dates.\n * 日報 ID と正規化済み営業日を取得する内部処理。\n */\n const fetchDailyReportIdsByUserId = async (userId: number): Promise<DailyReportItem[]> => {\n const DraftLabelRelation = aliasedTable(DailyReportHub_Label as unknown as Parameters<typeof aliasedTable>[0], \"draft_label\") as unknown as typeof DailyReportHub_Label\n\n const result = await db\n .select<{ reportHubId: number; businessDate: Date | string | null }>({\n reportHubId: DailyReportHub.id,\n businessDate: DailyReportHub.businessDate,\n })\n .from(DailyReportHub)\n .leftJoin(DraftLabelRelation, and(eq(DraftLabelRelation.hubId, DailyReportHub.id), eq(DraftLabelRelation.labelId, db.select({ id: DailyReportLabel.id }).top(1).from(DailyReportLabel).where(eq(DailyReportLabel.name, draftLabelName)))))\n .where(and(isNull(DailyReportHub.deletedAt), or(eq(DailyReportHub.userId, userId), isNull(DraftLabelRelation.hubId))))\n .orderBy(desc(DailyReportHub.businessDate), desc(DailyReportHub.id))\n\n return result.map((item) => ({\n ...item,\n businessDate: formatDateValue(item.businessDate, \"YYYY-MM-DD\"),\n }))\n }\n\n /**\n * Fetches daily report details for the provided business date.\n * 指定した営業日の日報詳細を取得する内部処理。\n */\n const fetchDailyReportsByBusinessDate = async (normalizedBusinessDate: string): Promise<DailyReportDetail[]> => {\n const rows = await applyExternalJoins(\n db\n .select<HubQueryRow>({\n hub: cols(DailyReportHub),\n internal: cols(DailyReportInternal),\n creatorName: users.displayName,\n ...externalSelections(),\n })\n .from(DailyReportHub),\n )\n .leftJoin(DailyReportInternal, eq(DailyReportHub.id, DailyReportInternal.hubId))\n .leftJoin(users, eq(DailyReportHub.userId, users.id))\n .where(and(eq(DailyReportHub.businessDate, sql`${normalizedBusinessDate}`), isNull(DailyReportHub.deletedAt)))\n .orderBy(desc(DailyReportHub.id))\n\n return rows.map((row) => mapHubRecord(row))\n }\n\n /**\n * Builds a deterministic cache key for business-date caches.\n * 営業日キャッシュ用の一意キーを生成する処理。\n */\n const buildBusinessDateCacheKey = (normalizedBusinessDate: string): string => {\n return `${DAILY_REPORT_BUSINESS_DATE_CACHE_PREFIX}${normalizedBusinessDate}`\n }\n\n /**\n * Resolves the internal user ID from an external ID (with process-local caching).\n * 外部 ID から内部ユーザー ID を解決する (プロセス内キャッシュ付き)。\n */\n const userIdCache = new Map<string, number>()\n\n const getUserIdByExternalId = async (externalId: string): Promise<number | null> => {\n if (!config.disableUserIdCache && userIdCache.has(externalId)) {\n return userIdCache.get(externalId) ?? null\n }\n\n const userId = await resolveUserId(externalId)\n if (userId !== null && !config.disableUserIdCache) {\n userIdCache.set(externalId, userId)\n }\n return userId\n }\n\n /**\n * Retrieves daily report IDs and their normalized business dates.\n * 日報 ID と正規化済み営業日を取得する処理。\n */\n const getDailyReportIdsByExternalId = async (externalId: string, { forceRefresh = false, snapshot = false, ttlMsOverride }: SqlResultCacheQueryOptions = {}): Promise<DailyReportItem[]> => {\n const userId = await getUserIdByExternalId(externalId)\n if (!userId) {\n return []\n }\n\n const cacheKey = `${DAILY_REPORT_IDS_CACHE_KEY}:user:${userId}`\n return sqlResultCache.getOrFetch<DailyReportItem>({\n cacheKey,\n fetcher: async () => {\n const res = await fetchDailyReportIdsByUserId(userId)\n return res\n },\n forceRefresh,\n snapshot,\n ttlMsOverride: ttlMsOverride ?? DAILY_REPORT_IDS_TTL_MS,\n epochKey: DAILY_REPORT_IDS_EPOCH_KEY,\n }) as Promise<DailyReportItem[]>\n }\n\n /**\n * Retrieves daily report details for a business date (⚠️ NOT per-user filtered).\n * 指定した営業日に紐づく日報詳細を取得する処理 (⚠️ ユーザー別フィルタなし)。\n *\n * ⚠️ SECURITY: この関数は下書きラベルによる可視性フィルタ (他ユーザーの下書きを隠す) と\n * ユーザー別の既読/スター状態を **適用しない**。取得結果は全ユーザーの下書きを含み得るため、\n * HTTP レスポンス / SSR loader / SSE へ **直接返してはならない**。ユーザー向け配信には\n * 必ず {@link getDailyReportsByBusinessDateByExternalId} を使うこと。\n * (本関数は管理・バッチ・テスト用途に限定する。)\n */\n const getDailyReportsByBusinessDate = (businessDate: string, { forceRefresh = false, snapshot = false, ttlMsOverride }: SqlResultCacheQueryOptions = {}): Promise<DailyReportDetail[]> => {\n const normalizedBusinessDate = normalizeBusinessDateKey(businessDate)\n if (!normalizedBusinessDate) {\n return Promise.resolve([])\n }\n\n return sqlResultCache.getOrFetch<DailyReportDetail>({\n cacheKey: buildBusinessDateCacheKey(normalizedBusinessDate),\n fetcher: () => fetchDailyReportsByBusinessDate(normalizedBusinessDate),\n forceRefresh,\n snapshot,\n ttlMsOverride: ttlMsOverride ?? DAILY_REPORT_BUSINESS_DATE_TTL_MS,\n }) as Promise<DailyReportDetail[]>\n }\n\n /**\n * Retrieves the ID of the draft label.\n * 下書きラベルの ID を取得する(キャッシュ付き)。\n */\n let cachedDraftLabelId: number | null = null\n const getDraftLabelId = async (): Promise<number | null> => {\n if (cachedDraftLabelId !== null) return cachedDraftLabelId\n const [label] = await db.select<{ id: number }>({ id: DailyReportLabel.id }).top(1).from(DailyReportLabel).where(eq(DailyReportLabel.name, draftLabelName))\n\n if (label) {\n cachedDraftLabelId = label.id\n return cachedDraftLabelId\n }\n return null\n }\n\n /**\n * Retrieves daily report details for a business date with user-specific status and relations.\n * 指定した営業日の日報詳細を、ユーザー状態と関連データを含めて取得する。\n */\n const getDailyReportsByBusinessDateByExternalId = async (businessDate: string, externalId: string, { forceRefresh = false, snapshot = false, ttlMsOverride }: SqlResultCacheQueryOptions = {}): Promise<DailyReportDetail[]> => {\n const userId = await getUserIdByExternalId(externalId)\n if (!userId) {\n return []\n }\n\n const normalizedBusinessDate = normalizeBusinessDateKey(businessDate)\n if (!normalizedBusinessDate) {\n return []\n }\n\n const cacheKey = `daily-report:date:${normalizedBusinessDate}:user:${userId}`\n\n return sqlResultCache.getOrFetch<DailyReportDetail>({\n cacheKey,\n fetcher: async () => {\n const draftLabelId = await getDraftLabelId()\n const DraftLabelRelation = aliasedTable(DailyReportHub_Label as unknown as Parameters<typeof aliasedTable>[0], \"draft_label\") as unknown as typeof DailyReportHub_Label\n\n const rows = await applyExternalJoins(\n db\n .select<HubQueryRow>({\n hub: cols(DailyReportHub),\n internal: cols(DailyReportInternal),\n isRead: DailyReportUserStatus.isRead,\n isStarred: DailyReportUserStatus.isStarred,\n creatorName: users.displayName,\n ...externalSelections(),\n })\n .from(DailyReportHub),\n )\n .leftJoin(DailyReportInternal, eq(DailyReportHub.id, DailyReportInternal.hubId))\n .leftJoin(DailyReportUserStatus, and(eq(DailyReportHub.id, DailyReportUserStatus.hubId), eq(DailyReportUserStatus.userId, userId)))\n .leftJoin(DraftLabelRelation, and(eq(DraftLabelRelation.hubId, DailyReportHub.id), eq(DraftLabelRelation.labelId, draftLabelId ?? -1)))\n .leftJoin(users, eq(DailyReportHub.userId, users.id))\n .where(and(eq(DailyReportHub.businessDate, sql`${normalizedBusinessDate}`), isNull(DailyReportHub.deletedAt), or(eq(DailyReportHub.userId, userId), isNull(DraftLabelRelation.hubId))))\n .orderBy(desc(DailyReportHub.id))\n\n if (rows.length === 0) {\n return []\n }\n\n const hubIds = rows.map((r) => r.hub.id)\n\n // Drizzle ORM batch queries to fetch labels and comments\n const allLabels = await db\n .select<{ hubId: number; id: number; name: string; color: string | null }>({\n hubId: DailyReportHub_Label.hubId,\n id: DailyReportLabel.id,\n name: DailyReportLabel.name,\n color: DailyReportLabel.color,\n })\n .from(DailyReportHub_Label)\n .innerJoin(DailyReportLabel, eq(DailyReportHub_Label.labelId, DailyReportLabel.id))\n .where(inArray(DailyReportHub_Label.hubId, hubIds))\n\n const allComments = await db\n .select<{ hubId: number; id: number; body: string; createdAt: Date | string; userId: number; userName: string | null }>({\n hubId: DailyReportCommentModel.hubId,\n id: DailyReportCommentModel.id,\n body: DailyReportCommentModel.body,\n createdAt: DailyReportCommentModel.createdAt,\n userId: DailyReportCommentModel.userId,\n userName: users.displayName,\n })\n .from(DailyReportCommentModel)\n .leftJoin(users, eq(DailyReportCommentModel.userId, users.id))\n .where(inArray(DailyReportCommentModel.hubId, hubIds))\n .orderBy(asc(DailyReportCommentModel.createdAt))\n\n const labelsMap = new Map<number, RawJsonLabel[]>()\n const commentsMap = new Map<number, RawJsonComment[]>()\n\n for (const label of allLabels) {\n let list = labelsMap.get(label.hubId)\n if (!list) {\n list = []\n labelsMap.set(label.hubId, list)\n }\n list.push({\n id: label.id,\n name: label.name,\n color: label.color,\n })\n }\n\n for (const comment of allComments) {\n let list = commentsMap.get(comment.hubId)\n if (!list) {\n list = []\n commentsMap.set(comment.hubId, list)\n }\n list.push({\n id: comment.id,\n content: comment.body,\n createdAt: formatDateValue(comment.createdAt, \"YYYY-MM-DD HH:mm:ss\") || \"\",\n userId: comment.userId,\n userName: comment.userName || \"\",\n })\n }\n\n return rows.map((row) => {\n const hubId = row.hub.id\n return mapHubRecord(\n {\n ...row,\n labels: labelsMap.get(hubId) || [],\n comments: commentsMap.get(hubId) || [],\n },\n userId,\n )\n })\n },\n forceRefresh,\n snapshot,\n ttlMsOverride: ttlMsOverride ?? DAILY_REPORT_BUSINESS_DATE_TTL_MS,\n epochKey: `${DAILY_REPORT_DATE_EPOCH_PREFIX}${normalizedBusinessDate}`,\n }) as Promise<DailyReportDetail[]>\n }\n\n /**\n * Retrieves a single daily report detail by ID with user-specific status and relations.\n * 指定した日報詳細を、ユーザー状態と関連データを含めて取得する。\n */\n const getDailyReportDetailById = async (reportHubId: number, userId: number, { forceRefresh = false, snapshot = false, ttlMsOverride }: SqlResultCacheQueryOptions = {}): Promise<DailyReportDetail | null> => {\n const cacheKey = `daily-report:detail:${reportHubId}:user:${userId}`\n\n const results = (await sqlResultCache.getOrFetch<DailyReportDetail>({\n cacheKey,\n fetcher: async () => {\n const rows = await applyExternalJoins(\n db\n .select<HubQueryRow>({\n hub: cols(DailyReportHub),\n internal: cols(DailyReportInternal),\n isRead: DailyReportUserStatus.isRead,\n isStarred: DailyReportUserStatus.isStarred,\n creatorName: users.displayName,\n ...externalSelections(),\n })\n .from(DailyReportHub),\n )\n .leftJoin(DailyReportInternal, eq(DailyReportHub.id, DailyReportInternal.hubId))\n .leftJoin(DailyReportUserStatus, and(eq(DailyReportHub.id, DailyReportUserStatus.hubId), eq(DailyReportUserStatus.userId, userId)))\n .leftJoin(users, eq(DailyReportHub.userId, users.id))\n .where(and(eq(DailyReportHub.id, reportHubId), isNull(DailyReportHub.deletedAt)))\n\n if (rows.length === 0) {\n return []\n }\n\n const hubId = rows[0].hub.id\n\n // Fetch labels and comments via Drizzle ORM\n const labels = await db\n .select<{ id: number; name: string; color: string | null }>({\n id: DailyReportLabel.id,\n name: DailyReportLabel.name,\n color: DailyReportLabel.color,\n })\n .from(DailyReportHub_Label)\n .innerJoin(DailyReportLabel, eq(DailyReportHub_Label.labelId, DailyReportLabel.id))\n .where(eq(DailyReportHub_Label.hubId, hubId))\n\n const comments = await db\n .select<{ id: number; body: string; createdAt: Date | string; userId: number; userName: string | null }>({\n id: DailyReportCommentModel.id,\n body: DailyReportCommentModel.body,\n createdAt: DailyReportCommentModel.createdAt,\n userId: DailyReportCommentModel.userId,\n userName: users.displayName,\n })\n .from(DailyReportCommentModel)\n .leftJoin(users, eq(DailyReportCommentModel.userId, users.id))\n .where(eq(DailyReportCommentModel.hubId, hubId))\n .orderBy(asc(DailyReportCommentModel.createdAt))\n\n const labelsMapped = labels.map((l) => ({\n id: l.id,\n name: l.name,\n color: l.color,\n }))\n\n const commentsMapped = comments.map((c) => ({\n id: c.id,\n content: c.body,\n createdAt: formatDateValue(c.createdAt, \"YYYY-MM-DD HH:mm:ss\") || \"\",\n userId: c.userId,\n userName: c.userName || \"\",\n }))\n\n return [\n mapHubRecord(\n {\n ...rows[0],\n labels: labelsMapped,\n comments: commentsMapped,\n },\n userId,\n ),\n ]\n },\n forceRefresh,\n snapshot,\n ttlMsOverride: ttlMsOverride ?? DAILY_REPORT_BUSINESS_DATE_TTL_MS,\n epochKey: `${DAILY_REPORT_DETAIL_EPOCH_PREFIX}${reportHubId}`,\n })) as DailyReportDetail[]\n\n return results[0] ?? null\n }\n\n /**\n * Retrieves a single daily report detail by ID with user-specific status and relations.\n * 指定した日報詳細を、ユーザー状態と関連データを含めて取得する。\n */\n const getDailyReportDetailByIdByExternalId = async (reportHubId: number, externalId: string, options: SqlResultCacheQueryOptions = {}): Promise<DailyReportDetail | null> => {\n const userId = await getUserIdByExternalId(externalId)\n if (!userId) {\n return null\n }\n return getDailyReportDetailById(reportHubId, userId, options)\n }\n\n /**\n * Sets the starred status of a daily report for a user.\n * ユーザーの日報スター状態を設定する。\n */\n const setStarStatus = async (userId: number, reportHubId: number, businessDate: string | null, isStarred: boolean, clientTempId: string): Promise<DailyReportUserStatusRow> => {\n const existing = await db\n .select<DailyReportUserStatusRow>()\n .top(1)\n .from(DailyReportUserStatus)\n .where(and(eq(DailyReportUserStatus.hubId, reportHubId), eq(DailyReportUserStatus.userId, userId)))\n\n let updatedStatus: DailyReportUserStatusRow\n\n if (existing.length > 0) {\n if (existing[0].isStarred !== isStarred) {\n const rows = await db\n .update<DailyReportUserStatusRow>(DailyReportUserStatus)\n .set({\n isStarred: isStarred,\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n .output()\n .where(and(eq(DailyReportUserStatus.hubId, reportHubId), eq(DailyReportUserStatus.userId, userId)))\n updatedStatus = rows[0]\n } else {\n updatedStatus = existing[0]\n }\n } else {\n const rows = await db\n .insert<DailyReportUserStatusRow>(DailyReportUserStatus)\n .output()\n .values({\n hubId: reportHubId,\n userId,\n isStarred: isStarred,\n isRead: false,\n createdAt: new Date(),\n createdBy: String(userId),\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n updatedStatus = rows[0]\n }\n\n if (businessDate) {\n const normalizedDate = normalizeBusinessDateKey(businessDate)\n if (normalizedDate) {\n sqlResultCache.invalidate(`daily-report:date:${normalizedDate}:user:${userId}`)\n await incrementRedisEpoch(`${DAILY_REPORT_DATE_EPOCH_PREFIX}${normalizedDate}`)\n }\n }\n sqlResultCache.invalidate(`daily-report:detail:${reportHubId}`)\n sqlResultCache.invalidate(`daily-report:detail:${reportHubId}:user:${userId}`)\n await incrementRedisEpoch(`${DAILY_REPORT_DETAIL_EPOCH_PREFIX}${reportHubId}`)\n\n await publishToSseStream(\n statusUpdateMessageSchema.parse({\n type: \"status-update\",\n reportHubId: reportHubId,\n recipientRawUserId: userId,\n statusType: \"star\",\n value: isStarred,\n clientTempId,\n }),\n \"setStarStatus\",\n )\n\n return updatedStatus\n }\n\n /**\n * Sets the read status of a daily report for a user.\n * ユーザーの日報既読状態を設定する。\n */\n const setReadStatus = async (userId: number, reportHubId: number, businessDate: string | null, isRead: boolean, clientTempId: string): Promise<DailyReportUserStatusRow> => {\n const existing = await db\n .select<DailyReportUserStatusRow>()\n .top(1)\n .from(DailyReportUserStatus)\n .where(and(eq(DailyReportUserStatus.hubId, reportHubId), eq(DailyReportUserStatus.userId, userId)))\n\n let updatedStatus: DailyReportUserStatusRow\n\n if (existing.length > 0) {\n if (existing[0].isRead !== isRead) {\n const rows = await db\n .update<DailyReportUserStatusRow>(DailyReportUserStatus)\n .set({\n isRead: isRead,\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n .output()\n .where(and(eq(DailyReportUserStatus.hubId, reportHubId), eq(DailyReportUserStatus.userId, userId)))\n updatedStatus = rows[0]\n } else {\n updatedStatus = existing[0]\n }\n } else {\n const rows = await db\n .insert<DailyReportUserStatusRow>(DailyReportUserStatus)\n .output()\n .values({\n hubId: reportHubId,\n userId,\n isRead: isRead,\n isStarred: false,\n createdAt: new Date(),\n createdBy: String(userId),\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n updatedStatus = rows[0]\n }\n\n if (businessDate) {\n const normalizedDate = normalizeBusinessDateKey(businessDate)\n if (normalizedDate) {\n sqlResultCache.invalidate(`daily-report:date:${normalizedDate}:user:${userId}`)\n await incrementRedisEpoch(`${DAILY_REPORT_DATE_EPOCH_PREFIX}${normalizedDate}`)\n }\n }\n sqlResultCache.invalidate(`daily-report:detail:${reportHubId}`)\n sqlResultCache.invalidate(`daily-report:detail:${reportHubId}:user:${userId}`)\n await incrementRedisEpoch(`${DAILY_REPORT_DETAIL_EPOCH_PREFIX}${reportHubId}`)\n\n await publishToSseStream(\n statusUpdateMessageSchema.parse({\n type: \"status-update\",\n reportHubId: reportHubId,\n recipientRawUserId: userId,\n statusType: \"read\",\n value: isRead,\n clientTempId,\n }),\n \"setReadStatus\",\n )\n\n return updatedStatus\n }\n\n /**\n * Adds a comment to a daily report.\n * 日報にコメントを追加する。\n */\n const addComment = async (userId: number, reportHubId: number, content: string, businessDate: string | null, clientTempId: string): Promise<DailyReportCommentItem> => {\n const [inserted] = await db\n .insert<DailyReportCommentRow>(DailyReportCommentModel)\n .output()\n .values({\n hubId: reportHubId,\n userId,\n body: content,\n createdAt: new Date(),\n createdBy: String(userId),\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n\n const [user] = await db.select<{ displayName: string | null }>({ displayName: users.displayName }).top(1).from(users).where(eq(users.id, userId))\n const userName = user?.displayName ?? \"Unknown\"\n\n // コメントは全ユーザーに表示されるため、date キャッシュも全ユーザー分を無効化\n if (businessDate) {\n const normalizedDate = normalizeBusinessDateKey(businessDate)\n if (normalizedDate) {\n sqlResultCache.invalidatePrefix(`daily-report:date:${normalizedDate}:user:`)\n await incrementRedisEpoch(`${DAILY_REPORT_DATE_EPOCH_PREFIX}${normalizedDate}`)\n }\n }\n sqlResultCache.invalidate(`daily-report:detail:${reportHubId}`)\n sqlResultCache.invalidatePrefix(`daily-report:detail:${reportHubId}:user:`)\n await incrementRedisEpoch(`${DAILY_REPORT_DETAIL_EPOCH_PREFIX}${reportHubId}`)\n\n const commentItem: DailyReportCommentItem = {\n id: inserted.id,\n userId: encodeUserId(inserted.userId),\n userName: userName,\n content: inserted.body,\n createdAt: formatDateValue(inserted.createdAt, \"YYYY-MM-DD HH:mm:ss\") ?? \"\",\n isMine: true,\n }\n\n await publishToSseStream(\n commentAddMessageSchema.parse({\n type: \"comment-add\",\n reportHubId: reportHubId,\n comment: commentItem,\n clientTempId,\n }),\n \"addComment\",\n )\n\n return commentItem\n }\n\n /**\n * Finds a daily report comment by ID.\n * 日報コメントをIDで検索する。\n */\n const findDailyReportCommentById = async (tx: DailyReportDb, commentId: number) => {\n return await tx.select<DailyReportCommentRow>().top(1).from(DailyReportCommentModel).where(eq(DailyReportCommentModel.id, commentId))\n }\n\n /**\n * Deletes a comment from a daily report.\n * 日報のコメントを削除する。\n */\n const deleteComment = async (userId: number, reportHubId: number, commentId: number, businessDate: string | null, clientTempId: string): Promise<void> => {\n const comments = await findDailyReportCommentById(db, commentId)\n if (comments.length === 0) {\n throw new Error(\"Not Found\")\n }\n if (comments[0].userId !== userId) {\n throw new Error(\"Unauthorized\")\n }\n\n await db.delete(DailyReportCommentModel).where(eq(DailyReportCommentModel.id, commentId))\n\n // コメントは全ユーザーに表示されるため、date キャッシュも全ユーザー分を無効化\n if (businessDate) {\n const normalizedDate = normalizeBusinessDateKey(businessDate)\n if (normalizedDate) {\n sqlResultCache.invalidatePrefix(`daily-report:date:${normalizedDate}:user:`)\n await incrementRedisEpoch(`${DAILY_REPORT_DATE_EPOCH_PREFIX}${normalizedDate}`)\n }\n }\n sqlResultCache.invalidate(`daily-report:detail:${reportHubId}`)\n sqlResultCache.invalidatePrefix(`daily-report:detail:${reportHubId}:user:`)\n await incrementRedisEpoch(`${DAILY_REPORT_DETAIL_EPOCH_PREFIX}${reportHubId}`)\n\n await publishToSseStream(\n commentDeleteMessageSchema.parse({\n type: \"comment-delete\",\n reportHubId: reportHubId,\n commentId,\n clientTempId,\n }),\n \"deleteComment\",\n )\n }\n\n /**\n * Creates a new draft daily report.\n * 新しい日報(下書き)を作成する。\n */\n const createDailyReport = async (userId: number, businessDate: string, clientTempId: string): Promise<DailyReportDetail> => {\n logger.info(\"createDailyReport called\", { userId, businessDate })\n\n // ユーザー名取得\n const [user] = await db.select<{ displayName: string | null }>({ displayName: users.displayName }).from(users).where(eq(users.id, userId))\n const userName = user?.displayName ?? encodeUserId(userId)\n\n try {\n const result = await db.transaction(async (tx) => {\n logger.info(\"Starting transaction\")\n // 1. Hub作成\n const sourceId = `internal-temp-${Date.now()}-${Math.random()}` // 一時的なID\n const [hub] = await tx\n .insert<DailyReportHubRow>(DailyReportHub)\n .output()\n .values({\n sourceType: \"Internal\",\n sourceId: sourceId,\n businessDate: new Date(businessDate),\n userId: userId,\n title: \"(無題)\",\n createdAt: new Date(),\n createdBy: String(userId),\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n\n // sourceId を id と同じ値に更新 (Internal の場合の正規化)\n await tx\n .update(DailyReportHub)\n .set({ sourceId: String(hub.id) })\n .where(eq(DailyReportHub.id, hub.id))\n\n logger.info(\"Hub created\", hub)\n\n // 2. Internal作成\n await tx.insert(DailyReportInternal).values({\n hubId: hub.id,\n body: \"\",\n createdAt: new Date(),\n createdBy: String(userId),\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n logger.info(\"Internal created\")\n\n // 3. ラベル付与\n logger.info(\"Calling getDraftLabelId\")\n const draftLabelId = await getDraftLabelId()\n logger.info(\"draftLabelId\", draftLabelId)\n const labels: DailyReportLabelDef[] = []\n if (draftLabelId) {\n await tx.insert(DailyReportHub_Label).values({\n hubId: hub.id,\n labelId: draftLabelId,\n createdAt: new Date(),\n createdBy: String(userId),\n })\n labels.push({ id: draftLabelId, name: draftLabelName, color: null })\n }\n logger.info(\"Label assigned\")\n\n // 4. 詳細オブジェクト構築\n return {\n reportHubId: hub.id,\n date: businessDate,\n createdAt: formatDateValue(hub.createdAt, \"YYYY-MM-DD HH:mm:ss\"),\n author: userName,\n userId: encodeUserId(userId),\n employeeName: userName,\n // 監査列と同様、クライアント公開時は生内部 ID を難読化する (mapHubRecord と整合)\n updatedBy: encodeUserId(userId),\n updatedAt: formatDateValue(hub.updatedAt, \"YYYY-MM-DD HH:mm:ss\"),\n category: null,\n creationCategory: null,\n visitTimeFrom: null,\n visitTimeTo: null,\n customerName: null,\n interviewers: [],\n subject: hub.title,\n content: \"\",\n comments: [],\n isRead: true, // 自分で作ったので既読\n isStarred: false,\n labels: labels,\n commentItems: [],\n }\n })\n\n // キャッシュ無効化\n const normalizedBusinessDate = normalizeBusinessDateKey(businessDate)\n if (normalizedBusinessDate) {\n sqlResultCache.invalidate(`daily-report:date:${normalizedBusinessDate}:user:${userId}`)\n }\n sqlResultCache.invalidatePrefix(DAILY_REPORT_BUSINESS_DATE_CACHE_PREFIX)\n sqlResultCache.invalidate(`${DAILY_REPORT_IDS_CACHE_KEY}:user:${userId}`)\n // ❗ 順序重要: invalidate → incrementRedisEpoch → publishToSseStream\n await incrementRedisEpoch(DAILY_REPORT_IDS_EPOCH_KEY)\n if (normalizedBusinessDate) {\n await incrementRedisEpoch(`${DAILY_REPORT_DATE_EPOCH_PREFIX}${normalizedBusinessDate}`)\n }\n\n const fullDetail = await getDailyReportDetailById(result.reportHubId, userId, { forceRefresh: true })\n\n if (fullDetail) {\n // 下書き判定\n const draftLabelId = await getDraftLabelId()\n const isDraft = draftLabelId ? fullDetail.labels.some((l) => l.id === draftLabelId) : false\n await publishToSseStream(\n reportCreateMessageSchema.parse({\n type: \"report-create\",\n reportHubId: fullDetail.reportHubId,\n report: fullDetail,\n clientTempId,\n recipientRawUserId: isDraft ? userId : undefined,\n }),\n \"createDailyReport\",\n )\n }\n\n return fullDetail ?? result\n } catch (e) {\n logger.error(\"Error in createDailyReport\", e)\n throw e\n }\n }\n\n // --- Internal Repository Layer ---\n\n /**\n * Finds a DailyReportHub by ID.\n * 日報HubをIDで検索する。\n */\n const findDailyReportHubById = async (tx: DailyReportDb, reportHubId: number) => {\n return await tx.select<DailyReportHubRow>().top(1).from(DailyReportHub).where(eq(DailyReportHub.id, reportHubId))\n }\n\n /**\n * Updates a DailyReportHub.\n * 日報Hubを更新する。\n */\n const updateDailyReportHub = async (tx: DailyReportDb, reportHubId: number, data: Partial<DailyReportHubRow>) => {\n await tx.update(DailyReportHub).set(data).where(eq(DailyReportHub.id, reportHubId))\n }\n\n /**\n * Updates a DailyReportInternal.\n * 日報Internalを更新する。\n */\n const updateDailyReportInternal = async (tx: DailyReportDb, hubId: number, data: Partial<DailyReportInternalRow>) => {\n await tx.update(DailyReportInternal).set(data).where(eq(DailyReportInternal.hubId, hubId))\n }\n\n /**\n * Deletes a label from a DailyReportHub.\n * 日報Hubからラベルを削除する。\n */\n const deleteDailyReportLabel = async (tx: DailyReportDb, hubId: number, labelId: number) => {\n await tx.delete(DailyReportHub_Label).where(and(eq(DailyReportHub_Label.hubId, hubId), eq(DailyReportHub_Label.labelId, labelId)))\n }\n\n // --- Service Layer ---\n\n /**\n * Logically deletes a daily report.\n * 日報を論理削除する。\n */\n const deleteDailyReport = async (reportHubId: number, userId: number, clientTempId: string): Promise<void> => {\n const report = await findDailyReportHubById(db, reportHubId)\n if (!report.length || report[0].deletedAt) {\n throw new Error(\"Not Found\")\n }\n if (report[0].userId !== userId) {\n throw new Error(\"Unauthorized\")\n }\n\n await updateDailyReportHub(db, reportHubId, {\n deletedAt: new Date(),\n deletedBy: String(userId),\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n\n // キャッシュ無効化\n sqlResultCache.invalidatePrefix(`daily-report:detail:${reportHubId}:user:`)\n sqlResultCache.invalidatePrefix(DAILY_REPORT_BUSINESS_DATE_CACHE_PREFIX)\n // 削除されたレポートは全ユーザーの一覧から消えるため、全ユーザーの IDs キャッシュを invalidate\n sqlResultCache.invalidatePrefix(DAILY_REPORT_IDS_CACHE_KEY)\n // ❗ 順序重要: invalidatePrefix → incrementRedisEpoch → publishToSseStream\n await incrementRedisEpoch(DAILY_REPORT_IDS_EPOCH_KEY)\n if (report[0].businessDate) {\n const normalizedDate = normalizeBusinessDateKey(formatDateValue(report[0].businessDate, \"YYYY-MM-DD\"))\n if (normalizedDate) {\n await incrementRedisEpoch(`${DAILY_REPORT_DATE_EPOCH_PREFIX}${normalizedDate}`)\n }\n }\n\n await publishToSseStream(\n reportDeleteMessageSchema.parse({\n type: \"report-delete\",\n reportHubId: reportHubId,\n clientTempId,\n }),\n \"deleteDailyReport\",\n )\n }\n\n /**\n * Updates an existing daily report.\n * 日報を更新する。\n */\n const updateDailyReport = async (reportHubId: number, userId: number, data: { title?: string; content?: string }, clientTempId: string): Promise<void> => {\n const report = await findDailyReportHubById(db, reportHubId)\n if (!report.length || report[0].deletedAt) {\n throw new Error(\"Not Found\")\n }\n if (report[0].userId !== userId) {\n throw new Error(\"Unauthorized\")\n }\n\n await db.transaction(async (tx) => {\n if (data.title !== undefined) {\n await updateDailyReportHub(tx, reportHubId, {\n title: data.title,\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n }\n if (data.content !== undefined) {\n await updateDailyReportInternal(tx, reportHubId, {\n body: data.content,\n updatedAt: new Date(),\n updatedBy: String(userId),\n })\n }\n })\n\n // キャッシュ無効化\n sqlResultCache.invalidatePrefix(`daily-report:detail:${reportHubId}:user:`)\n sqlResultCache.invalidatePrefix(DAILY_REPORT_BUSINESS_DATE_CACHE_PREFIX)\n\n const fullDetail = await getDailyReportDetailById(reportHubId, userId, { forceRefresh: true })\n if (fullDetail) {\n // 下書き判定\n const draftLabelId = await getDraftLabelId()\n const isDraft = draftLabelId ? fullDetail.labels.some((l) => l.id === draftLabelId) : false\n await publishToSseStream(\n reportUpdateMessageSchema.parse({\n type: \"report-update\",\n reportHubId: fullDetail.reportHubId,\n report: fullDetail,\n clientTempId,\n recipientRawUserId: isDraft ? userId : undefined,\n }),\n \"updateDailyReport\",\n )\n }\n }\n\n /**\n * Publishes a draft daily report.\n * 日報を公開する(下書きラベルを削除)。\n */\n const publishDailyReport = async (reportHubId: number, userId: number, clientTempId: string): Promise<DailyReportDetail | null> => {\n const report = await findDailyReportHubById(db, reportHubId)\n if (!report.length) {\n throw new Error(\"Not Found\")\n }\n if (report[0].userId !== userId) {\n throw new Error(\"Unauthorized\")\n }\n\n const draftLabelId = await getDraftLabelId()\n if (!draftLabelId) return null\n\n await deleteDailyReportLabel(db, reportHubId, draftLabelId)\n\n // キャッシュ無効化\n sqlResultCache.invalidatePrefix(`daily-report:detail:${reportHubId}:user:`)\n sqlResultCache.invalidatePrefix(DAILY_REPORT_BUSINESS_DATE_CACHE_PREFIX)\n // 公開によりドラフトが全ユーザーに可視化されるため、全ユーザーの IDs キャッシュを invalidate\n sqlResultCache.invalidatePrefix(DAILY_REPORT_IDS_CACHE_KEY)\n // ❗ 順序重要: invalidatePrefix → incrementRedisEpoch → publishToSseStream\n await incrementRedisEpoch(DAILY_REPORT_IDS_EPOCH_KEY)\n if (report[0].businessDate) {\n const normalizedDate = normalizeBusinessDateKey(formatDateValue(report[0].businessDate, \"YYYY-MM-DD\"))\n if (normalizedDate) {\n await incrementRedisEpoch(`${DAILY_REPORT_DATE_EPOCH_PREFIX}${normalizedDate}`)\n }\n }\n\n // ユーザーごとの営業日別一覧キャッシュも無効化\n const normalizedBusinessDate = normalizeBusinessDateKey(formatDateValue(report[0].businessDate, \"YYYY-MM-DD\"))\n if (normalizedBusinessDate) {\n sqlResultCache.invalidate(`daily-report:date:${normalizedBusinessDate}:user:${userId}`)\n }\n\n const fullDetail = await getDailyReportDetailById(reportHubId, userId, { forceRefresh: true })\n if (fullDetail) {\n await publishToSseStream(\n reportPublishMessageSchema.parse({\n type: \"report-publish\",\n reportHubId: fullDetail.reportHubId,\n report: fullDetail,\n clientTempId,\n }),\n \"publishDailyReport\",\n )\n }\n return fullDetail ?? null\n }\n\n return {\n // 定数 (アプリ側の互換 export 用)\n streamKey: DAILY_REPORT_SSE_STREAM_KEY,\n streamMaxLen: DAILY_REPORT_SSE_STREAM_MAXLEN,\n // ユーザー解決\n getUserIdByExternalId,\n // 参照系\n getDailyReportIdsByExternalId,\n getDailyReportsByBusinessDate,\n getDailyReportsByBusinessDateByExternalId,\n getDailyReportDetailById,\n getDailyReportDetailByIdByExternalId,\n getDraftLabelId,\n // 更新系\n setStarStatus,\n setReadStatus,\n addComment,\n deleteComment,\n createDailyReport,\n updateDailyReport,\n publishDailyReport,\n deleteDailyReport,\n // リポジトリヘルパー (統合テスト等からの直接利用向け)\n findDailyReportHubById,\n updateDailyReportHub,\n updateDailyReportInternal,\n deleteDailyReportLabel,\n }\n}\n","/**\n * External source adapter contract for legacy/foreign daily-report tables.\n * レガシー・外部由来の日報テーブルを取り込む外部ソースアダプタ契約。\n *\n * DailyReportHub.source_type がアダプタの `sourceType` に一致する行は、\n * `table` を `Hub.source_id_num = idColumn` で LEFT JOIN し、その行を\n * `mapRow` で表示フィールドへ変換する (例: 別システムのレガシー日報テーブルの取り込み)。\n */\nimport type { AnyMsSqlColumn } from \"drizzle-orm/mssql-core\"\nimport { createLogger, type DailyReportLogger, LogLevel } from \"../shared/logger\"\nimport type { DailyReportComment, DailyReportInterviewer } from \"../shared/types\"\n\n/** 外部ソース行から詳細表示へ供給するフィールド群。 */\nexport type ExternalReportFields = {\n content?: string | null\n employeeName?: string | null\n category?: string | null\n creationCategory?: string | null\n visitTimeFrom?: string | null\n visitTimeTo?: string | null\n customerName?: string | null\n interviewers?: DailyReportInterviewer[]\n comments?: DailyReportComment[]\n}\n\n/** 外部ソースアダプタ。 */\nexport type DailyReportExternalSource = {\n /** DailyReportHub.source_type の一致値 (例 \"legacy\")。 */\n sourceType: string\n /** LEFT JOIN する drizzle テーブル。 */\n table: unknown\n /** Hub.source_id_num と突き合わせる ID 列。 */\n idColumn: AnyMsSqlColumn\n /** 結合行を表示フィールドへ変換する処理。 */\n mapRow: (row: Record<string, unknown>) => ExternalReportFields\n}\n\nconst defaultLogger = createLogger(LogLevel.INFO, \"[DailyReportExternalSource]\")\n\n/**\n * Parses JSON array payloads and maps each element (fail-soft: returns [] on error).\n * JSON 配列のペイロードを解析し各要素を変換する処理 (エラー時は空配列)。\n */\nexport const transformJsonArray = <TRaw, TResult>(payload: string | null, label: string, mapper: (raw: TRaw) => TResult | null, logger: DailyReportLogger = defaultLogger): TResult[] => {\n if (!payload) {\n return []\n }\n\n try {\n const parsed = JSON.parse(payload)\n if (!Array.isArray(parsed)) {\n logger.warn(`Unexpected ${label} format: not an array`)\n return []\n }\n return (parsed as TRaw[]).map(mapper).filter((entry): entry is TResult => entry !== null)\n } catch (error) {\n logger.warn(`Failed to parse ${label}:`, error)\n return []\n }\n}\n","/**\n * Structural table types + drizzle (mssql) schema factory for the daily-report tables.\n * 日報テーブル群の構造的テーブル型と drizzle (mssql) スキーマファクトリ。\n *\n * 既存アプリは自前のモデル定義をそのまま `DailyReportTables` として注入できる (構造互換)。\n * 新規プロジェクトは `defineDailyReportSchema()` で同一構造のテーブル定義を生成できる。\n */\nimport { desc, sql } from \"drizzle-orm\"\nimport { type AnyMsSqlColumn, bigint, bit, date, datetime2, foreignKey, index, int, mssqlSchema, nvarchar, primaryKey } from \"drizzle-orm/mssql-core\"\n\n/** 注入する外部ユーザーテーブルの最小形 (id / display_name)。 */\nexport type DailyReportUserTable = { id: AnyMsSqlColumn; displayName: AnyMsSqlColumn }\n\n/** DailyReportHub テーブルの構造形。 */\nexport type DailyReportHubTable = {\n id: AnyMsSqlColumn\n sourceType: AnyMsSqlColumn\n sourceId: AnyMsSqlColumn\n sourceIdNum: AnyMsSqlColumn\n businessDate: AnyMsSqlColumn\n userId: AnyMsSqlColumn\n title: AnyMsSqlColumn\n summary: AnyMsSqlColumn\n createdAt: AnyMsSqlColumn\n createdBy: AnyMsSqlColumn\n updatedAt: AnyMsSqlColumn\n updatedBy: AnyMsSqlColumn\n deletedAt: AnyMsSqlColumn\n deletedBy: AnyMsSqlColumn\n}\n\n/** DailyReportInternal テーブルの構造形。 */\nexport type DailyReportInternalTable = {\n hubId: AnyMsSqlColumn\n body: AnyMsSqlColumn\n metadata: AnyMsSqlColumn\n createdAt: AnyMsSqlColumn\n createdBy: AnyMsSqlColumn\n updatedAt: AnyMsSqlColumn\n updatedBy: AnyMsSqlColumn\n}\n\n/** DailyReportComment テーブルの構造形。 */\nexport type DailyReportCommentTable = {\n id: AnyMsSqlColumn\n hubId: AnyMsSqlColumn\n userId: AnyMsSqlColumn\n body: AnyMsSqlColumn\n createdAt: AnyMsSqlColumn\n createdBy: AnyMsSqlColumn\n updatedAt: AnyMsSqlColumn\n updatedBy: AnyMsSqlColumn\n}\n\n/** DailyReportLabel テーブルの構造形。 */\nexport type DailyReportLabelTable = {\n id: AnyMsSqlColumn\n userId: AnyMsSqlColumn\n name: AnyMsSqlColumn\n color: AnyMsSqlColumn\n sortOrder: AnyMsSqlColumn\n createdAt: AnyMsSqlColumn\n createdBy: AnyMsSqlColumn\n updatedAt: AnyMsSqlColumn\n updatedBy: AnyMsSqlColumn\n}\n\n/** DailyReportHub_Label 中間テーブルの構造形。 */\nexport type DailyReportHubLabelTable = {\n hubId: AnyMsSqlColumn\n labelId: AnyMsSqlColumn\n createdAt: AnyMsSqlColumn\n createdBy: AnyMsSqlColumn\n}\n\n/** DailyReportUserStatus テーブルの構造形。 */\nexport type DailyReportUserStatusTable = {\n hubId: AnyMsSqlColumn\n userId: AnyMsSqlColumn\n isRead: AnyMsSqlColumn\n isStarred: AnyMsSqlColumn\n createdAt: AnyMsSqlColumn\n createdBy: AnyMsSqlColumn\n updatedAt: AnyMsSqlColumn\n updatedBy: AnyMsSqlColumn\n}\n\n/** サービスへ注入するテーブル一式 (アプリ既存モデルまたは本ファクトリ生成物)。 */\nexport type DailyReportTables = {\n hub: DailyReportHubTable\n internal: DailyReportInternalTable\n comment: DailyReportCommentTable\n label: DailyReportLabelTable\n hubLabel: DailyReportHubLabelTable\n userStatus: DailyReportUserStatusTable\n}\n\n/**\n * Generic factory: build the six daily-report tables under an arbitrary schema name.\n * 任意のスキーマ名の下に日報 6 テーブルを生成する汎用ファクトリ。\n *\n * 制約・索引名は `${schemaName}_<Table>_...` 規約で生成する。\n * ユーザーテーブルへの FK は注入された `userTable` を参照する。\n */\nexport function defineDailyReportSchema<S extends string>(schemaName: S, opts: { userTable: DailyReportUserTable }) {\n const s = mssqlSchema(schemaName)\n const users = opts.userTable\n\n const hub = s.table(\n \"DailyReportHub\",\n {\n id: bigint(\"id\", { mode: \"number\" }).identity().notNull(),\n sourceType: nvarchar(\"source_type\", { length: 20 }).notNull(),\n sourceId: nvarchar(\"source_id\", { length: 100 }).notNull(),\n sourceIdNum: bigint(\"source_id_num\", { mode: \"number\" }).generatedAlwaysAs(sql`TRY_CAST(source_id AS BIGINT)`),\n businessDate: date(\"business_date\"),\n userId: bigint(\"user_id\", { mode: \"number\" }),\n title: nvarchar(\"title\", { length: 200 }),\n summary: nvarchar(\"summary\", { length: \"max\" }),\n createdAt: datetime2(\"created_at\").notNull(),\n createdBy: nvarchar(\"created_by\", { length: 50 }).notNull(),\n updatedAt: datetime2(\"updated_at\").notNull(),\n updatedBy: nvarchar(\"updated_by\", { length: 50 }).notNull(),\n deletedAt: datetime2(\"deleted_at\"),\n deletedBy: nvarchar(\"deleted_by\", { length: 50 }),\n },\n (table) => [\n primaryKey({ name: `${schemaName}_DailyReportHub_pk`, columns: [table.id] }),\n foreignKey({\n name: `${schemaName}_DailyReportHub_user_id_fk`,\n columns: [table.userId],\n foreignColumns: [users.id],\n }),\n index(`${schemaName}_DailyReportHub_business_date_index`).on(table.businessDate),\n index(`${schemaName}_DailyReportHub_updated_at_index`).on(table.updatedAt),\n index(`${schemaName}_DailyReportHub_source_index`).on(table.sourceType, table.sourceId),\n index(`${schemaName}_DailyReportHub_user_id_index`).on(table.userId),\n index(`${schemaName}_DailyReportHub_business_date_id_index`).on(desc(table.businessDate), desc(table.id)),\n index(`${schemaName}_DailyReportHub_deleted_at_index`).on(table.deletedAt),\n ],\n )\n\n const internal = s.table(\n \"DailyReportInternal\",\n {\n hubId: bigint(\"hub_id\", { mode: \"number\" }).notNull(),\n body: nvarchar(\"body\", { length: \"max\" }),\n metadata: nvarchar(\"metadata\", { length: \"max\" }),\n createdAt: datetime2(\"created_at\").notNull(),\n createdBy: nvarchar(\"created_by\", { length: 50 }).notNull(),\n updatedAt: datetime2(\"updated_at\").notNull(),\n updatedBy: nvarchar(\"updated_by\", { length: 50 }).notNull(),\n },\n (table) => [\n primaryKey({ name: `${schemaName}_DailyReportInternal_pk`, columns: [table.hubId] }),\n foreignKey({\n name: `${schemaName}_DailyReportInternal_hub_id_fk`,\n columns: [table.hubId],\n foreignColumns: [hub.id],\n }),\n ],\n )\n\n const comment = s.table(\n \"DailyReportComment\",\n {\n id: bigint(\"id\", { mode: \"number\" }).identity().notNull(),\n hubId: bigint(\"hub_id\", { mode: \"number\" }).notNull(),\n userId: bigint(\"user_id\", { mode: \"number\" }).notNull(),\n body: nvarchar(\"body\", { length: \"max\" }).notNull(),\n createdAt: datetime2(\"created_at\").notNull(),\n createdBy: nvarchar(\"created_by\", { length: 50 }).notNull(),\n updatedAt: datetime2(\"updated_at\").notNull(),\n updatedBy: nvarchar(\"updated_by\", { length: 50 }).notNull(),\n },\n (table) => [\n primaryKey({ name: `${schemaName}_DailyReportComment_pk`, columns: [table.id] }),\n foreignKey({\n name: `${schemaName}_DailyReportComment_hub_id_fk`,\n columns: [table.hubId],\n foreignColumns: [hub.id],\n }),\n foreignKey({\n name: `${schemaName}_DailyReportComment_user_id_fk`,\n columns: [table.userId],\n foreignColumns: [users.id],\n }),\n index(`${schemaName}_DailyReportComment_hub_id_index`).on(table.hubId),\n ],\n )\n\n const label = s.table(\n \"DailyReportLabel\",\n {\n id: bigint(\"id\", { mode: \"number\" }).identity().notNull(),\n userId: bigint(\"user_id\", { mode: \"number\" }),\n name: nvarchar(\"name\", { length: 50 }).notNull(),\n color: nvarchar(\"color\", { length: 20 }),\n sortOrder: int(\"sort_order\"),\n createdAt: datetime2(\"created_at\").notNull(),\n createdBy: nvarchar(\"created_by\", { length: 50 }).notNull(),\n updatedAt: datetime2(\"updated_at\").notNull(),\n updatedBy: nvarchar(\"updated_by\", { length: 50 }).notNull(),\n },\n (table) => [\n primaryKey({ name: `${schemaName}_DailyReportLabel_pk`, columns: [table.id] }),\n foreignKey({\n name: `${schemaName}_DailyReportLabel_user_id_fk`,\n columns: [table.userId],\n foreignColumns: [users.id],\n }),\n ],\n )\n\n const hubLabel = s.table(\n \"DailyReportHub_Label\",\n {\n hubId: bigint(\"hub_id\", { mode: \"number\" }).notNull(),\n labelId: bigint(\"label_id\", { mode: \"number\" }).notNull(),\n createdAt: datetime2(\"created_at\").notNull(),\n createdBy: nvarchar(\"created_by\", { length: 50 }).notNull(),\n },\n (table) => [\n primaryKey({ name: `${schemaName}_DailyReportHub_Label_pk`, columns: [table.hubId, table.labelId] }),\n foreignKey({\n name: `${schemaName}_DailyReportHub_Label_hub_id_fk`,\n columns: [table.hubId],\n foreignColumns: [hub.id],\n }),\n foreignKey({\n name: `${schemaName}_DailyReportHub_Label_label_id_fk`,\n columns: [table.labelId],\n foreignColumns: [label.id],\n }),\n ],\n )\n\n const userStatus = s.table(\n \"DailyReportUserStatus\",\n {\n hubId: bigint(\"hub_id\", { mode: \"number\" }).notNull(),\n userId: bigint(\"user_id\", { mode: \"number\" }).notNull(),\n isRead: bit(\"is_read\").default(false).notNull(),\n isStarred: bit(\"is_starred\").default(false).notNull(),\n createdAt: datetime2(\"created_at\").notNull(),\n createdBy: nvarchar(\"created_by\", { length: 50 }).notNull(),\n updatedAt: datetime2(\"updated_at\").notNull(),\n updatedBy: nvarchar(\"updated_by\", { length: 50 }).notNull(),\n },\n (table) => [\n primaryKey({ name: `${schemaName}_DailyReportUserStatus_pk`, columns: [table.hubId, table.userId] }),\n foreignKey({\n name: `${schemaName}_DailyReportUserStatus_hub_id_fk`,\n columns: [table.hubId],\n foreignColumns: [hub.id],\n }),\n foreignKey({\n name: `${schemaName}_DailyReportUserStatus_user_id_fk`,\n columns: [table.userId],\n foreignColumns: [users.id],\n }),\n ],\n )\n\n return { hub, internal, comment, label, hubLabel, userStatus } satisfies DailyReportTables\n}\n"],"mappings":"ubAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,0BAAAE,GAAA,mBAAAC,GAAA,8BAAAC,GAAA,4BAAAC,GAAA,6BAAAC,GAAA,qBAAAC,GAAA,4BAAAC,GAAA,iBAAAC,GAAA,kBAAAC,GAAA,yBAAAC,EAAA,uBAAAC,KAAA,eAAAC,GAAAb,ICmBO,IAAMc,GAAoBC,IAAsC,CAKnE,MAAM,SAASC,EAAmC,CAC9C,GAAI,CACA,IAAMC,EAAS,MAAMF,GAAO,UAAU,EACtC,GAAI,CAACE,EAAQ,MAAO,GACpB,IAAMC,EAAM,MAAMD,EAAO,IAAID,CAAQ,EACrC,OAAOE,EAAM,OAAOA,CAAG,EAAI,CAC/B,MAAQ,CACJ,MAAO,EACX,CACJ,EAKA,MAAM,eAAeF,EAAiC,CAClD,GAAI,CACA,IAAMC,EAAS,MAAMF,GAAO,UAAU,EACtC,GAAI,CAACE,EAAQ,OACb,MAAMA,EAAO,KAAKD,CAAQ,CAC9B,MAAQ,CAER,CACJ,CACJ,GAQaG,GAAN,KAAqB,CAIxB,YACqBC,EACAC,EACnB,CAFmB,YAAAD,EACA,gBAAAC,EALrB,KAAiB,QAAU,IAAI,IAC/B,KAAiB,SAAW,IAAI,IAWhC,gBAAcC,GAA2B,CACrC,KAAK,QAAQ,OAAOA,CAAQ,EAC5B,KAAK,SAAS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O,OAAAF,CAAO,CAAC,EAE/DM,EAAY,IAAIC,GAAqB,CACvC,MAAOR,EAAO,MACd,UAAWK,EAAQ,UACnB,MAAAF,EACA,OAAQH,EAAO,MACnB,CAAC,EAEKS,EAAWC,GAA0B,CACvC,aAAcV,EAAO,aACrB,QAAAK,EACA,aAAcL,EAAO,aACrB,MAAOA,EAAO,MACd,UAAAO,EACA,UAAWF,EAAQ,UACnB,kBAAmBL,EAAO,kBAC1B,OAAQA,EAAO,MACnB,CAAC,EAED,MAAO,CAEH,QAAAK,EAEA,MAAAF,EAEA,OAAAF,EAEA,UAAAM,EAEA,UAAWF,EAAQ,UACnB,GAAGI,CACP,CACJ","names":["server_exports","__export","DailyReportSseReader","SqlResultCache","createDailyReportHandlers","createDailyReportServer","createDailyReportService","createEpochStore","defineDailyReportSchema","generateETag","isStreamIdLte","jsonResponseWithETag","transformJsonArray","__toCommonJS","createEpochStore","redis","epochKey","client","val","SqlResultCache","config","epochStore","cacheKey","opts","forceRefresh","snapshot","bucket","currentEpoch","r","shared","promise","records","expireAt","epoch","result","prefix","key","ISO_DATE_PATTERN","SLASH_DATE_PATTERN","zeroPad","value","normalizeFromDate","year","month","day","normalizeBusinessDateKey","trimmed","parsed","createLogger","level","prefix","impl","format","message","rest","import_zod","dailyReportInterviewerSchema","dailyReportCommentSchema","dailyReportLabelDefSchema","dailyReportCommentItemSchema","dailyReportDetailSchema","connectedMessageSchema","statusUpdateMessageSchema","commentAddMessageSchema","commentDeleteMessageSchema","reportCreateMessageSchema","reportUpdateMessageSchema","reportPublishMessageSchema","reportDeleteMessageSchema","dailyReportSseMessageSchema","import_node_crypto","generateETag","data","json","defaultLogger","createLogger","jsonResponseWithETag","request","cookie","payload","status","logger","etag","generateETag","ifNoneMatch","headers","import_node_events","isStreamIdLte","a","b","aMs","aSeq","bMs","bSeq","DailyReportSseReader","config","createLogger","onEntry","onError","resolve","err","results","stream","msg","parsed","msgType","reportHubId","jsonData","payload","init","createDailyReportHandlers","config","authenticate","service","encodeUserId","redis","sseReader","streamKey","loginRedirectPath","apiLogger","createLogger","sseLogger","indexLoader","request","user","cookie","headers","userId","hashedUserId","endpointHandlers","url","normalizedBusinessDate","normalizeBusinessDateKey","forceRefresh","jsonResponseWithETag","reports","dailyReportIds","param","parsedId","detail","params","sanitizedCookie","endpoint","handler","startTime","error","elapsed","err","formData","intent","reportHubIdRaw","reportHubId","businessDate","operationTimestamp","clientTempId","newReport","title","content","e","publishedReport","isStarredRaw","isStarred","updatedStatus","isReadRaw","isRead","newComment","safeComment","commentId","internalUserId","lastEventId","encoder","controllerRef","keepAliveInterval","unsubscribe","isCleaningUp","cleanup","processEntry","entryId","fields","raw","result","dailyReportSseMessageSchema","parsed","recipientRawUserId","sanitizedMessage","_","rest","stream","controller","lastProcessedId","entry","isStreamIdLte","client","latest","connectedPayload","sseMessage","catchUpEntries","import_drizzle_orm","cols","t","createDailyReportService","config","db","tables","users","resolveUserId","encodeUserId","redis","sqlResultCache","epochs","DailyReportHub","DailyReportInternal","DailyReportCommentModel","DailyReportLabel","DailyReportHub_Label","DailyReportUserStatus","externalSources","draftLabelName","logger","createLogger","DAILY_REPORT_IDS_CACHE_KEY","DAILY_REPORT_IDS_TTL_MS","DAILY_REPORT_IDS_EPOCH_KEY","DAILY_REPORT_BUSINESS_DATE_CACHE_PREFIX","DAILY_REPORT_BUSINESS_DATE_TTL_MS","DAILY_REPORT_DATE_EPOCH_PREFIX","DAILY_REPORT_DETAIL_EPOCH_PREFIX","DAILY_REPORT_SSE_STREAM_KEY","DAILY_REPORT_SSE_STREAM_MAXLEN","incrementRedisEpoch","key","publishToSseStream","message","callerName","client","publishStartMs","publishDurationMs","e","formatDateValue","value","pattern","dateValue","opts","maskAuditActor","externalSelections","out","adapter","applyExternalJoins","chain","c","mapHubRecord","row","currentUserId","hub","internal","content","interviewers","category","creationCategory","visitTimeFrom","visitTimeTo","customerName","employeeName","comments","a","externalRow","fields","labelsRaw","commentItemsRaw","l","fetchDailyReportIdsByUserId","userId","DraftLabelRelation","item","fetchDailyReportsByBusinessDate","normalizedBusinessDate","buildBusinessDateCacheKey","userIdCache","getUserIdByExternalId","externalId","getDailyReportIdsByExternalId","forceRefresh","snapshot","ttlMsOverride","cacheKey","getDailyReportsByBusinessDate","businessDate","normalizeBusinessDateKey","cachedDraftLabelId","getDraftLabelId","label","getDailyReportsByBusinessDateByExternalId","draftLabelId","rows","hubIds","r","allLabels","allComments","labelsMap","commentsMap","list","comment","hubId","getDailyReportDetailById","reportHubId","labels","labelsMapped","commentsMapped","getDailyReportDetailByIdByExternalId","options","setStarStatus","isStarred","clientTempId","existing","updatedStatus","normalizedDate","statusUpdateMessageSchema","setReadStatus","isRead","addComment","inserted","user","userName","commentItem","commentAddMessageSchema","findDailyReportCommentById","tx","commentId","deleteComment","commentDeleteMessageSchema","createDailyReport","result","sourceId","fullDetail","isDraft","reportCreateMessageSchema","findDailyReportHubById","updateDailyReportHub","data","updateDailyReportInternal","deleteDailyReportLabel","labelId","report","reportUpdateMessageSchema","reportPublishMessageSchema","reportDeleteMessageSchema","defaultLogger","createLogger","transformJsonArray","payload","label","mapper","logger","parsed","entry","error","import_drizzle_orm","import_mssql_core","defineDailyReportSchema","schemaName","opts","s","users","hub","table","internal","comment","label","hubLabel","userStatus","createDailyReportServer","config","epochs","createEpochStore","cache","SqlResultCache","service","createDailyReportService","sseReader","DailyReportSseReader","handlers","createDailyReportHandlers"]}