-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
-
61
-
62
-
63
-
64
-
65
-
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-
144
-
145
-
146
-
147
-
148
-
149
-
150
-
151
-
152
-
153
-
154
-
155
-
156
-
157
-
158
-
159
-
160
-
161
-
162
-
163
-
164
-
165
-
166
-
167
-
168
-
169
-
170
-
171
-
172
-
173
-
174
-
175
-
176
-
177
-
178
-
179
-
180
-
181
-
182
-
183
-
184
-
185
-
186
-
187
-
188
-
189
-
190
-
191
-
192
-
193
-
194
-
195
-
196
-
197
-
198
-
199
-
200
-
201
-
202
-
203
-
204
-
205
-
206
-
207
-
208
-
209
-
210
-
211
-
212
-
213
-
214
-
215
-
216
-
217
-
218
-
219
-
220
-
221
-
222
-
223
-
224
-
225
-
226
-
227
-
228
-
229
-
230
-
231
-
232
-
233
-
234
-
235
-
236
-
237
-
238
-
239
-
240
-
241
-
242
-
243
-
244
-
245
-
246
-
247
-
248
-
249
-
250
-
251
-
252
-
253
-
254
-
255
-
256
-
257
-
258
-
259
-
260
-
261
-
262
-
263
-
264
-
265
-
266
-
267
-
268
-
269
-
270
-
271
-
272
-
273
-
274
-
275
-
276
-
277
-
278
-
279
-
280
-
281
-
282
-
283
-
284
-
285
-
286
-
287
-
288
-
289
-
290
-
291
-
292
-
293
-
294
-
295
-
296
-
297
-
298
-
299
-
300
-
301
-
302
-
303
-
304
-
305
-
306
-
307
-
308
-
309
-
310
-
311
-
312
-
313
-
314
-
315
-
316
-
317
-
318
-
319
-
320
-
321
-
322
-
323
-
324
-
325
-
326
-
327
-
328
-
329
-
330
-
331
-
332
-
333
-
334
-
335
-
336
-
337
-
338
-
339
-
340
-
341
-
342
-
343
-
344
-
345
-
346
-
347
-
348
-
349
-
350
-
351
-
352
-
353
-
354
-
355
-
356
-
357
-
358
-
359
-
360
-
361
-
362
-
363
-
364
-
365
-
366
-
367
-
368
-
369
-
370
-
371
-
372
-
373
-
374
-
375
-
376
-
377
-
378
-
379
-
380
-
381
-
382
-
383
-
384
-
385
-
386
-
387
-
388
-
389
-
390
-
391
-
392
-
393
-
394
-
395
-
396
-
397
-
398
-
399
-
400
-
401
-
402
-
403
-
404
-
405
-
406
-
407
-
408
-
409
-
410
-
411
-
412
-
413
-
414
-
415
-
416
-
417
-
418
-
419
-
420
-
421
-
422
-
423
-
424
-
425
-
426
-
427
-
428
-
429
-
430
-
431
-
432
-
433
-
434
-
435
-
436
-
437
-
438
-
439
-
440
-
441
-
442
-
443
-
444
-
445
-
446
-
447
-
448
-
449
-
450
-
451
-
452
-
453
-
454
-
455
-
456
-
457
-
458
-
459
-
460
-
461
-
462
-
463
-
464
-
465
-
466
-
467
-
468
-
469
-
470
-
471
-
472
-
473
-
474
-
475
-
476
-
477
-
478
-
479
-
480
-
481
-
482
-
483
-
484
-
485
-
486
-
487
-
488
-
489
-
490
-
491
-
492
-
493
-
494
-
495
-
496
-
497
-
498
-
499
-
500
-
501
-
502
-
503
-
504
-
505
-
506
-
507
-
508
-
509
-
510
-
511
-
512
-
513
-
514
-
515
-
516
-
517
-
518
-
519
-
520
-
521
-
522
-
523
-
524
-
525
-
526
-
527
-
528
-
529
-
530
-
531
-
532
-
533
-
534
-
535
-
536
-
537
-
538
-
539
-
540
-
541
-
542
-
543
-
544
-
545
-
546
-
547
-
548
-
549
-
550
-
551
-
552
-
553
-
554
-
555
-
556
-
557
-
558
-
559
-
560
-
561
-
562
-
563
-
564
// SPDX-FileCopyrightText: 2024 Shota FUJI <pockawoooh@gmail.com>
// SPDX-License-Identifier: AGPL-3.0-only
import "../../../polyfill.ts";
import * as proto from "@bufbuild/protobuf";
import { tz } from "@date-fns/tz";
import { CaretLeftIcon, CaretRightIcon, PersonIcon } from "@radix-ui/react-icons";
import {
Avatar,
Box,
Container,
ContextMenu,
Dialog,
Flex,
Grid,
IconButton,
Link,
ScrollArea,
Text,
VisuallyHidden,
} from "@radix-ui/themes";
import { DateSchema } from "@yamori/proto/yamori/type/v1/date_pb.js";
import { WorkspaceSchema } from "@yamori/proto/yamori/workspace/v1/workspace_pb.js";
import { GetRequestSchema } from "@yamori/proto/yamori/workspace/v1/get_request_pb.js";
import { GetResponseSchema } from "@yamori/proto/yamori/workspace/v1/get_response_pb.js";
import { ListRequestSchema } from "@yamori/proto/yamori/worker/v1/list_request_pb.js";
import { ListResponseSchema } from "@yamori/proto/yamori/worker/v1/list_response_pb.js";
import { WorkerSchema } from "@yamori/proto/yamori/worker/v1/worker_pb.js";
import { PaidLeaveProvisionSchema } from "@yamori/proto/yamori/worker/v1/paid_leave_provision_pb.js";
import { WorkRecordSchema } from "@yamori/proto/yamori/work_record/v1/work_record_pb.js";
import {
addMonths,
subMonths,
startOfMonth,
endOfMonth,
eachDayOfInterval,
} from "date-fns";
import { type FC, use, useEffect, useMemo, useRef, useState } from "react";
import { WorkRecordBadges } from "../../../components/WorkRecordBadges.tsx";
import { NavigationContext, URLContext } from "../../../contexts/Router.tsx";
import { useMethodQuery } from "../../../contexts/Service.tsx";
import { IllegalMessageError } from "../../../errors/IllegalMessageError.ts";
import { fromProtoDate, toProtoDate, isSameDate } from "../../../helpers.ts";
import * as workerDashboard from "../workers/:id/Dashboard.tsx";
import { Layout } from "../Layout.tsx";
import { Menu } from "./Menu.tsx";
import { RecordEditDialog, type RecordEditDialogProps } from "./RecordEditDialog.ts";
import * as Spreadsheet from "./Spreadsheet.ts";
import { useActions } from "./useActions.ts";
import css from "./page.module.css";
export const Title: FC = () => "カレンダー";
function addMonthToSearchParams(
month: proto.MessageShape<typeof DateSchema>,
base?: URLSearchParams,
): URLSearchParams {
const params = new URLSearchParams(base);
params.set("month", `${month.year}-${month.month}`);
return params;
}
export interface HrefInput {
workspace: proto.MessageShape<typeof WorkspaceSchema>;
month?: proto.MessageShape<typeof DateSchema>;
}
export function href({ workspace, month }: HrefInput): string {
if (!workspace.id) {
return "/";
}
const base = `/${workspace.id.value}/calendar`;
if (!month) {
return base;
}
return base + "?" + addMonthToSearchParams(month).toString();
}
export const pattern = new URLPattern({
pathname: "/:workspace/calendar",
});
// TODO: どこか共通のファイルで定義する
const TZ = "Asia/Tokyo";
const weekdayFormatter = new Intl.DateTimeFormat(navigator.language, {
weekday: "short",
});
interface BodyProps {
workspace: proto.MessageShape<typeof WorkspaceSchema>;
month: proto.MessageShape<typeof DateSchema>;
onChangeMonth(month: proto.MessageShape<typeof DateSchema>): void;
}
const Body: FC<BodyProps> = ({ workspace, month, onChangeMonth }) => {
const { start, end } = useMemo(() => {
const d = fromProtoDate(month);
return {
start: toProtoDate(startOfMonth(d, { in: tz(TZ) })),
end: toProtoDate(endOfMonth(d, { in: tz(TZ) })),
} as const;
}, [month]);
const wsDetails = useMethodQuery({
service: "yamori.workspace.v1.WorkspaceService",
method: "Get",
request: {
schema: GetRequestSchema,
data: {
workspaceId: workspace.id,
readMask: {
fields: [
WorkspaceSchema.field.abbreviations.number,
WorkspaceSchema.field.leaveDefinitions.number,
WorkspaceSchema.field.id.number,
],
},
},
},
response: {
schema: GetResponseSchema,
},
mapResponse(resp) {
switch (resp.result.case) {
case "ok":
return resp.result.value;
case undefined:
throw new IllegalMessageError(resp);
default:
throw resp.result.value;
}
},
});
const query = useMethodQuery({
service: "yamori.worker.v1.WorkerService",
method: "List",
request: {
schema: ListRequestSchema,
data: {
workspaceId: workspace.id,
workRecordFilter: {
since: start,
until: end,
},
paidLeaveProvisionFilter: {
providedAtUntil: end,
expiresAtSince: start,
},
readMask: {
fields: [
WorkerSchema.field.id.number,
WorkerSchema.field.displayName.number,
WorkerSchema.field.writeWorkRecordKey.number,
WorkerSchema.field.providePaidLeaveKey.number,
WorkerSchema.field.workRecords.number,
WorkerSchema.field.paidLeaveProvisions.number,
],
paidLeaveProvisionsMask: {
fields: [
PaidLeaveProvisionSchema.field.providedAt.number,
PaidLeaveProvisionSchema.field.expiresAt.number,
PaidLeaveProvisionSchema.field.remainingDays.number,
PaidLeaveProvisionSchema.field.isHalvedDayRemaining.number,
],
},
workRecordsMask: {
fields: [
WorkRecordSchema.field.date.number,
WorkRecordSchema.field.dayWhole.number,
WorkRecordSchema.field.dayHalved.number,
],
},
},
},
},
response: {
schema: ListResponseSchema,
},
mapResponse(resp) {
switch (resp.result.case) {
case "ok":
return resp.result.value.workers;
case undefined:
throw new IllegalMessageError(resp);
default:
throw resp.result.value;
}
},
});
const dates = useMemo(() => {
return eachDayOfInterval(
{
start: fromProtoDate(start),
end: fromProtoDate(end),
},
{
in: tz(TZ),
},
);
}, [start, end]);
const [selection, setSelection] = useState(() => Spreadsheet.empty());
// 見えていない別の月の選択状態を保持してもわかりづらいので、表示月が
// 変わったタイミングで選択を解除する。
useEffect(() => {
setSelection(Spreadsheet.empty());
}, [month]);
const scrollAreaRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!scrollAreaRef.current) {
return;
}
scrollAreaRef.current.scrollLeft = 0;
}, [month]);
const actions = useActions({
workspace,
workers: query.data || [],
dates,
selection,
onWorkRecordUpdated() {
query.refetch();
},
});
const actionsRef = useRef(actions);
actionsRef.current = actions;
const rows = query.data?.length ?? 0;
const columns = dates.length;
useEffect(() => {
const listener = async (event: KeyboardEvent) => {
if (event.isComposing || event.ctrlKey || event.shiftKey || event.metaKey) {
return;
}
let action: () => Promise<void>;
switch (event.key) {
case "1":
action = actionsRef.current.markAsWorked;
break;
case "2":
action = actionsRef.current.markAsDayOff;
break;
case "3":
action = actionsRef.current.markAsAbsent;
break;
case "4":
action = actionsRef.current.markAsPaidLeave;
break;
default:
return;
}
event.preventDefault();
event.stopPropagation();
await action();
// TODO: スプレッドシート側で次に送る動作を定義する
setSelection((prev) => {
if (!prev.cursor) {
return prev;
}
const next: Spreadsheet.GridCell =
prev.cursor.column === columns - 1
? {
row: prev.cursor.row === rows - 1 ? 0 : prev.cursor.row + 1,
column: 0,
}
: {
row: prev.cursor.row,
column: prev.cursor.column + 1,
};
// TODO: 外に出す
const nextEl = document.querySelector(
`[data-gridrow="${next.row}"][data-gridcol="${next.column}"]`,
);
if (nextEl instanceof HTMLElement) {
nextEl.focus();
}
return {
cells: [next],
cursor: next,
expandingTo: null,
committed: [],
};
});
};
document.addEventListener("keyup", listener);
return () => void document.removeEventListener("keyup", listener);
}, [rows, columns]);
const [editDialogPayload, setEditDialogPayload] = useState<Pick<
RecordEditDialogProps,
"worker" | "record"
> | null>(null);
return (
<Dialog.Root
open={!!editDialogPayload}
onOpenChange={(isOpen) => {
if (!isOpen) {
setEditDialogPayload(null);
}
}}
>
<Container px="2" py="4" size="2">
<Flex align="center" gap="1">
<IconButton
variant="soft"
size="2"
onClick={() => {
onChangeMonth(toProtoDate(subMonths(fromProtoDate(month), 1)));
}}
>
<CaretLeftIcon />
<VisuallyHidden>前の月へ</VisuallyHidden>
</IconButton>
<Text weight="bold" size="2" align="center" style={{ minWidth: "6rem" }}>
{month.year}年{month.month}月
</Text>
<IconButton
variant="soft"
size="2"
onClick={() => {
onChangeMonth(toProtoDate(addMonths(fromProtoDate(month), 1)));
}}
>
<CaretRightIcon />
<VisuallyHidden>次の月へ</VisuallyHidden>
</IconButton>
<Box flexGrow="1" flexShrink="1" />
<Menu
disabled={selection.cells.length === 0}
actions={actions}
workspaceID={workspace.id}
/>
</Flex>
</Container>
<Box mt="2" pl={{ md: "2" }}>
<ScrollArea ref={scrollAreaRef} scrollbars="horizontal" size="2">
<Spreadsheet.Root
asChild
selection={selection}
onSelectionChange={setSelection}
rows={rows}
columns={columns}
>
<Grid columns={`max-content repeat(${dates.length}, 3rem)`} pb="4">
<Spreadsheet.Row className={css.row} row={-1}>
<Spreadsheet.ColumnHeader asChild>
<Box
className={`${css.rowHeaderCell} ${css.columnHeaderCell}`}
position="sticky"
left="0"
top="0"
style={{ backgroundColor: "var(--color-background)", zIndex: 5 }}
/>
</Spreadsheet.ColumnHeader>
{dates.map((d) => (
<Spreadsheet.ColumnHeader key={+d} asChild>
<Flex
className={css.rowHeaderCell}
position="sticky"
top="0"
direction="column"
align="center"
justify="center"
p="1"
style={{ zIndex: 1 }}
>
<Text
size="1"
weight="bold"
color={
d.getDay() === 0 ? "red" : d.getDay() === 6 ? "blue" : "gray"
}
>
{weekdayFormatter.format(d)}
</Text>
<Text size="3" weight="bold">
{d.getDate()}
</Text>
</Flex>
</Spreadsheet.ColumnHeader>
))}
</Spreadsheet.Row>
{query.data?.map((worker, workerIndex) => {
return (
<Spreadsheet.Row
key={worker.id?.value}
className={css.row}
row={workerIndex}
>
<Spreadsheet.RowHeader asChild>
<Flex
asChild
className={css.columnHeaderCell}
position="sticky"
left="0"
style={{ backgroundColor: "var(--color-background)", zIndex: 3 }}
align="center"
gap="2"
p="2"
>
<Link href={workerDashboard.href({ workspace, worker })}>
<Avatar
size="2"
fallback={worker.displayName[0] || <PersonIcon />}
/>
<Text>{worker.displayName}</Text>
</Link>
</Flex>
</Spreadsheet.RowHeader>
{dates.map((date, dateIndex) => {
const d = toProtoDate(date);
const record = worker.workRecords.find(
(record) => record.date && isSameDate(record.date, d),
);
const contents = record && (
<WorkRecordBadges
abbreviations={wsDetails.data?.abbreviations}
workRecord={record}
/>
);
return (
<ContextMenu.Root key={+date}>
<ContextMenu.Trigger>
<Spreadsheet.Cell asChild column={dateIndex}>
<Flex
className={`${css.recordCell} ${css.writableCell}`}
direction="column"
gap="1"
p="1"
minWidth="0"
>
{contents}
</Flex>
</Spreadsheet.Cell>
</ContextMenu.Trigger>
<ContextMenu.Content>
<ContextMenu.Item
onSelect={() => {
setEditDialogPayload({
worker,
record:
record ||
proto.create(WorkRecordSchema, {
date: d,
}),
});
}}
>
詳細
</ContextMenu.Item>
</ContextMenu.Content>
</ContextMenu.Root>
);
})}
</Spreadsheet.Row>
);
})}
</Grid>
</Spreadsheet.Root>
</ScrollArea>
</Box>
{wsDetails.data && editDialogPayload && (
<RecordEditDialog
workspace={wsDetails.data}
{...editDialogPayload}
onSuccessfullyRecordEdited={() => {
query.refetch();
setEditDialogPayload(null);
}}
/>
)}
</Dialog.Root>
);
};
export interface PageProps {
workspace: proto.MessageShape<typeof WorkspaceSchema>;
}
export const Page: FC<PageProps> = ({ workspace }) => {
const navigation = use(NavigationContext);
const url = use(URLContext);
const searchParams = useMemo(() => new URLSearchParams(url.search), [url.search]);
const month = useMemo<proto.MessageShape<typeof DateSchema>>(() => {
const param = searchParams.get("month");
if (!param) {
return toProtoDate(Date.now());
}
const tokens = param.split("-").map((s) => parseInt(s, 10));
if (tokens.length !== 2 || tokens.some((t) => !Number.isFinite(t))) {
return toProtoDate(Date.now());
}
return proto.create(DateSchema, {
year: tokens[0],
month: tokens[1],
day: 1,
});
}, [searchParams]);
// ブラウザのクエリパラメータと month が違う場合は同期させる
useEffect(() => {
const next = addMonthToSearchParams(month, searchParams);
if (next.toString() === searchParams.toString()) {
return;
}
navigation.replace(href({ workspace, month }));
}, [searchParams, month]);
return (
<Layout workspace={workspace} title={<Title />}>
<Body
workspace={workspace}
month={month}
onChangeMonth={(month) => {
navigation.replace(
href({
workspace,
month,
}),
);
}}
/>
</Layout>
);
};