@aiquants/daily-report 0.20.0 → 0.21.0
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.
- package/README.md +229 -8
- package/dist/client.d.mts +201 -739
- package/dist/client.d.ts +201 -739
- package/dist/client.js +5 -6
- package/dist/client.mjs +5 -6
- package/dist/index.d.mts +5 -197
- package/dist/index.d.ts +5 -197
- package/dist/index.js +1 -2
- package/dist/index.mjs +1 -2
- package/dist/logger-D3krZrNK.d.mts +0 -14
- package/dist/logger-D3krZrNK.d.ts +0 -14
- package/dist/server.d.mts +114 -744
- package/dist/server.d.ts +114 -744
- package/dist/server.js +1 -2
- package/dist/server.mjs +1 -2
- package/dist/{sse-schema-ChSFm-4q.d.mts → sse-schema-DCxpdETM.d.mts} +1106 -1090
- package/dist/{sse-schema-BdUGThiz.d.ts → sse-schema-DoQw8_om.d.ts} +1106 -1090
- package/dist/types-CqgYQgbH.d.mts +0 -34
- package/dist/types-CqgYQgbH.d.ts +0 -34
- package/package.json +9 -10
- package/dist/client.js.map +0 -1
- package/dist/client.mjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/server.js.map +0 -1
- package/dist/server.mjs.map +0 -1
- package/src/client/components/business-day-thumb-overlay.tsx +0 -19
- package/src/client/components/daily-report-attachment-indicator.spec.tsx +0 -51
- package/src/client/components/daily-report-attachment-indicator.tsx +0 -45
- package/src/client/components/daily-report-attachment-list.spec.tsx +0 -94
- package/src/client/components/daily-report-attachment-list.tsx +0 -112
- package/src/client/components/daily-report-comment-item.tsx +0 -89
- package/src/client/components/daily-report-comment-section.tsx +0 -166
- package/src/client/components/daily-report-detail-list.tsx +0 -842
- package/src/client/components/daily-report-edit-form.tsx +0 -87
- package/src/client/components/daily-report-ids-stream-status.spec.tsx +0 -93
- package/src/client/components/daily-report-ids-stream-status.tsx +0 -67
- package/src/client/components/daily-report-list.tsx +0 -1232
- package/src/client/components/daily-report-page.spec.tsx +0 -119
- package/src/client/components/daily-report-page.tsx +0 -140
- package/src/client/components/daily-report-resize-panels.spec.tsx +0 -307
- package/src/client/components/daily-report-resolved-content.tsx +0 -207
- package/src/client/components/daily-report-scroll-restoration.spec.tsx +0 -422
- package/src/client/components/report-views.spec.tsx +0 -375
- package/src/client/components/unread-indicator.tsx +0 -13
- package/src/client/config-context.tsx +0 -184
- package/src/client/contexts/daily-report-action-context.spec.tsx +0 -433
- package/src/client/contexts/daily-report-action-context.tsx +0 -1147
- package/src/client/contexts/daily-report-error-context.spec.tsx +0 -66
- package/src/client/contexts/daily-report-error-context.tsx +0 -98
- package/src/client/hooks/use-animated-number.spec.ts +0 -103
- package/src/client/hooks/use-animated-number.ts +0 -69
- package/src/client/hooks/use-daily-report-comments.ts +0 -73
- package/src/client/hooks/use-daily-report-sse-connection.ts +0 -86
- package/src/client/hooks/use-daily-report.spec.ts +0 -546
- package/src/client/hooks/use-daily-report.ts +0 -549
- package/src/client/hooks/use-dynamic-viewport-height.ts +0 -127
- package/src/client/hooks/use-responsive-layout.spec.ts +0 -74
- package/src/client/hooks/use-responsive-layout.ts +0 -63
- package/src/client/route-helpers.spec.ts +0 -100
- package/src/client/route-helpers.ts +0 -61
- package/src/client/streaming/daily-report-ids-stream-client.spec.ts +0 -910
- package/src/client/streaming/daily-report-ids-stream-client.ts +0 -730
- package/src/client/streaming/daily-report-ids-stream-session.spec.ts +0 -401
- package/src/client/streaming/daily-report-ids-stream-session.ts +0 -319
- package/src/client/ui/button.tsx +0 -42
- package/src/client/ui/cn.ts +0 -14
- package/src/client/ui/input.tsx +0 -21
- package/src/client/ui/label.tsx +0 -16
- package/src/client/ui/switch.tsx +0 -19
- package/src/client/ui/tabs.tsx +0 -40
- package/src/client/ui/textarea.tsx +0 -19
- package/src/client/utils/constants.spec.ts +0 -96
- package/src/client/utils/constants.ts +0 -84
- package/src/client.ts +0 -28
- package/src/index.ts +0 -11
- package/src/lucide-icons.d.ts +0 -6
- package/src/server/authz.spec.ts +0 -57
- package/src/server/authz.ts +0 -99
- package/src/server/cache.spec.ts +0 -556
- package/src/server/cache.ts +0 -303
- package/src/server/etag.ts +0 -18
- package/src/server/external-source.ts +0 -60
- package/src/server/handlers.action.spec.ts +0 -44
- package/src/server/handlers.attachment.spec.ts +0 -470
- package/src/server/handlers.ids-stream.spec.ts +0 -618
- package/src/server/handlers.ts +0 -1638
- package/src/server/handlers.unauthorized-cookie.spec.ts +0 -187
- package/src/server/handlers.visibility.spec.ts +0 -774
- package/src/server/ports.ts +0 -222
- package/src/server/response.ts +0 -37
- package/src/server/schema.spec.ts +0 -30
- package/src/server/schema.ts +0 -344
- package/src/server/service.spec.ts +0 -1130
- package/src/server/service.ts +0 -2045
- package/src/server/sse-reader.spec.ts +0 -302
- package/src/server/sse-reader.ts +0 -267
- package/src/server/test-helpers/handlers-config.ts +0 -321
- package/src/server/transaction-retry.spec.ts +0 -63
- package/src/server/visibility.spec.ts +0 -403
- package/src/server/visibility.ts +0 -373
- package/src/server.spec.ts +0 -160
- package/src/server.ts +0 -131
- package/src/shared/business-date.spec.ts +0 -82
- package/src/shared/business-date.ts +0 -104
- package/src/shared/comment-adapter.spec.ts +0 -38
- package/src/shared/comment-adapter.ts +0 -80
- package/src/shared/ids-stream.spec.ts +0 -154
- package/src/shared/ids-stream.ts +0 -279
- package/src/shared/logger.ts +0 -47
- package/src/shared/sse-schema.spec.ts +0 -50
- package/src/shared/sse-schema.ts +0 -198
- package/src/shared/text-utils.spec.ts +0 -42
- package/src/shared/text-utils.ts +0 -65
- package/src/shared/types.ts +0 -109
- package/src/styles/standalone.entry.css +0 -51
|
@@ -1,1130 +0,0 @@
|
|
|
1
|
-
import type { SQL } from "drizzle-orm"
|
|
2
|
-
import { bigint, MsSqlDialect, mssqlSchema, nvarchar, primaryKey } from "drizzle-orm/mssql-core"
|
|
3
|
-
import { describe, expect, it, vi } from "vitest"
|
|
4
|
-
import { createEpochStore, SqlResultCache } from "./cache"
|
|
5
|
-
import { defineDailyReportSchema } from "./schema"
|
|
6
|
-
import { createDailyReportService, type DailyReportDb, type DailyReportHubRow, formatDateValue } from "./service"
|
|
7
|
-
import { buildVisibleSourceTypeCondition, DailyReportViewerScope } from "./visibility"
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Security regression tests for audit-actor masking in mapHubRecord.
|
|
11
|
-
* mapHubRecord の監査アクターマスク (生内部 ID 漏洩防止) のセキュリティ回帰テスト。
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
// 実テーブル (getColumns / eq / desc が実カラムを要求するため mock 不可)
|
|
15
|
-
const testUsers = mssqlSchema("test").table("Users", { id: bigint("id", { mode: "number" }).notNull(), displayName: nvarchar("display_name", { length: 100 }) }, (t) => [primaryKey({ columns: [t.id] })])
|
|
16
|
-
const tables = defineDailyReportSchema("test", { userTable: testUsers })
|
|
17
|
-
|
|
18
|
-
/** 本物の方言。`where` に渡された式を実際の SQL 文字列へ落として表明するために使う。 */
|
|
19
|
-
const dialect = new MsSqlDialect()
|
|
20
|
-
|
|
21
|
-
/** 1 本のクエリについてモックが記録した内容。 */
|
|
22
|
-
type RecordedQuery = {
|
|
23
|
-
/** `where` に渡された式を実 SQL へ落としたもの。未指定なら null。 */
|
|
24
|
-
whereSql: string | null
|
|
25
|
-
/**
|
|
26
|
-
* `where` の束縛値。
|
|
27
|
-
*
|
|
28
|
-
* SQL 文字列だけでは**認可の中身を検証できない**。drizzle は値をすべて `@parN` へ落とすため、
|
|
29
|
-
* 文字列は「どのカラムをどう結んだか」しか含まない。閲覧者 ID と添付 ID の取り違えは
|
|
30
|
-
* ここを見なければ 1 件も検出できない。
|
|
31
|
-
*/
|
|
32
|
-
whereParams: unknown[]
|
|
33
|
-
/** `leftJoin` された回数。 */
|
|
34
|
-
leftJoins: number
|
|
35
|
-
/** `leftJoin` の ON 条件に載った束縛値 (下書きラベル ID はここに来る)。 */
|
|
36
|
-
joinParams: unknown[]
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** `update(...).set(...).where(...)` について記録した内容。 */
|
|
40
|
-
type RecordedUpdate = {
|
|
41
|
-
/** `set` に渡された更新内容。 */
|
|
42
|
-
set: Record<string, unknown>
|
|
43
|
-
/** `where` の束縛値。 */
|
|
44
|
-
whereParams: unknown[]
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Minimal db mock that also records the SQL each query would emit.
|
|
49
|
-
* 各クエリが実際に生成する SQL を記録もする最小の db モック。
|
|
50
|
-
*
|
|
51
|
-
* チェーンは thenable にしてある。`.where()` で終わるクエリ (認可判定の
|
|
52
|
-
* `getAttachmentForUser` や `getDraftLabelId`) を `orderBy` 前提のモックで受けると
|
|
53
|
-
* チェーンオブジェクト自身が await の結果になり、分割代入が TypeError で落ちる。
|
|
54
|
-
* それを避けるためにモックを「どの段でも解決できる」形にしている。
|
|
55
|
-
*
|
|
56
|
-
* @param rows Rows every query resolves to. すべてのクエリが返す行。
|
|
57
|
-
* @returns The db mock and the per-query recordings. db モックとクエリごとの記録。
|
|
58
|
-
*/
|
|
59
|
-
const makeDb = (rows: unknown[], options: { selectQueue?: unknown[][] } = {}): { db: DailyReportDb; queries: RecordedQuery[]; updates: RecordedUpdate[] } => {
|
|
60
|
-
const queries: RecordedQuery[] = []
|
|
61
|
-
const updates: RecordedUpdate[] = []
|
|
62
|
-
// selectQueue があれば select 呼び出しごとに 1 要素ずつ消費する (枯れたら rows へフォールバック)。
|
|
63
|
-
// 複数 select が異なる結果を返す必要のあるフロー (draft 判定など) の検証に使う
|
|
64
|
-
const selectQueue = options.selectQueue ? [...options.selectQueue] : null
|
|
65
|
-
const select = () => {
|
|
66
|
-
const result = selectQueue && selectQueue.length > 0 ? (selectQueue.shift() as unknown[]) : rows
|
|
67
|
-
const recorded: RecordedQuery = { whereSql: null, whereParams: [], leftJoins: 0, joinParams: [] }
|
|
68
|
-
queries.push(recorded)
|
|
69
|
-
const chain: Record<string, unknown> = {
|
|
70
|
-
from: () => chain,
|
|
71
|
-
innerJoin: () => chain,
|
|
72
|
-
leftJoin: (_table: unknown, onExpr?: SQL) => {
|
|
73
|
-
recorded.leftJoins += 1
|
|
74
|
-
if (onExpr) recorded.joinParams.push(...dialect.sqlToQuery(onExpr).params)
|
|
75
|
-
return chain
|
|
76
|
-
},
|
|
77
|
-
where: (expr: SQL | undefined) => {
|
|
78
|
-
const query = expr ? dialect.sqlToQuery(expr) : null
|
|
79
|
-
recorded.whereSql = query?.sql ?? null
|
|
80
|
-
recorded.whereParams = query?.params ?? []
|
|
81
|
-
return chain
|
|
82
|
-
},
|
|
83
|
-
top: () => chain,
|
|
84
|
-
orderBy: () => Promise.resolve(result),
|
|
85
|
-
// `.where()` / `.orderBy()` のどちらで終わっても await できるようにする。
|
|
86
|
-
// thenable であること自体が目的なので、この規則はここでは意図的に外す
|
|
87
|
-
// biome-ignore lint/suspicious/noThenProperty: 意図的な thenable (クエリビルダの終端を模擬する)
|
|
88
|
-
then: (resolve: (value: unknown) => unknown) => resolve(result),
|
|
89
|
-
}
|
|
90
|
-
return chain
|
|
91
|
-
}
|
|
92
|
-
const update = () => {
|
|
93
|
-
const recorded: RecordedUpdate = { set: {}, whereParams: [] }
|
|
94
|
-
const chain: Record<string, unknown> = {
|
|
95
|
-
set: (values: Record<string, unknown>) => {
|
|
96
|
-
recorded.set = values
|
|
97
|
-
return chain
|
|
98
|
-
},
|
|
99
|
-
where: (expr: SQL | undefined) => {
|
|
100
|
-
recorded.whereParams = expr ? dialect.sqlToQuery(expr).params : []
|
|
101
|
-
updates.push(recorded)
|
|
102
|
-
return Promise.resolve({ rowsAffected: [1] })
|
|
103
|
-
},
|
|
104
|
-
// `.output().where()` 形 (setStarStatus / setReadStatus の更新経路) も受ける。
|
|
105
|
-
// 更新後の行が必要なため、set された値をそのままエコーして返す
|
|
106
|
-
output: () => ({
|
|
107
|
-
where: (expr: SQL | undefined) => {
|
|
108
|
-
recorded.whereParams = expr ? dialect.sqlToQuery(expr).params : []
|
|
109
|
-
updates.push(recorded)
|
|
110
|
-
return Promise.resolve([{ hubId: 1, userId: 8, isRead: false, isStarred: false, ...recorded.set }])
|
|
111
|
-
},
|
|
112
|
-
}),
|
|
113
|
-
}
|
|
114
|
-
return chain
|
|
115
|
-
}
|
|
116
|
-
// INSERT: values をそのまま id 付きでエコーする (addComment の inserted 行を模擬)
|
|
117
|
-
const insert = () => {
|
|
118
|
-
const chain: Record<string, unknown> = {
|
|
119
|
-
output: () => chain,
|
|
120
|
-
values: (values: Record<string, unknown>) => Promise.resolve([{ id: 501, ...values }]),
|
|
121
|
-
}
|
|
122
|
-
return chain
|
|
123
|
-
}
|
|
124
|
-
// DELETE: 記録のみ (deleteComment 用)
|
|
125
|
-
const del = () => ({ where: () => Promise.resolve({ rowsAffected: [1] }) })
|
|
126
|
-
// TRANSACTION: 同じモックをそのまま tx として渡す (createDailyReport 等の検証用)。
|
|
127
|
-
// ロールバックは模擬しない (本モックの目的は発行クエリとキャッシュ挙動の観測)
|
|
128
|
-
const db: DailyReportDb = { select, update, insert, delete: del, transaction: (fn: (tx: DailyReportDb) => Promise<unknown>) => fn(db) } as unknown as DailyReportDb
|
|
129
|
-
return { db, queries, updates }
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const baseHub = (over: Partial<DailyReportHubRow>): DailyReportHubRow => ({
|
|
133
|
-
id: 1,
|
|
134
|
-
sourceType: "Internal",
|
|
135
|
-
sourceId: "1",
|
|
136
|
-
sourceIdNum: 1,
|
|
137
|
-
businessDate: "2099-01-05",
|
|
138
|
-
userId: 8,
|
|
139
|
-
title: "t",
|
|
140
|
-
summary: "s",
|
|
141
|
-
createdAt: "2099-01-05 00:00:00",
|
|
142
|
-
createdBy: "8",
|
|
143
|
-
updatedAt: "2099-01-05 00:00:00",
|
|
144
|
-
updatedBy: "8",
|
|
145
|
-
deletedAt: null,
|
|
146
|
-
deletedBy: null,
|
|
147
|
-
...over,
|
|
148
|
-
})
|
|
149
|
-
|
|
150
|
-
/** テストが「絞り込みなし」を意図していることを 1 箇所で表明する束縛。 */
|
|
151
|
-
const UNRESTRICTED_SCOPE = DailyReportViewerScope.unrestricted("unit test: no viewer restriction under test")
|
|
152
|
-
|
|
153
|
-
const makeService = (rows: unknown[], withAttachmentCodec = false, options: { selectQueue?: unknown[][]; streamKey?: string } = {}) => {
|
|
154
|
-
const epochs = createEpochStore(undefined)
|
|
155
|
-
const cache = new SqlResultCache({ defaultTtlMs: 60_000 }, epochs)
|
|
156
|
-
const { db, queries, updates } = makeDb(rows, { selectQueue: options.selectQueue })
|
|
157
|
-
// SSE publish (redis xAdd) の捕捉。宛先フィルタ (recipientRawUserId) の検証に使う
|
|
158
|
-
const sseMessages: Record<string, unknown>[] = []
|
|
159
|
-
const redis = {
|
|
160
|
-
getClient: async () => ({
|
|
161
|
-
xAdd: async (_key: string, _id: string, fields: { data: string }) => {
|
|
162
|
-
sseMessages.push(JSON.parse(fields.data) as Record<string, unknown>)
|
|
163
|
-
return "1-1"
|
|
164
|
-
},
|
|
165
|
-
}),
|
|
166
|
-
}
|
|
167
|
-
const service = createDailyReportService({
|
|
168
|
-
db,
|
|
169
|
-
tables,
|
|
170
|
-
userTable: testUsers,
|
|
171
|
-
resolveUserId: async () => 8,
|
|
172
|
-
encodeUserId: (id) => `ENC${id}`, // テスト用の識別可能な難読化
|
|
173
|
-
cache,
|
|
174
|
-
epochs,
|
|
175
|
-
redis: redis as unknown as Parameters<typeof createDailyReportService>[0]["redis"],
|
|
176
|
-
draftLabelName: "draft", // 必須注入 (ドラフト可視性フィルタ用のラベル名。テストは中立値で十分)
|
|
177
|
-
...(options.streamKey !== undefined ? { streamKey: options.streamKey } : {}),
|
|
178
|
-
// 既定では未注入のまま。既存テストが縮退動作 (添付は常に空) で通ることも同時に確認する。
|
|
179
|
-
// ユーザー ID 用 (`ENC`) とは別の接頭辞にして ID 空間の分離を表現する。
|
|
180
|
-
...(withAttachmentCodec ? { attachmentIdCodec: { encode: (id: number) => `ATT${id}`, decode: (t: string) => (t.startsWith("ATT") ? Number(t.slice(3)) : null) } } : {}),
|
|
181
|
-
})
|
|
182
|
-
return Object.assign(service, { __queries: queries, __updates: updates, __sse: sseMessages, __epochs: epochs })
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
describe("mapHubRecord audit-actor masking (security)", () => {
|
|
186
|
-
it("数値の updatedBy / createdBy (= 生内部 ID) は encodeUserId で難読化される", async () => {
|
|
187
|
-
const svc = makeService([{ hub: baseHub({ createdBy: "8", updatedBy: "8" }), internal: null, creatorName: null }])
|
|
188
|
-
const [r] = await svc.getDailyReportsByBusinessDate(UNRESTRICTED_SCOPE, "2099-01-05", { forceRefresh: true })
|
|
189
|
-
// 生 ID "8" がそのまま出ないこと (漏洩防止の核心)
|
|
190
|
-
expect(r.updatedBy).toBe("ENC8")
|
|
191
|
-
expect(r.updatedBy).not.toBe("8")
|
|
192
|
-
expect(r.author).toBe("ENC8") // creatorName(null) → createdBy をマスク
|
|
193
|
-
expect(r.employeeName).toBe("ENC8")
|
|
194
|
-
// userId フィールドは従来どおり難読化
|
|
195
|
-
expect(r.userId).toBe("ENC8")
|
|
196
|
-
})
|
|
197
|
-
|
|
198
|
-
it("表示名 (creatorName) がある場合はマスクせず表示名を優先する", async () => {
|
|
199
|
-
const svc = makeService([{ hub: baseHub({ createdBy: "8", updatedBy: "8" }), internal: null, creatorName: "山田太郎" }])
|
|
200
|
-
const [r] = await svc.getDailyReportsByBusinessDate(UNRESTRICTED_SCOPE, "2099-01-05", { forceRefresh: true })
|
|
201
|
-
expect(r.author).toBe("山田太郎")
|
|
202
|
-
expect(r.employeeName).toBe("山田太郎")
|
|
203
|
-
// updatedBy は表示名解決を持たないため常にマスク
|
|
204
|
-
expect(r.updatedBy).toBe("ENC8")
|
|
205
|
-
})
|
|
206
|
-
|
|
207
|
-
it("非数値の監査値 (レガシー氏名/システム文字列) はそのまま通す", async () => {
|
|
208
|
-
const svc = makeService([{ hub: baseHub({ createdBy: "system-import", updatedBy: "batch" }), internal: null, creatorName: null }])
|
|
209
|
-
const [r] = await svc.getDailyReportsByBusinessDate(UNRESTRICTED_SCOPE, "2099-01-05", { forceRefresh: true })
|
|
210
|
-
expect(r.author).toBe("system-import")
|
|
211
|
-
expect(r.updatedBy).toBe("batch")
|
|
212
|
-
})
|
|
213
|
-
|
|
214
|
-
it("空 / null の監査値は null になる (生値の漏れなし)", async () => {
|
|
215
|
-
const svc = makeService([{ hub: baseHub({ createdBy: "", updatedBy: "" }), internal: null, creatorName: null }])
|
|
216
|
-
const [r] = await svc.getDailyReportsByBusinessDate(UNRESTRICTED_SCOPE, "2099-01-05", { forceRefresh: true })
|
|
217
|
-
expect(r.updatedBy).toBeNull()
|
|
218
|
-
expect(r.author).toBe("") // author は非 null 契約のため空文字
|
|
219
|
-
})
|
|
220
|
-
})
|
|
221
|
-
|
|
222
|
-
describe("添付ファイルの一括取得", () => {
|
|
223
|
-
it("コーデック未注入なら空マップを返す (既定の縮退動作)", async () => {
|
|
224
|
-
const svc = makeService([])
|
|
225
|
-
const map = await svc.getAttachmentsByHubIds([1, 2])
|
|
226
|
-
expect(map.size).toBe(0)
|
|
227
|
-
})
|
|
228
|
-
|
|
229
|
-
it("hubIds が空なら DB を叩かずに空マップを返す", async () => {
|
|
230
|
-
const svc = makeService([], true)
|
|
231
|
-
const map = await svc.getAttachmentsByHubIds([])
|
|
232
|
-
expect(map.size).toBe(0)
|
|
233
|
-
})
|
|
234
|
-
|
|
235
|
-
it("hub ID ごとにグルーピングし、内部数値 ID を難読化トークンへ変換する", async () => {
|
|
236
|
-
const rows = [
|
|
237
|
-
{ id: 11, hubId: 1, fileName: "a.png", fileType: "image/png", fileSize: 10, createdAt: "2099-01-05 00:00:00", objectCheckedAt: null, objectMissingAt: null },
|
|
238
|
-
{ id: 12, hubId: 1, fileName: "b.pdf", fileType: null, fileSize: null, createdAt: "2099-01-05 00:00:01", objectCheckedAt: "2099-01-06 00:00:00", objectMissingAt: null },
|
|
239
|
-
{ id: 13, hubId: 2, fileName: "c.txt", fileType: "text/plain", fileSize: 0, createdAt: "2099-01-05 00:00:02", objectCheckedAt: "2099-01-06 00:00:00", objectMissingAt: "2099-01-06 00:00:00" },
|
|
240
|
-
]
|
|
241
|
-
const svc = makeService(rows, true)
|
|
242
|
-
const map = await svc.getAttachmentsByHubIds([1, 2])
|
|
243
|
-
|
|
244
|
-
expect(map.get(1)).toHaveLength(2)
|
|
245
|
-
expect(map.get(2)).toHaveLength(1)
|
|
246
|
-
// 生の内部 ID が出ないこと。ユーザー ID 用の接頭辞とも異なること
|
|
247
|
-
expect(map.get(1)?.[0].id).toBe("ATT11")
|
|
248
|
-
expect(map.get(1)?.[0].id).not.toBe("11")
|
|
249
|
-
expect(map.get(1)?.[0].id.startsWith("ENC")).toBe(false)
|
|
250
|
-
})
|
|
251
|
-
|
|
252
|
-
it("実体状態を三値へ導出する (未検証 / 実在 / 消失)", async () => {
|
|
253
|
-
const rows = [
|
|
254
|
-
{ id: 1, hubId: 1, fileName: "unknown.bin", fileType: null, fileSize: null, createdAt: null, objectCheckedAt: null, objectMissingAt: null },
|
|
255
|
-
{ id: 2, hubId: 1, fileName: "present.bin", fileType: null, fileSize: null, createdAt: null, objectCheckedAt: "2099-01-06 00:00:00", objectMissingAt: null },
|
|
256
|
-
{ id: 3, hubId: 1, fileName: "absent.bin", fileType: null, fileSize: null, createdAt: null, objectCheckedAt: "2099-01-06 00:00:00", objectMissingAt: "2099-01-06 00:00:00" },
|
|
257
|
-
]
|
|
258
|
-
const svc = makeService(rows, true)
|
|
259
|
-
const list = (await svc.getAttachmentsByHubIds([1])).get(1) ?? []
|
|
260
|
-
expect(list.map((a) => a.state)).toEqual(["unknown", "present", "absent"])
|
|
261
|
-
})
|
|
262
|
-
|
|
263
|
-
it("サイズ 0 と サイズ不明 (null) を区別する", async () => {
|
|
264
|
-
const rows = [
|
|
265
|
-
{ id: 1, hubId: 1, fileName: "empty.bin", fileType: null, fileSize: 0, createdAt: null, objectCheckedAt: null, objectMissingAt: null },
|
|
266
|
-
{ id: 2, hubId: 1, fileName: "unsized.bin", fileType: null, fileSize: null, createdAt: null, objectCheckedAt: null, objectMissingAt: null },
|
|
267
|
-
]
|
|
268
|
-
const svc = makeService(rows, true)
|
|
269
|
-
const list = (await svc.getAttachmentsByHubIds([1])).get(1) ?? []
|
|
270
|
-
expect(list[0].fileSize).toBe(0)
|
|
271
|
-
expect(list[1].fileSize).toBeNull()
|
|
272
|
-
})
|
|
273
|
-
|
|
274
|
-
it("空文字の fileType を null へ正規化する (取込元が欠損を空文字で表現する場合)", async () => {
|
|
275
|
-
const rows = [{ id: 1, hubId: 1, fileName: "x.bin", fileType: "", fileSize: null, createdAt: null, objectCheckedAt: null, objectMissingAt: null }]
|
|
276
|
-
const svc = makeService(rows, true)
|
|
277
|
-
expect((await svc.getAttachmentsByHubIds([1])).get(1)?.[0].fileType).toBeNull()
|
|
278
|
-
})
|
|
279
|
-
})
|
|
280
|
-
|
|
281
|
-
describe("添付ファイルの認可付き取得", () => {
|
|
282
|
-
it("添付テーブル未注入なら null を返す", async () => {
|
|
283
|
-
const epochs = createEpochStore(undefined)
|
|
284
|
-
const cache = new SqlResultCache({ defaultTtlMs: 60_000 }, epochs)
|
|
285
|
-
const { attachment: _omitted, ...tablesWithoutAttachment } = tables
|
|
286
|
-
const svc = createDailyReportService({
|
|
287
|
-
db: makeDb([]).db,
|
|
288
|
-
tables: tablesWithoutAttachment,
|
|
289
|
-
userTable: testUsers,
|
|
290
|
-
resolveUserId: async () => 8,
|
|
291
|
-
encodeUserId: (id) => `ENC${id}`,
|
|
292
|
-
cache,
|
|
293
|
-
epochs,
|
|
294
|
-
draftLabelName: "draft",
|
|
295
|
-
})
|
|
296
|
-
expect(await svc.getAttachmentForUser(UNRESTRICTED_SCOPE, 1, 8)).toBeNull()
|
|
297
|
-
})
|
|
298
|
-
|
|
299
|
-
it("認可述語が閲覧者の所有と下書き非該当を OR で結び、論理削除も除外する", async () => {
|
|
300
|
-
// これがこの機能の唯一の認可境界。述語そのものを SQL 文字列として固定する
|
|
301
|
-
// (モックは行を絞れないので、生成される WHERE 句を直接表明するしかない)
|
|
302
|
-
const svc = makeService([{ fileName: "a.png", filePath: "gcs://b/a.png", fileType: "image/png", fileSize: 1 }])
|
|
303
|
-
await svc.getAttachmentForUser(UNRESTRICTED_SCOPE, 11, 8)
|
|
304
|
-
|
|
305
|
-
// 最後のクエリが添付の認可判定 (直前は下書きラベルの解決)
|
|
306
|
-
const recorded = svc.__queries.at(-1)
|
|
307
|
-
const where = recorded?.whereSql ?? ""
|
|
308
|
-
expect(where).toContain("[DailyReportAttachment].[id]")
|
|
309
|
-
expect(where).toContain("[deleted_at] is null")
|
|
310
|
-
expect(where).toContain("[user_id] = ")
|
|
311
|
-
expect(where).toContain(" or ")
|
|
312
|
-
expect(where).toContain("[draft_label].[hub_id] is null")
|
|
313
|
-
// ❗ SQL 文字列だけでは足りない。値はすべて @parN へ落ちるため、
|
|
314
|
-
// 「添付 ID の位置に閲覧者 ID を渡す」ような取り違えは束縛値を見ないと検出できない
|
|
315
|
-
expect(recorded?.whereParams).toEqual([11, 8])
|
|
316
|
-
})
|
|
317
|
-
|
|
318
|
-
it("認可判定の束縛値が入れ替わっていないこと (添付 ID と閲覧者 ID)", async () => {
|
|
319
|
-
const svc = makeService([])
|
|
320
|
-
await svc.getAttachmentForUser(UNRESTRICTED_SCOPE, 777, 42)
|
|
321
|
-
expect(svc.__queries.at(-1)?.whereParams).toEqual([777, 42])
|
|
322
|
-
})
|
|
323
|
-
|
|
324
|
-
it("営業日一覧・詳細取得・添付取得の 3 経路が同一の可視性述語を持つ", async () => {
|
|
325
|
-
// 1 経路だけ緩いと、緩い経路がメタデータ (件名・添付名・トークン) を渡してしまう。
|
|
326
|
-
// 「所有者本人」または「下書きラベルが付いていない」の OR を 3 経路すべてで固定する
|
|
327
|
-
const draftPredicate = (sql: string): boolean => /\[user_id\] = @par\d+\) or \(\(\[draft_label\]\.\[hub_id\] is null\)/.test(sql)
|
|
328
|
-
|
|
329
|
-
const byDate = makeService([])
|
|
330
|
-
await byDate.getDailyReportsByBusinessDateByExternalId(UNRESTRICTED_SCOPE, "2099-01-05", "ext", { forceRefresh: true })
|
|
331
|
-
expect(byDate.__queries.some((q) => q.whereSql !== null && draftPredicate(q.whereSql))).toBe(true)
|
|
332
|
-
|
|
333
|
-
const byId = makeService([])
|
|
334
|
-
await byId.getDailyReportDetailById(UNRESTRICTED_SCOPE, 1, 8, { forceRefresh: true })
|
|
335
|
-
expect(byId.__queries.some((q) => q.whereSql !== null && draftPredicate(q.whereSql))).toBe(true)
|
|
336
|
-
|
|
337
|
-
const byAttachment = makeService([])
|
|
338
|
-
await byAttachment.getAttachmentForUser(UNRESTRICTED_SCOPE, 1, 8)
|
|
339
|
-
expect(byAttachment.__queries.some((q) => q.whereSql !== null && draftPredicate(q.whereSql))).toBe(true)
|
|
340
|
-
})
|
|
341
|
-
|
|
342
|
-
it("ID 一覧経路だけは `user_id IS NULL` を追加で許す (意図的な差分)", async () => {
|
|
343
|
-
// 4 番目の経路。取込元が投稿者を持たない日報 (user_id IS NULL) を一覧から消さないための
|
|
344
|
-
// 意図的な緩和であり、返すのは ID・営業日・ソース種別だけで本文も添付も含まない。
|
|
345
|
-
// 「3 経路と同一」ではないことを明示的に固定し、無自覚な差分と区別する
|
|
346
|
-
const byIds = makeService([])
|
|
347
|
-
await byIds.getDailyReportIdsByExternalId(UNRESTRICTED_SCOPE, "ext", { forceRefresh: true })
|
|
348
|
-
const idsWhere = byIds.__queries.map((q) => q.whereSql ?? "").find((sql) => sql.includes("[draft_label].[hub_id] is null"))
|
|
349
|
-
expect(idsWhere).toBeDefined()
|
|
350
|
-
expect(idsWhere).toContain("[user_id] is null")
|
|
351
|
-
})
|
|
352
|
-
|
|
353
|
-
it("下書きラベルは複数解決し、可視性の結合が 2 つ目以降も対象にする", async () => {
|
|
354
|
-
// `draftLabelNames` には取込元ごとの下書き名を複数注入できる。1 個の ID でしか結合しないと
|
|
355
|
-
// 2 つ目の下書きラベルが付いた日報が誰にでも可視になる
|
|
356
|
-
const svc = makeService([{ id: 11 }, { id: 22 }])
|
|
357
|
-
await svc.getAttachmentForUser(UNRESTRICTED_SCOPE, 1, 8)
|
|
358
|
-
// 結合条件は where ではなく leftJoin の ON 側に載る
|
|
359
|
-
const joinParams = svc.__queries.flatMap((q) => q.joinParams)
|
|
360
|
-
expect(joinParams).toContain(11)
|
|
361
|
-
expect(joinParams).toContain(22)
|
|
362
|
-
})
|
|
363
|
-
})
|
|
364
|
-
|
|
365
|
-
describe("実体存在の記録 (三値の書き込み側)", () => {
|
|
366
|
-
it("markAttachmentMissing は消失時刻と検証時刻の両方を立てる", async () => {
|
|
367
|
-
const svc = makeService([])
|
|
368
|
-
await svc.markAttachmentMissing(77)
|
|
369
|
-
const [update] = svc.__updates
|
|
370
|
-
expect(update?.whereParams).toEqual([77])
|
|
371
|
-
// objectMissingAt を落とすと三値が absent にならず、消失が永久に検知されない
|
|
372
|
-
expect(update?.set.objectMissingAt).toBeInstanceOf(Date)
|
|
373
|
-
expect(update?.set.objectCheckedAt).toBeInstanceOf(Date)
|
|
374
|
-
expect(update?.set.updatedAt).toBeInstanceOf(Date)
|
|
375
|
-
})
|
|
376
|
-
|
|
377
|
-
it("markAttachmentPresent は消失時刻を NULL へ戻す (自己回復)", async () => {
|
|
378
|
-
const svc = makeService([])
|
|
379
|
-
await svc.markAttachmentPresent(77)
|
|
380
|
-
const [update] = svc.__updates
|
|
381
|
-
expect(update?.whereParams).toEqual([77])
|
|
382
|
-
// ここが null でないと absent が解除されず、UI からリンクが戻らない
|
|
383
|
-
expect(update?.set.objectMissingAt).toBeNull()
|
|
384
|
-
expect(update?.set.objectCheckedAt).toBeInstanceOf(Date)
|
|
385
|
-
})
|
|
386
|
-
|
|
387
|
-
it("添付テーブル未注入なら書き込みを試みない", async () => {
|
|
388
|
-
const epochs = createEpochStore(undefined)
|
|
389
|
-
const { attachment: _omitted, ...tablesWithoutAttachment } = tables
|
|
390
|
-
const { db, updates } = makeDb([])
|
|
391
|
-
const svc = createDailyReportService({
|
|
392
|
-
db,
|
|
393
|
-
tables: tablesWithoutAttachment,
|
|
394
|
-
userTable: testUsers,
|
|
395
|
-
resolveUserId: async () => 8,
|
|
396
|
-
encodeUserId: (id) => `ENC${id}`,
|
|
397
|
-
cache: new SqlResultCache({ defaultTtlMs: 60_000 }, epochs),
|
|
398
|
-
epochs,
|
|
399
|
-
draftLabelName: "draft",
|
|
400
|
-
})
|
|
401
|
-
await svc.markAttachmentMissing(1)
|
|
402
|
-
await svc.markAttachmentPresent(1)
|
|
403
|
-
expect(updates).toHaveLength(0)
|
|
404
|
-
})
|
|
405
|
-
})
|
|
406
|
-
|
|
407
|
-
describe("コメント操作の整合性チェック", () => {
|
|
408
|
-
it("addComment は存在しない日報に対して Not Found を投げる (孤児コメントを作らない)", async () => {
|
|
409
|
-
// hub 取得が空 = 存在しない日報。以前は hub 未取得でもフォールスルーして INSERT していた
|
|
410
|
-
const svc = makeService([])
|
|
411
|
-
await expect(svc.addComment(UNRESTRICTED_SCOPE, 8, 999, "本文", "2099-01-05", "tmp")).rejects.toThrow("Not Found")
|
|
412
|
-
})
|
|
413
|
-
|
|
414
|
-
it("addComment は論理削除済みの日報を拒否する", async () => {
|
|
415
|
-
const svc = makeService([{ sourceType: "Internal", deletedAt: "2099-01-06 00:00:00", userId: 8 }])
|
|
416
|
-
await expect(svc.addComment(UNRESTRICTED_SCOPE, 8, 1, "本文", "2099-01-05", "tmp")).rejects.toThrow("Not Found")
|
|
417
|
-
})
|
|
418
|
-
|
|
419
|
-
it("deleteComment は reportHubId がコメントの実所属と一致しないと Not Found を投げる", async () => {
|
|
420
|
-
// コメントは hubId=100 に属するのに、呼び出しは reportHubId=999 を渡している。
|
|
421
|
-
// 不一致のまま進むと無関係な日報のキャッシュ無効化と SSE 配信を起こすため拒否する
|
|
422
|
-
const svc = makeService([{ id: 5, hubId: 100, userId: 8, body: "x", createdAt: "2099-01-05 00:00:00", createdBy: "8", updatedAt: "2099-01-05 00:00:00", updatedBy: "8" }])
|
|
423
|
-
await expect(svc.deleteComment(UNRESTRICTED_SCOPE, 8, 999, 5, "2099-01-05", "tmp")).rejects.toThrow("Not Found")
|
|
424
|
-
})
|
|
425
|
-
|
|
426
|
-
it("addComment: 公開済み日報のコメントは全員配信 (recipientRawUserId 無し)", async () => {
|
|
427
|
-
const svc = makeService([], false, {
|
|
428
|
-
selectQueue: [
|
|
429
|
-
[{ sourceType: "Internal", deletedAt: null, userId: 8 }], // hub 取得
|
|
430
|
-
[{ id: 10 }], // getDraftLabelJoinIds (下書きラベル定義)
|
|
431
|
-
[{ sourceType: "Internal", deletedAt: null }], // 共通ゲート (assertHubMutable) の可視性判定
|
|
432
|
-
[], // 下書き関連 (該当なし = 公開済み)
|
|
433
|
-
[{ displayName: "山田" }], // コメント投稿者名
|
|
434
|
-
],
|
|
435
|
-
})
|
|
436
|
-
await svc.addComment(UNRESTRICTED_SCOPE, 8, 1, "本文", "2099-01-05", "tmp")
|
|
437
|
-
const sse = (svc as unknown as { __sse: Record<string, unknown>[] }).__sse
|
|
438
|
-
const add = sse.find((m) => m.type === "comment-add")
|
|
439
|
-
expect(add).toBeDefined()
|
|
440
|
-
expect(add?.recipientRawUserId).toBeUndefined()
|
|
441
|
-
})
|
|
442
|
-
|
|
443
|
-
it("addComment: 下書き日報のコメントは所有者だけに配信 (本文の全員配信を防ぐ)", async () => {
|
|
444
|
-
const svc = makeService([], false, {
|
|
445
|
-
selectQueue: [
|
|
446
|
-
[{ sourceType: "Internal", deletedAt: null, userId: 8 }], // hub (所有者 8)
|
|
447
|
-
[{ id: 10 }], // getDraftLabelJoinIds
|
|
448
|
-
[{ sourceType: "Internal", deletedAt: null }], // 共通ゲート (所有者本人なので通る)
|
|
449
|
-
[{ hubId: 1 }], // 下書き関連あり = 下書き
|
|
450
|
-
[{ displayName: "山田" }], // 投稿者名
|
|
451
|
-
],
|
|
452
|
-
})
|
|
453
|
-
await svc.addComment(UNRESTRICTED_SCOPE, 8, 1, "秘密の下書きコメント", "2099-01-05", "tmp")
|
|
454
|
-
const sse = (svc as unknown as { __sse: Record<string, unknown>[] }).__sse
|
|
455
|
-
const add = sse.find((m) => m.type === "comment-add")
|
|
456
|
-
expect(add?.recipientRawUserId).toBe(8)
|
|
457
|
-
})
|
|
458
|
-
})
|
|
459
|
-
|
|
460
|
-
describe("formatDateValue (Intl-free rewrite equivalence)", () => {
|
|
461
|
-
/**
|
|
462
|
-
* Reference implementation: the pre-fix Intl-based formatter, copied verbatim.
|
|
463
|
-
* 参照実装: 修正前の Intl ベース整形処理の逐語コピー。
|
|
464
|
-
*
|
|
465
|
-
* 等価性テストの oracle として使う。呼び出しごとに Intl.DateTimeFormat を生成するため
|
|
466
|
-
* 本体からは根絶済 (227k 行 map で 15〜20 秒の CPU 洪水になる)。テスト内 oracle 用途に限る。
|
|
467
|
-
*/
|
|
468
|
-
const referenceFormatDateValue = (value: Date | string | null | undefined, pattern: "YYYY-MM-DD HH:mm:ss" | "YYYY-MM-DD"): string | null => {
|
|
469
|
-
if (!value) {
|
|
470
|
-
return null
|
|
471
|
-
}
|
|
472
|
-
const dateValue = value instanceof Date ? value : new Date(value)
|
|
473
|
-
if (Number.isNaN(dateValue.getTime())) {
|
|
474
|
-
return typeof value === "string" ? value : null
|
|
475
|
-
}
|
|
476
|
-
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" }
|
|
477
|
-
const formatted = pattern === "YYYY-MM-DD HH:mm:ss" ? dateValue.toLocaleString("ja-JP", opts) : dateValue.toLocaleDateString("ja-JP", opts)
|
|
478
|
-
return formatted.replace(/\//g, "-")
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
/** 再現可能な乱数列 (LCG)。テストを決定的にするため Math.random は使わない。 */
|
|
482
|
-
const makeLcg = (seed: number) => {
|
|
483
|
-
let state = seed >>> 0
|
|
484
|
-
return () => {
|
|
485
|
-
state = (state * 1664525 + 1013904223) >>> 0
|
|
486
|
-
return state / 0x1_0000_0000
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
it("ランダム 500 日時 × 両パターンで旧 Intl 実装と完全一致する (1900-2100 年域)", () => {
|
|
491
|
-
const rand = makeLcg(20260810)
|
|
492
|
-
const minMs = Date.UTC(1900, 0, 1)
|
|
493
|
-
const spanMs = Date.UTC(2100, 0, 1) - minMs
|
|
494
|
-
for (let i = 0; i < 500; i++) {
|
|
495
|
-
const d = new Date(minMs + Math.floor(rand() * spanMs))
|
|
496
|
-
for (const pattern of ["YYYY-MM-DD", "YYYY-MM-DD HH:mm:ss"] as const) {
|
|
497
|
-
expect(formatDateValue(d, pattern), `${d.toISOString()} / ${pattern}`).toBe(referenceFormatDateValue(d, pattern))
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
})
|
|
501
|
-
|
|
502
|
-
it("境界値 (月替わり・年跨ぎ・一桁時分秒・真夜中・閏日・秒 59) で旧実装と完全一致する", () => {
|
|
503
|
-
const edges = [
|
|
504
|
-
new Date(2026, 0, 1, 0, 0, 0), // 年始・真夜中 (h23 で 00 になること)
|
|
505
|
-
new Date(2025, 11, 31, 23, 59, 59), // 年末・全フィールド最大
|
|
506
|
-
new Date(2026, 7, 31, 1, 2, 3), // 一桁時分秒 (ゼロ詰め)
|
|
507
|
-
new Date(2024, 1, 29, 12, 0, 0), // 閏日
|
|
508
|
-
new Date(2026, 8, 30, 9, 5, 0), // 月末 30 日
|
|
509
|
-
new Date(2026, 2, 1, 0, 0, 1), // 月初・秒 1
|
|
510
|
-
]
|
|
511
|
-
for (const d of edges) {
|
|
512
|
-
for (const pattern of ["YYYY-MM-DD", "YYYY-MM-DD HH:mm:ss"] as const) {
|
|
513
|
-
expect(formatDateValue(d, pattern), `${d.toISOString()} / ${pattern}`).toBe(referenceFormatDateValue(d, pattern))
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
})
|
|
517
|
-
|
|
518
|
-
it("文字列入力 (ISO 日付・ISO 日時・スペース区切り) でも旧実装と完全一致する", () => {
|
|
519
|
-
// "YYYY-MM-DD" 形式は Date 仕様上 UTC 深夜として解釈されローカルへずれるが、
|
|
520
|
-
// その挙動ごと旧実装と一致していることが等価性の要件 (挙動変更ではないことの証明)
|
|
521
|
-
const inputs = ["2026-08-10", "2026-08-10T15:30:00", "2026-08-10 15:30:00", "2026-01-01T00:00:00.000Z"]
|
|
522
|
-
for (const s of inputs) {
|
|
523
|
-
for (const pattern of ["YYYY-MM-DD", "YYYY-MM-DD HH:mm:ss"] as const) {
|
|
524
|
-
expect(formatDateValue(s, pattern), `${s} / ${pattern}`).toBe(referenceFormatDateValue(s, pattern))
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
})
|
|
528
|
-
|
|
529
|
-
it("1000 年未満は旧実装 (年ゼロ詰めなし) から意図的に乖離し、ISO 準拠の 4 桁ゼロ詰めで出力する", () => {
|
|
530
|
-
// 旧 Intl 実装は "202-08-10" を返す。新実装はより正しい "0202-08-10" に固定する
|
|
531
|
-
// (仕様 02 §8.1 に明示した意図的乖離。業務ドメイン 1900-2100 年域の等価性とは独立)
|
|
532
|
-
const ancient = new Date(202, 7, 10, 1, 2, 3)
|
|
533
|
-
expect(formatDateValue(ancient, "YYYY-MM-DD")).toBe("0202-08-10")
|
|
534
|
-
expect(formatDateValue(ancient, "YYYY-MM-DD HH:mm:ss")).toBe("0202-08-10 01:02:03")
|
|
535
|
-
// 負の年 (ISO 拡張表記の文字列入力のみで到達) は符号を除いた絶対値を 4 桁詰め。
|
|
536
|
-
// 素朴な String(-5).padStart(4, "0") は "00-5" と符号ごと詰める崩壊を起こすため固定する
|
|
537
|
-
const bce = new Date(Date.UTC(2000, 5, 15, 12))
|
|
538
|
-
bce.setFullYear(-5)
|
|
539
|
-
expect(formatDateValue(bce, "YYYY-MM-DD")).toMatch(/^-0005-/)
|
|
540
|
-
})
|
|
541
|
-
|
|
542
|
-
it("不変挙動: null / undefined / 空文字は null、解釈不能文字列は原文、Invalid Date は null を返す", () => {
|
|
543
|
-
expect(formatDateValue(null, "YYYY-MM-DD")).toBeNull()
|
|
544
|
-
expect(formatDateValue(undefined, "YYYY-MM-DD")).toBeNull()
|
|
545
|
-
expect(formatDateValue("", "YYYY-MM-DD HH:mm:ss")).toBeNull()
|
|
546
|
-
expect(formatDateValue("not-a-date", "YYYY-MM-DD")).toBe("not-a-date")
|
|
547
|
-
expect(formatDateValue(new Date(Number.NaN), "YYYY-MM-DD HH:mm:ss")).toBeNull()
|
|
548
|
-
})
|
|
549
|
-
|
|
550
|
-
it("性能ガード: 100,000 回の整形が 2 秒未満で完了する (Intl 逆行の煙探知機)", () => {
|
|
551
|
-
// 手組み実装は約 0.1μs/呼。旧 Intl 実装は約 66μs/呼で 100k 回 ≈ 6.6 秒かかるため、
|
|
552
|
-
// 2 秒の粗い閾値でも逆行 (toLocale* への差し戻し) を確実に検知できる
|
|
553
|
-
const d = new Date(2026, 7, 10, 15, 30, 45)
|
|
554
|
-
const startMs = performance.now()
|
|
555
|
-
for (let i = 0; i < 100_000; i++) {
|
|
556
|
-
formatDateValue(d, "YYYY-MM-DD HH:mm:ss")
|
|
557
|
-
}
|
|
558
|
-
expect(performance.now() - startMs).toBeLessThan(2000)
|
|
559
|
-
})
|
|
560
|
-
})
|
|
561
|
-
|
|
562
|
-
describe("区分 (sourceType) 可視性フィルタ", () => {
|
|
563
|
-
/** テスト用の可視集合 (NI と kintone のみ許可)。 */
|
|
564
|
-
const restricted = DailyReportViewerScope.restrictTo(["NI", "kintone"])
|
|
565
|
-
/** 全拒否の可視集合 (権限なし・リゾルバ例外時と同じ状態)。 */
|
|
566
|
-
const denyAll = DailyReportViewerScope.restrictTo([])
|
|
567
|
-
|
|
568
|
-
/** 区分述語を含む最後のクエリを取り出す。 */
|
|
569
|
-
const lastQueryWithSourceType = (svc: { __queries: { whereSql: string | null; whereParams: unknown[] }[] }) => svc.__queries.filter((q) => (q.whereSql ?? "").includes("[source_type]")).at(-1)
|
|
570
|
-
|
|
571
|
-
describe("読み取り経路への述語注入", () => {
|
|
572
|
-
it("ID 一覧 (全量) の WHERE に畳み込み済みトークンの IN 述語が載る", async () => {
|
|
573
|
-
const svc = makeService([])
|
|
574
|
-
await svc.getDailyReportIdsByExternalId(restricted, "ext", { forceRefresh: true })
|
|
575
|
-
|
|
576
|
-
const recorded = lastQueryWithSourceType(svc)
|
|
577
|
-
// レンダリングは大文字 LOWER( なので大小文字を厳密に一致させる
|
|
578
|
-
expect(recorded?.whereSql).toContain("LOWER(")
|
|
579
|
-
expect(recorded?.whereSql).toContain("[source_type]")
|
|
580
|
-
expect(recorded?.whereSql).toContain(" in ")
|
|
581
|
-
// 閲覧者 ID など他の束縛値と同居するため部分集合で検査する
|
|
582
|
-
expect(recorded?.whereParams).toEqual(expect.arrayContaining(["kintone", "ni"]))
|
|
583
|
-
})
|
|
584
|
-
|
|
585
|
-
it("ID 一覧 (先頭ページ) にも同一の述語が載る", async () => {
|
|
586
|
-
const svc = makeService([])
|
|
587
|
-
await svc.getDailyReportIdsFirstPageByExternalId(restricted, "ext", 200)
|
|
588
|
-
|
|
589
|
-
const recorded = lastQueryWithSourceType(svc)
|
|
590
|
-
expect(recorded?.whereSql).toContain("LOWER(")
|
|
591
|
-
expect(recorded?.whereParams).toEqual(expect.arrayContaining(["kintone", "ni"]))
|
|
592
|
-
})
|
|
593
|
-
|
|
594
|
-
it("営業日別一覧の WHERE に述語が載る", async () => {
|
|
595
|
-
const svc = makeService([])
|
|
596
|
-
await svc.getDailyReportsByBusinessDateByExternalId(restricted, "2099-01-05", "ext", { forceRefresh: true })
|
|
597
|
-
|
|
598
|
-
const recorded = lastQueryWithSourceType(svc)
|
|
599
|
-
expect(recorded?.whereSql).toContain("LOWER(")
|
|
600
|
-
expect(recorded?.whereParams).toEqual(expect.arrayContaining(["kintone", "ni"]))
|
|
601
|
-
})
|
|
602
|
-
|
|
603
|
-
it("詳細取得の WHERE に述語が載る", async () => {
|
|
604
|
-
const svc = makeService([])
|
|
605
|
-
await svc.getDailyReportDetailById(restricted, 1, 8, { forceRefresh: true })
|
|
606
|
-
|
|
607
|
-
const recorded = lastQueryWithSourceType(svc)
|
|
608
|
-
expect(recorded?.whereSql).toContain("LOWER(")
|
|
609
|
-
expect(recorded?.whereParams).toEqual(expect.arrayContaining(["kintone", "ni"]))
|
|
610
|
-
})
|
|
611
|
-
|
|
612
|
-
it("管理用の営業日別一覧も区分でゲートされる (docstring の警告だけに頼らない)", async () => {
|
|
613
|
-
// v0.14.0 でゲート対象へ昇格した経路。ここが無いと、述語・短絡・ダイジェストを
|
|
614
|
-
// すべて剥がしても既存テスト (無制限スコープのみ) は緑のまま通ってしまう
|
|
615
|
-
const svc = makeService([])
|
|
616
|
-
await svc.getDailyReportsByBusinessDate(restricted, "2099-01-05", { forceRefresh: true })
|
|
617
|
-
|
|
618
|
-
const recorded = lastQueryWithSourceType(svc)
|
|
619
|
-
expect(recorded?.whereSql).toContain("LOWER(")
|
|
620
|
-
expect(recorded?.whereParams).toEqual(expect.arrayContaining(["kintone", "ni"]))
|
|
621
|
-
})
|
|
622
|
-
|
|
623
|
-
it("管理用の営業日別一覧も全拒否では DB を引かない", async () => {
|
|
624
|
-
const svc = makeService([])
|
|
625
|
-
expect(await svc.getDailyReportsByBusinessDate(denyAll, "2099-01-05", { forceRefresh: true })).toEqual([])
|
|
626
|
-
expect(svc.__queries).toHaveLength(0)
|
|
627
|
-
})
|
|
628
|
-
|
|
629
|
-
it("管理用の営業日別一覧も可視集合ごとにキャッシュが隔離される", async () => {
|
|
630
|
-
const svc = makeService([])
|
|
631
|
-
await svc.getDailyReportsByBusinessDate(DailyReportViewerScope.restrictTo(["ni"]), "2099-01-05", {})
|
|
632
|
-
const afterFirst = svc.__queries.length
|
|
633
|
-
await svc.getDailyReportsByBusinessDate(DailyReportViewerScope.restrictTo(["kintone"]), "2099-01-05", {})
|
|
634
|
-
|
|
635
|
-
expect(svc.__queries.length).toBeGreaterThan(afterFirst)
|
|
636
|
-
})
|
|
637
|
-
|
|
638
|
-
it("添付の認可述語にも載る (一覧だけ絞って添付から抜ける穴を塞ぐ)", async () => {
|
|
639
|
-
const svc = makeService([{ fileName: "a.png", filePath: "gcs://b/a.png", fileType: null, fileSize: 1 }])
|
|
640
|
-
await svc.getAttachmentForUser(restricted, 11, 8)
|
|
641
|
-
|
|
642
|
-
const recorded = lastQueryWithSourceType(svc)
|
|
643
|
-
expect(recorded?.whereSql).toContain("LOWER(")
|
|
644
|
-
expect(recorded?.whereParams).toEqual(expect.arrayContaining(["kintone", "ni"]))
|
|
645
|
-
})
|
|
646
|
-
|
|
647
|
-
it("外部 ID 経由の詳細取得は可視集合をそのまま透過する (ここで null へ潰さない)", async () => {
|
|
648
|
-
const svc = makeService([])
|
|
649
|
-
await svc.getDailyReportDetailByIdByExternalId(restricted, 1, "ext", { forceRefresh: true })
|
|
650
|
-
|
|
651
|
-
const recorded = lastQueryWithSourceType(svc)
|
|
652
|
-
expect(recorded?.whereParams).toEqual(expect.arrayContaining(["kintone", "ni"]))
|
|
653
|
-
})
|
|
654
|
-
|
|
655
|
-
it("無制限 (null) では述語が一切現れない (現行互換の回帰ガード)", async () => {
|
|
656
|
-
const svc = makeService([])
|
|
657
|
-
await svc.getDailyReportIdsByExternalId(UNRESTRICTED_SCOPE, "ext", { forceRefresh: true })
|
|
658
|
-
await svc.getDailyReportsByBusinessDateByExternalId(UNRESTRICTED_SCOPE, "2099-01-05", "ext", { forceRefresh: true })
|
|
659
|
-
await svc.getDailyReportDetailById(UNRESTRICTED_SCOPE, 1, 8, { forceRefresh: true })
|
|
660
|
-
|
|
661
|
-
expect(svc.__queries.every((q) => !(q.whereSql ?? "").includes("[source_type]"))).toBe(true)
|
|
662
|
-
})
|
|
663
|
-
})
|
|
664
|
-
|
|
665
|
-
describe("全拒否 (空集合) は DB を引かずに 0 件へ短絡する", () => {
|
|
666
|
-
it("読み取り 5 経路すべてが問い合わせ無しで空を返す", async () => {
|
|
667
|
-
const svc = makeService([{ fileName: "a.png", filePath: "gcs://b/a.png", fileType: null, fileSize: 1 }], true)
|
|
668
|
-
|
|
669
|
-
expect(await svc.getDailyReportIdsByExternalId(denyAll, "ext", { forceRefresh: true })).toEqual([])
|
|
670
|
-
expect(await svc.getDailyReportIdsFirstPageByExternalId(denyAll, "ext", 200)).toEqual([])
|
|
671
|
-
expect(await svc.getDailyReportsByBusinessDateByExternalId(denyAll, "2099-01-05", "ext", { forceRefresh: true })).toEqual([])
|
|
672
|
-
expect(await svc.getDailyReportDetailById(denyAll, 1, 8, { forceRefresh: true })).toBeNull()
|
|
673
|
-
expect(await svc.getAttachmentForUser(denyAll, 11, 8)).toBeNull()
|
|
674
|
-
|
|
675
|
-
// 短絡しているので DB は一度も引かれない
|
|
676
|
-
expect(svc.__queries).toHaveLength(0)
|
|
677
|
-
})
|
|
678
|
-
|
|
679
|
-
it("条件生成器自体も fail-close する (呼び出し側の短絡が漏れても認可は反転しない)", () => {
|
|
680
|
-
// 空集合を「制限なし」と解釈すると添付が全区分ダウンロード可能になる。
|
|
681
|
-
// 短絡を迂回しても 1 = 0 が残ることを、生成 SQL で直接固定する
|
|
682
|
-
const condition = buildVisibleSourceTypeCondition(tables.hub.sourceType, denyAll.visible)
|
|
683
|
-
expect(condition).toBeDefined()
|
|
684
|
-
expect(dialect.sqlToQuery(condition as SQL).sql).toContain("1 = 0")
|
|
685
|
-
})
|
|
686
|
-
})
|
|
687
|
-
|
|
688
|
-
describe("キャッシュの可視集合ダイジェスト隔離", () => {
|
|
689
|
-
it("正規化後に等価な可視集合はキャッシュを再利用する (性能無退行)", async () => {
|
|
690
|
-
const svc = makeService([])
|
|
691
|
-
await svc.getDailyReportIdsByExternalId(DailyReportViewerScope.restrictTo(["NI"]), "ext", {})
|
|
692
|
-
const afterFirst = svc.__queries.length
|
|
693
|
-
await svc.getDailyReportIdsByExternalId(DailyReportViewerScope.restrictTo([" ni "]), "ext", {})
|
|
694
|
-
|
|
695
|
-
expect(svc.__queries.length).toBe(afterFirst)
|
|
696
|
-
})
|
|
697
|
-
|
|
698
|
-
it("異なる可視集合は別バケットになる (別権限へ他人の結果を配らない)", async () => {
|
|
699
|
-
const svc = makeService([])
|
|
700
|
-
await svc.getDailyReportIdsByExternalId(DailyReportViewerScope.restrictTo(["ni"]), "ext", {})
|
|
701
|
-
const afterFirst = svc.__queries.length
|
|
702
|
-
await svc.getDailyReportIdsByExternalId(DailyReportViewerScope.restrictTo(["kintone"]), "ext", {})
|
|
703
|
-
|
|
704
|
-
expect(svc.__queries.length).toBeGreaterThan(afterFirst)
|
|
705
|
-
})
|
|
706
|
-
|
|
707
|
-
it("営業日別と詳細でも可視集合ごとに隔離される", async () => {
|
|
708
|
-
const svc = makeService([])
|
|
709
|
-
await svc.getDailyReportsByBusinessDateByExternalId(DailyReportViewerScope.restrictTo(["ni"]), "2099-01-05", "ext", {})
|
|
710
|
-
const afterDateFirst = svc.__queries.length
|
|
711
|
-
await svc.getDailyReportsByBusinessDateByExternalId(DailyReportViewerScope.restrictTo(["kintone"]), "2099-01-05", "ext", {})
|
|
712
|
-
expect(svc.__queries.length).toBeGreaterThan(afterDateFirst)
|
|
713
|
-
|
|
714
|
-
await svc.getDailyReportDetailById(DailyReportViewerScope.restrictTo(["ni"]), 1, 8, {})
|
|
715
|
-
const afterDetailFirst = svc.__queries.length
|
|
716
|
-
await svc.getDailyReportDetailById(DailyReportViewerScope.restrictTo(["kintone"]), 1, 8, {})
|
|
717
|
-
expect(svc.__queries.length).toBeGreaterThan(afterDetailFirst)
|
|
718
|
-
})
|
|
719
|
-
})
|
|
720
|
-
|
|
721
|
-
describe("キャッシュ無効化はダイジェスト付きキーを取りこぼさない", () => {
|
|
722
|
-
it("setStarStatus の後は同じ可視集合の詳細が再取得される", async () => {
|
|
723
|
-
const svc = makeService([
|
|
724
|
-
{
|
|
725
|
-
hub: {
|
|
726
|
-
id: 1,
|
|
727
|
-
sourceType: "Internal",
|
|
728
|
-
deletedAt: null,
|
|
729
|
-
userId: 8,
|
|
730
|
-
businessDate: "2099-01-05",
|
|
731
|
-
title: "t",
|
|
732
|
-
summary: null,
|
|
733
|
-
sourceId: "1",
|
|
734
|
-
sourceIdNum: 1,
|
|
735
|
-
createdAt: "2099-01-05 00:00:00",
|
|
736
|
-
createdBy: "8",
|
|
737
|
-
updatedAt: "2099-01-05 00:00:00",
|
|
738
|
-
updatedBy: "8",
|
|
739
|
-
deletedBy: null,
|
|
740
|
-
},
|
|
741
|
-
internal: null,
|
|
742
|
-
isStarred: false,
|
|
743
|
-
isRead: false,
|
|
744
|
-
},
|
|
745
|
-
])
|
|
746
|
-
await svc.getDailyReportDetailById(restricted, 1, 8, {})
|
|
747
|
-
|
|
748
|
-
await svc.setStarStatus(UNRESTRICTED_SCOPE, 8, 1, "2099-01-05", true, "tmp")
|
|
749
|
-
// ❗ 基準はミューテーション「後」に取る。前に取ると setStarStatus 自身が発行する
|
|
750
|
-
// 2 本の select だけで閾値を満たしてしまい、無効化が壊れていても通ってしまう
|
|
751
|
-
const afterMutation = svc.__queries.length
|
|
752
|
-
await svc.getDailyReportDetailById(restricted, 1, 8, {})
|
|
753
|
-
|
|
754
|
-
// 接頭辞無効化が効いていなければキャッシュヒットで再クエリが 1 本も出ない
|
|
755
|
-
expect(svc.__queries.length).toBeGreaterThan(afterMutation)
|
|
756
|
-
})
|
|
757
|
-
|
|
758
|
-
it("setReadStatus の後も同様に再取得される (setStar だけ直す退行を防ぐ)", async () => {
|
|
759
|
-
const svc = makeService([
|
|
760
|
-
{
|
|
761
|
-
hub: {
|
|
762
|
-
id: 1,
|
|
763
|
-
sourceType: "Internal",
|
|
764
|
-
deletedAt: null,
|
|
765
|
-
userId: 8,
|
|
766
|
-
businessDate: "2099-01-05",
|
|
767
|
-
title: "t",
|
|
768
|
-
summary: null,
|
|
769
|
-
sourceId: "1",
|
|
770
|
-
sourceIdNum: 1,
|
|
771
|
-
createdAt: "2099-01-05 00:00:00",
|
|
772
|
-
createdBy: "8",
|
|
773
|
-
updatedAt: "2099-01-05 00:00:00",
|
|
774
|
-
updatedBy: "8",
|
|
775
|
-
deletedBy: null,
|
|
776
|
-
},
|
|
777
|
-
internal: null,
|
|
778
|
-
isStarred: false,
|
|
779
|
-
isRead: false,
|
|
780
|
-
},
|
|
781
|
-
])
|
|
782
|
-
await svc.getDailyReportDetailById(restricted, 1, 8, {})
|
|
783
|
-
|
|
784
|
-
await svc.setReadStatus(UNRESTRICTED_SCOPE, 8, 1, "2099-01-05", true, "tmp")
|
|
785
|
-
// 基準はミューテーション後 (理由は setStarStatus のテストと同じ)
|
|
786
|
-
const afterMutation = svc.__queries.length
|
|
787
|
-
await svc.getDailyReportDetailById(restricted, 1, 8, {})
|
|
788
|
-
|
|
789
|
-
expect(svc.__queries.length).toBeGreaterThan(afterMutation)
|
|
790
|
-
})
|
|
791
|
-
|
|
792
|
-
it("setStarStatus の後は同じ可視集合の営業日別一覧も再取得される (date 側の接頭辞変換を個別に gate)", async () => {
|
|
793
|
-
// detail 側だけ接頭辞化しても date 側が完全一致のままなら、営業日別一覧が
|
|
794
|
-
// 古いスター状態を配り続ける。両者を別々の表明で固定する
|
|
795
|
-
const svc = makeService([{ hub: baseHub({ id: 1 }), internal: null, isStarred: false, isRead: false, creatorName: "山田" }])
|
|
796
|
-
await svc.getDailyReportsByBusinessDateByExternalId(restricted, "2099-01-05", "ext", {})
|
|
797
|
-
|
|
798
|
-
await svc.setStarStatus(UNRESTRICTED_SCOPE, 8, 1, "2099-01-05", true, "tmp")
|
|
799
|
-
const afterMutation = svc.__queries.length
|
|
800
|
-
await svc.getDailyReportsByBusinessDateByExternalId(restricted, "2099-01-05", "ext", {})
|
|
801
|
-
|
|
802
|
-
expect(svc.__queries.length).toBeGreaterThan(afterMutation)
|
|
803
|
-
})
|
|
804
|
-
|
|
805
|
-
it("createDailyReport は作成者の ID 一覧キャッシュを落とす (redis 無し配備でも消える)", async () => {
|
|
806
|
-
// createDailyReport は ids の広域 prefix 無効化を持たないため、ユーザー単位の
|
|
807
|
-
// 接頭辞無効化だけが頼り。完全一致キーのままにすると、作成した日報が自分の一覧から
|
|
808
|
-
// TTL 分 (既定 180 秒) 消える
|
|
809
|
-
// 行を返さないモックでも create は完走する (詳細が null なら SSE を出さないだけ)。
|
|
810
|
-
// 検証対象は「無効化が走ったか」なので、これで十分かつ流れの変化に強い
|
|
811
|
-
const svc = makeService([])
|
|
812
|
-
await svc.getDailyReportIdsByExternalId(restricted, "ext", {})
|
|
813
|
-
|
|
814
|
-
await svc.createDailyReport(8, "2099-01-05", "tmp")
|
|
815
|
-
const afterCreate = svc.__queries.length
|
|
816
|
-
await svc.getDailyReportIdsByExternalId(restricted, "ext", {})
|
|
817
|
-
|
|
818
|
-
// 無効化が効いていなければキャッシュヒットで再クエリは 0 本になる
|
|
819
|
-
expect(svc.__queries.length).toBeGreaterThan(afterCreate)
|
|
820
|
-
})
|
|
821
|
-
})
|
|
822
|
-
|
|
823
|
-
describe("ミューテーションの区分ゲート", () => {
|
|
824
|
-
it("addComment は不可視区分の日報を Not Found で拒否する", async () => {
|
|
825
|
-
const svc = makeService([{ sourceType: "Internal", deletedAt: null, userId: 8 }])
|
|
826
|
-
await expect(svc.addComment(restricted, 8, 1, "本文", "2099-01-05", "tmp")).rejects.toThrow("Not Found")
|
|
827
|
-
})
|
|
828
|
-
|
|
829
|
-
it("setStarStatus は不可視区分を Not Found で拒否する", async () => {
|
|
830
|
-
const svc = makeService([{ sourceType: "Internal", deletedAt: null }])
|
|
831
|
-
await expect(svc.setStarStatus(restricted, 8, 1, "2099-01-05", true, "tmp")).rejects.toThrow("Not Found")
|
|
832
|
-
})
|
|
833
|
-
|
|
834
|
-
it("setReadStatus は不可視区分を Not Found で拒否する", async () => {
|
|
835
|
-
const svc = makeService([{ sourceType: "Internal", deletedAt: null }])
|
|
836
|
-
await expect(svc.setReadStatus(restricted, 8, 1, "2099-01-05", true, "tmp")).rejects.toThrow("Not Found")
|
|
837
|
-
})
|
|
838
|
-
|
|
839
|
-
it("setStarStatus は存在しない hubId を Not Found で拒否する (存在オラクルの是正)", async () => {
|
|
840
|
-
const svc = makeService([])
|
|
841
|
-
await expect(svc.setStarStatus(UNRESTRICTED_SCOPE, 8, 999, "2099-01-05", true, "tmp")).rejects.toThrow("Not Found")
|
|
842
|
-
})
|
|
843
|
-
|
|
844
|
-
it("setReadStatus は論理削除済みの日報を Not Found で拒否する", async () => {
|
|
845
|
-
const svc = makeService([{ sourceType: "Internal", deletedAt: "2099-01-06 00:00:00" }])
|
|
846
|
-
await expect(svc.setReadStatus(UNRESTRICTED_SCOPE, 8, 1, "2099-01-05", true, "tmp")).rejects.toThrow("Not Found")
|
|
847
|
-
})
|
|
848
|
-
|
|
849
|
-
it("deleteComment は所有者チェックより先に区分ゲートを適用する (403/404 の存在オラクル回避)", async () => {
|
|
850
|
-
// 他人 (userId=99) のコメント かつ 不可視区分。所有者チェックが先だと Unauthorized(403) になり、
|
|
851
|
-
// 「隠したはずの日報が存在する」ことを推定できてしまう
|
|
852
|
-
const svc = makeService([], false, {
|
|
853
|
-
selectQueue: [[{ id: 5, hubId: 1, userId: 99, body: "x", createdAt: "2099-01-05 00:00:00", createdBy: "99", updatedAt: "2099-01-05 00:00:00", updatedBy: "99" }], [{ userId: 99, sourceType: "Internal" }]],
|
|
854
|
-
})
|
|
855
|
-
await expect(svc.deleteComment(restricted, 8, 1, 5, "2099-01-05", "tmp")).rejects.toThrow("Not Found")
|
|
856
|
-
})
|
|
857
|
-
})
|
|
858
|
-
|
|
859
|
-
describe("下書き所有者ゲート (書き込み可能な存在オラクルの封じ込め)", () => {
|
|
860
|
-
// 読み取り経路は「自分の日報 or 下書きラベル無し」しか返さない。書き込みゲートが
|
|
861
|
-
// この条項を落とすと、閲覧できないはずの他人の下書きへ既読 / スター / コメントを
|
|
862
|
-
// 付けられてしまう (行の存在も書き込み可否から推定できる)
|
|
863
|
-
it("他人の下書きへは既読を付けられない", async () => {
|
|
864
|
-
// ゲートのクエリが 0 行を返す = 可視性述語で弾かれた状態
|
|
865
|
-
const svc = makeService([])
|
|
866
|
-
await expect(svc.setReadStatus(UNRESTRICTED_SCOPE, 8, 1, "2099-01-05", true, "tmp")).rejects.toThrow("Not Found")
|
|
867
|
-
})
|
|
868
|
-
|
|
869
|
-
it("他人の下書きへはスターを付けられない", async () => {
|
|
870
|
-
const svc = makeService([])
|
|
871
|
-
await expect(svc.setStarStatus(UNRESTRICTED_SCOPE, 8, 1, "2099-01-05", true, "tmp")).rejects.toThrow("Not Found")
|
|
872
|
-
})
|
|
873
|
-
|
|
874
|
-
it("書き込みゲートの述語が読み取り経路と同じ形をしている", async () => {
|
|
875
|
-
const svc = makeService([{ sourceType: "Internal", deletedAt: null }])
|
|
876
|
-
await svc.setStarStatus(UNRESTRICTED_SCOPE, 8, 1, "2099-01-05", true, "tmp").catch(() => undefined)
|
|
877
|
-
|
|
878
|
-
// 下書きラベル関連を LEFT JOIN し、所有者 OR 下書き非該当で絞っていること
|
|
879
|
-
const gate = svc.__queries.find((q) => (q.whereSql ?? "").includes("[draft_label].[hub_id] is null"))
|
|
880
|
-
expect(gate).toBeDefined()
|
|
881
|
-
expect(gate?.whereSql).toContain("[user_id] = ")
|
|
882
|
-
expect(gate?.whereSql).toContain(" or ")
|
|
883
|
-
})
|
|
884
|
-
|
|
885
|
-
it("他人の下書きへはコメントも付けられない", async () => {
|
|
886
|
-
const svc = makeService([], false, {
|
|
887
|
-
selectQueue: [
|
|
888
|
-
[{ sourceType: "Internal", deletedAt: null, userId: 99 }], // hub は存在する (所有者は他人)
|
|
889
|
-
[{ id: 10 }], // 下書きラベル定義
|
|
890
|
-
[], // 共通ゲート: 可視性述語で 0 行 = 他人の下書き
|
|
891
|
-
],
|
|
892
|
-
})
|
|
893
|
-
await expect(svc.addComment(UNRESTRICTED_SCOPE, 8, 1, "本文", "2099-01-05", "tmp")).rejects.toThrow("Not Found")
|
|
894
|
-
})
|
|
895
|
-
})
|
|
896
|
-
|
|
897
|
-
describe("SSE ペイロードの区分付与", () => {
|
|
898
|
-
it("comment-add は親日報の sourceType を載せる", async () => {
|
|
899
|
-
const svc = makeService([], false, {
|
|
900
|
-
// hub 取得 → 下書きラベル定義 → 共通ゲート → 下書き関連 → 投稿者名
|
|
901
|
-
selectQueue: [[{ sourceType: "Internal", deletedAt: null, userId: 8 }], [{ id: 10 }], [{ sourceType: "Internal", deletedAt: null }], [], [{ displayName: "山田" }]],
|
|
902
|
-
})
|
|
903
|
-
await svc.addComment(UNRESTRICTED_SCOPE, 8, 1, "本文", "2099-01-05", "tmp")
|
|
904
|
-
|
|
905
|
-
const add = svc.__sse.find((m) => m.type === "comment-add")
|
|
906
|
-
expect(add?.sourceType).toBe("Internal")
|
|
907
|
-
})
|
|
908
|
-
|
|
909
|
-
it("report-delete は削除対象の sourceType を載せる", async () => {
|
|
910
|
-
const svc = makeService([{ id: 1, sourceType: "NI", businessDate: "2099-01-05", userId: 8, title: "t", createdAt: "2099-01-05 00:00:00", createdBy: "8", updatedAt: "2099-01-05 00:00:00", updatedBy: "8", deletedAt: null }])
|
|
911
|
-
await svc.deleteDailyReport(1, 8, "tmp")
|
|
912
|
-
|
|
913
|
-
const del = svc.__sse.find((m) => m.type === "report-delete")
|
|
914
|
-
expect(del?.sourceType).toBe("NI")
|
|
915
|
-
})
|
|
916
|
-
})
|
|
917
|
-
|
|
918
|
-
describe("自報ミューテーションは所有者チェックで守る (区分ゲートを持たない理由)", () => {
|
|
919
|
-
// create / update / publish / delete に区分ゲートが無いのは意図的である。所有者が自分の
|
|
920
|
-
// 日報を操作することは区分閲覧のバイパスではないため。ただしその前提である所有者チェックが
|
|
921
|
-
// 外れると、区分ゲートも無い分だけ無防備になるので、ここで固定しておく
|
|
922
|
-
const otherOwnersHub = [
|
|
923
|
-
{ id: 1, sourceType: "Internal", businessDate: "2099-01-05", userId: 99, title: "t", summary: null, sourceId: "1", sourceIdNum: 1, createdAt: "2099-01-05 00:00:00", createdBy: "99", updatedAt: "2099-01-05 00:00:00", updatedBy: "99", deletedAt: null, deletedBy: null },
|
|
924
|
-
]
|
|
925
|
-
|
|
926
|
-
it("updateDailyReport は他人の日報を Unauthorized で拒否する", async () => {
|
|
927
|
-
const svc = makeService(otherOwnersHub)
|
|
928
|
-
await expect(svc.updateDailyReport(1, 8, { title: "x" }, "tmp")).rejects.toThrow("Unauthorized")
|
|
929
|
-
})
|
|
930
|
-
|
|
931
|
-
it("publishDailyReport は他人の日報を Unauthorized で拒否する", async () => {
|
|
932
|
-
const svc = makeService(otherOwnersHub)
|
|
933
|
-
await expect(svc.publishDailyReport(1, 8, "tmp")).rejects.toThrow("Unauthorized")
|
|
934
|
-
})
|
|
935
|
-
|
|
936
|
-
it("deleteDailyReport は他人の日報を Unauthorized で拒否する", async () => {
|
|
937
|
-
const svc = makeService(otherOwnersHub)
|
|
938
|
-
await expect(svc.deleteDailyReport(1, 8, "tmp")).rejects.toThrow("Unauthorized")
|
|
939
|
-
})
|
|
940
|
-
})
|
|
941
|
-
|
|
942
|
-
describe("コメント次元の射影 (mapHubRecord)", () => {
|
|
943
|
-
/** 詳細取得のクエリ順 (下書きラベル ID → hub → labels → comments → attachments) に合わせたキューを組む。 */
|
|
944
|
-
const detailQueue = (comments: unknown[]) => [[{ id: 10 }], [{ hub: baseHub({ sourceType: "Internal" }), internal: null, creatorName: null }], [], comments, []]
|
|
945
|
-
|
|
946
|
-
/** 他人 (99) と自分 (8) のコメントを 1 件ずつ含む固定入力。 */
|
|
947
|
-
const twoComments = [
|
|
948
|
-
{ id: 1, body: "他人のコメント", createdAt: "2099-01-05 00:00:00", userId: 99, userName: "他人" },
|
|
949
|
-
{ id: 2, body: "自分のコメント", createdAt: "2099-01-05 00:00:01", userId: 8, userName: "本人" },
|
|
950
|
-
]
|
|
951
|
-
|
|
952
|
-
it("コメント次元が許可する区分では両コメント面がそのまま載る", async () => {
|
|
953
|
-
const svc = makeService([], false, { selectQueue: detailQueue(twoComments) })
|
|
954
|
-
const detail = await svc.getDailyReportDetailById(DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: ["Internal"] }), 1, 8, { forceRefresh: true })
|
|
955
|
-
expect(detail?.postedComments.map((c) => c.id)).toEqual([1, 2])
|
|
956
|
-
})
|
|
957
|
-
|
|
958
|
-
it("コメント次元が拒否する区分では他人のコメントが落ち、自分のコメントだけ残る (要件 5)", async () => {
|
|
959
|
-
// 自分のコメントを隠すと「UI に見えないのに削除だけできる」非対称が生まれるため、
|
|
960
|
-
// 所有分は常に残す。他人の本文は 1 件も残してはならない
|
|
961
|
-
const svc = makeService([], false, { selectQueue: detailQueue(twoComments) })
|
|
962
|
-
const detail = await svc.getDailyReportDetailById(DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: [] }), 1, 8, { forceRefresh: true })
|
|
963
|
-
expect(detail?.postedComments.map((c) => c.id)).toEqual([2])
|
|
964
|
-
expect(detail?.postedComments[0].isMine).toBe(true)
|
|
965
|
-
// 本文そのものは読めたまま (次元が分離していることの実証)
|
|
966
|
-
expect(detail?.subject).toBe("t")
|
|
967
|
-
})
|
|
968
|
-
|
|
969
|
-
it("コメントを落としてもキーは残す (空配列)。省くと SSE 検証が落ちて更新が届かなくなる", async () => {
|
|
970
|
-
const svc = makeService([], false, { selectQueue: detailQueue([twoComments[0]]) })
|
|
971
|
-
const detail = await svc.getDailyReportDetailById(DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: [] }), 1, 8, { forceRefresh: true })
|
|
972
|
-
expect(detail?.postedComments).toEqual([])
|
|
973
|
-
expect(detail?.externalComments).toEqual([])
|
|
974
|
-
expect(Object.hasOwn(detail as object, "postedComments")).toBe(true)
|
|
975
|
-
expect(Object.hasOwn(detail as object, "externalComments")).toBe(true)
|
|
976
|
-
})
|
|
977
|
-
|
|
978
|
-
it("素の配列指定 (コメント次元が read に従う) では従来どおり全件載る", async () => {
|
|
979
|
-
const svc = makeService([], false, { selectQueue: detailQueue(twoComments) })
|
|
980
|
-
const detail = await svc.getDailyReportDetailById(DailyReportViewerScope.restrictTo(["Internal"]), 1, 8, { forceRefresh: true })
|
|
981
|
-
expect(detail?.postedComments.map((c) => c.id)).toEqual([1, 2])
|
|
982
|
-
})
|
|
983
|
-
|
|
984
|
-
it("閲覧者 ID が無い経路ではコメント不可時に 1 件も残らない (所有判定が成立しないため)", async () => {
|
|
985
|
-
// 管理 / バッチ経路 (currentUserId 無し) は isMine を立てられないので全落ちが正しい
|
|
986
|
-
const svc = makeService([{ hub: baseHub({ sourceType: "Internal" }), internal: null, creatorName: null }])
|
|
987
|
-
const [detail] = await svc.getDailyReportsByBusinessDate(DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: [] }), "2099-01-05", { forceRefresh: true })
|
|
988
|
-
expect(detail.postedComments).toEqual([])
|
|
989
|
-
})
|
|
990
|
-
})
|
|
991
|
-
|
|
992
|
-
describe("コメント次元の記入ゲート (addComment)", () => {
|
|
993
|
-
it("コメント次元が拒否する区分には記入できない (本文は読めても)", async () => {
|
|
994
|
-
const svc = makeService([{ sourceType: "Internal", deletedAt: null, userId: 8 }])
|
|
995
|
-
const scope = DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: [] })
|
|
996
|
-
await expect(svc.addComment(scope, 8, 1, "本文", "2099-01-05", "tmp")).rejects.toThrow("Comments are restricted")
|
|
997
|
-
})
|
|
998
|
-
|
|
999
|
-
it("拒否理由は「制限」であって「不存在」ではない (閲覧者には日報が見えているため)", async () => {
|
|
1000
|
-
const svc = makeService([{ sourceType: "Internal", deletedAt: null, userId: 8 }])
|
|
1001
|
-
const scope = DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: [] })
|
|
1002
|
-
await expect(svc.addComment(scope, 8, 1, "本文", "2099-01-05", "tmp")).rejects.toThrow(/comment permission/)
|
|
1003
|
-
})
|
|
1004
|
-
|
|
1005
|
-
it("コメント次元が許可する区分には従来どおり記入できる", async () => {
|
|
1006
|
-
const svc = makeService([], false, {
|
|
1007
|
-
selectQueue: [[{ sourceType: "Internal", deletedAt: null, userId: 8 }], [{ id: 10 }], [{ sourceType: "Internal", deletedAt: null }], [], [{ displayName: "山田" }]],
|
|
1008
|
-
})
|
|
1009
|
-
const scope = DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: ["Internal"] })
|
|
1010
|
-
await expect(svc.addComment(scope, 8, 1, "本文", "2099-01-05", "tmp")).resolves.toBeDefined()
|
|
1011
|
-
})
|
|
1012
|
-
})
|
|
1013
|
-
|
|
1014
|
-
describe("deleteComment はコメント次元でゲートしない (契約)", () => {
|
|
1015
|
-
it("コメント次元が拒否していても自分のコメントは削除できる", async () => {
|
|
1016
|
-
// ゲートすると、権限剥奪の瞬間に既存の自分のコメントが恒久的に削除不能になる。
|
|
1017
|
-
// 「自分のコメントは常に可視」(mapHubRecord) と対を成す規則
|
|
1018
|
-
const svc = makeService([], false, {
|
|
1019
|
-
selectQueue: [[{ id: 5, hubId: 1, userId: 8, body: "x", createdAt: "2099-01-05 00:00:00", createdBy: "8", updatedAt: "2099-01-05 00:00:00", updatedBy: "8" }], [{ userId: 8, sourceType: "Internal" }], [{ id: 10 }], [{ sourceType: "Internal", deletedAt: null }]],
|
|
1020
|
-
})
|
|
1021
|
-
const scope = DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: [] })
|
|
1022
|
-
await expect(svc.deleteComment(scope, 8, 1, 5, "2099-01-05", "tmp")).resolves.toBeUndefined()
|
|
1023
|
-
})
|
|
1024
|
-
})
|
|
1025
|
-
|
|
1026
|
-
describe("キャッシュはコメント次元でも隔離される", () => {
|
|
1027
|
-
it("コメント権限だけが違う同一ユーザーは別バケットになる", async () => {
|
|
1028
|
-
// 同一キーだと、コメント権限を剥奪された直後の TTL 内に剥奪前の本文入り詳細が返る
|
|
1029
|
-
const svc = makeService([{ hub: baseHub({}), internal: null, creatorName: null }])
|
|
1030
|
-
await svc.getDailyReportsByBusinessDate(DailyReportViewerScope.restrictTo({ read: ["Internal"] }), "2099-01-05", {})
|
|
1031
|
-
const first = svc.__queries.length
|
|
1032
|
-
await svc.getDailyReportsByBusinessDate(DailyReportViewerScope.restrictTo({ read: ["Internal"], comment: [] }), "2099-01-05", {})
|
|
1033
|
-
expect(svc.__queries.length).toBeGreaterThan(first)
|
|
1034
|
-
})
|
|
1035
|
-
})
|
|
1036
|
-
|
|
1037
|
-
describe("所有者経路の内部取得は無制限で行う", () => {
|
|
1038
|
-
it("createDailyReport の内部詳細取得に区分述語が載らない (自報の取得と配信を壊さない)", async () => {
|
|
1039
|
-
// 作成者の可視集合に "Internal" が無くても、自分で作った日報の取得と SSE 配信は
|
|
1040
|
-
// 成立しなければならない。区分の出し分けは受信側 SSE フィルタと次回読み取りが担う
|
|
1041
|
-
const svc = makeService([])
|
|
1042
|
-
|
|
1043
|
-
const created = await svc.createDailyReport(8, "2099-01-05", "tmp")
|
|
1044
|
-
|
|
1045
|
-
// 作成自体は可視集合に関係なく成立する
|
|
1046
|
-
expect(created.reportHubId).toBe(501)
|
|
1047
|
-
// 内部取得は明示 null を渡すため、発行された全クエリに区分述語が一切現れない
|
|
1048
|
-
expect(svc.__queries.length).toBeGreaterThan(0)
|
|
1049
|
-
expect(svc.__queries.every((q) => !(q.whereSql ?? "").includes("[source_type]"))).toBe(true)
|
|
1050
|
-
})
|
|
1051
|
-
})
|
|
1052
|
-
})
|
|
1053
|
-
|
|
1054
|
-
describe("SSE ストリームキーのワイヤ版分離", () => {
|
|
1055
|
-
it("既定キーにワイヤ版の接尾辞が付く", async () => {
|
|
1056
|
-
// ❗ SSE の実体は配備を跨いで残る永続 Redis Stream。スキーマの必須キーを変える改名は
|
|
1057
|
-
// 旧形式エントリを catch-up の safeParse で全滅させるため、版をキーへ焼き込んで
|
|
1058
|
-
// 旧エントリを構造的に到達不能にする
|
|
1059
|
-
const svc = makeService([])
|
|
1060
|
-
expect(svc.streamKey).toBe("daily-report:sse-stream:v2")
|
|
1061
|
-
})
|
|
1062
|
-
|
|
1063
|
-
it("設定キー (env 上書き相当) にも接尾辞が付く — 消費側の設定が版分離を無効化できない", async () => {
|
|
1064
|
-
// ❗ 実配備が使うのはこちらの経路 (env DAILY_REPORT_SSE_STREAM_KEY)。既定キーだけ
|
|
1065
|
-
// テストすると「既定にのみ接尾辞」への退行が素通りする (ミューテーションで実証済み)
|
|
1066
|
-
const svc = makeService([], false, { streamKey: "custom-stream" })
|
|
1067
|
-
expect(svc.streamKey).toBe("custom-stream:v2")
|
|
1068
|
-
})
|
|
1069
|
-
})
|
|
1070
|
-
|
|
1071
|
-
describe("invalidateHubReadCaches の ids epoch 更新", () => {
|
|
1072
|
-
it("ids epoch を進める (ワーカー横断無効化の半分 — プロセス内 prefix だけでは他ワーカーに届かない)", async () => {
|
|
1073
|
-
// ❗ B-1 の 2 行のうち epoch 側のゲート。prefix 無効化のテストは epoch 行を消しても
|
|
1074
|
-
// green のまま (fake epoch ストアが不活性のため) — スパイで直接固定する
|
|
1075
|
-
const svc = makeService([])
|
|
1076
|
-
const spy = vi.spyOn(svc.__epochs, "incrementEpoch")
|
|
1077
|
-
await svc.invalidateHubReadCaches([1], ["2099-01-05"])
|
|
1078
|
-
expect(spy.mock.calls.some((args) => args[0] === "daily-report:ids:epoch")).toBe(true)
|
|
1079
|
-
})
|
|
1080
|
-
})
|
|
1081
|
-
|
|
1082
|
-
describe("invalidateHubReadCaches の一覧 ID 無効化", () => {
|
|
1083
|
-
it("呼び出し後は ids 取得が DB を引き直す (一覧 ID キャッシュも捨てる)", async () => {
|
|
1084
|
-
// ❗ 一覧 ID は「どの行が存在するか」そのもの。詳細・営業日だけ無効化して一覧を
|
|
1085
|
-
// 残すと、行集合を変える取込が一覧にだけ反映されない
|
|
1086
|
-
const svc = makeService([])
|
|
1087
|
-
await svc.getDailyReportIdsByExternalId(UNRESTRICTED_SCOPE, "ext", {})
|
|
1088
|
-
const before = svc.__queries.length
|
|
1089
|
-
await svc.getDailyReportIdsByExternalId(UNRESTRICTED_SCOPE, "ext", {})
|
|
1090
|
-
expect(svc.__queries.length).toBe(before) // キャッシュヒット (発行なし)
|
|
1091
|
-
|
|
1092
|
-
await svc.invalidateHubReadCaches([1], ["2099-01-05"])
|
|
1093
|
-
await svc.getDailyReportIdsByExternalId(UNRESTRICTED_SCOPE, "ext", {})
|
|
1094
|
-
expect(svc.__queries.length).toBeGreaterThan(before)
|
|
1095
|
-
})
|
|
1096
|
-
})
|
|
1097
|
-
|
|
1098
|
-
describe("ids 配列の整列検査 (非点内一貫性の検知)", () => {
|
|
1099
|
-
/** 整列を崩した ids 行 (営業日昇順 = ストリーム順の逆)。 */
|
|
1100
|
-
const disorderedRows = [
|
|
1101
|
-
{ reportHubId: 1, businessDate: "2099-01-03", sourceType: "Internal" },
|
|
1102
|
-
{ reportHubId: 2, businessDate: "2099-01-05", sourceType: "Internal" },
|
|
1103
|
-
{ reportHubId: 3, businessDate: "2099-01-04", sourceType: "Internal" },
|
|
1104
|
-
]
|
|
1105
|
-
|
|
1106
|
-
it("並び順が崩れた結果は整列し直して返す (欠落・重複は直らない — 二次被害の抑止のみ)", async () => {
|
|
1107
|
-
const svc = makeService(disorderedRows)
|
|
1108
|
-
const items = await svc.getDailyReportIdsByExternalId(UNRESTRICTED_SCOPE, "ext", { forceRefresh: true })
|
|
1109
|
-
expect(items.map((i) => i.reportHubId)).toEqual([2, 3, 1])
|
|
1110
|
-
})
|
|
1111
|
-
|
|
1112
|
-
it("崩れていたら警告を出し、整列済みなら出さない", async () => {
|
|
1113
|
-
const warned: unknown[] = []
|
|
1114
|
-
const spy = vi.spyOn(console, "warn").mockImplementation((...args: unknown[]) => {
|
|
1115
|
-
warned.push(args)
|
|
1116
|
-
})
|
|
1117
|
-
try {
|
|
1118
|
-
const bad = makeService(disorderedRows)
|
|
1119
|
-
await bad.getDailyReportIdsByExternalId(UNRESTRICTED_SCOPE, "ext", { forceRefresh: true })
|
|
1120
|
-
expect(warned.some((args) => String(args).includes("not in stream order"))).toBe(true)
|
|
1121
|
-
|
|
1122
|
-
warned.length = 0
|
|
1123
|
-
const good = makeService([{ reportHubId: 2, businessDate: "2099-01-05", sourceType: "Internal" }])
|
|
1124
|
-
await good.getDailyReportIdsByExternalId(UNRESTRICTED_SCOPE, "ext", { forceRefresh: true })
|
|
1125
|
-
expect(warned.some((args) => String(args).includes("not in stream order"))).toBe(false)
|
|
1126
|
-
} finally {
|
|
1127
|
-
spy.mockRestore()
|
|
1128
|
-
}
|
|
1129
|
-
})
|
|
1130
|
-
})
|