@things-factory/figure-service 10.1.3 → 10.1.4

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 (34) hide show
  1. package/dist-server/service/figure/event-subscriber.d.ts +21 -0
  2. package/dist-server/service/figure/event-subscriber.js +51 -0
  3. package/dist-server/service/figure/event-subscriber.js.map +1 -0
  4. package/dist-server/service/figure/figure-history.d.ts +43 -0
  5. package/dist-server/service/figure/figure-history.js +155 -0
  6. package/dist-server/service/figure/figure-history.js.map +1 -0
  7. package/dist-server/service/figure/figure-mutation.d.ts +39 -0
  8. package/dist-server/service/figure/figure-mutation.js +153 -1
  9. package/dist-server/service/figure/figure-mutation.js.map +1 -1
  10. package/dist-server/service/figure/figure-query.d.ts +15 -0
  11. package/dist-server/service/figure/figure-query.js +47 -0
  12. package/dist-server/service/figure/figure-query.js.map +1 -1
  13. package/dist-server/service/figure/figure-type.d.ts +0 -1
  14. package/dist-server/service/figure/figure-type.js +0 -4
  15. package/dist-server/service/figure/figure-type.js.map +1 -1
  16. package/dist-server/service/figure/figure.d.ts +9 -0
  17. package/dist-server/service/figure/figure.js +15 -3
  18. package/dist-server/service/figure/figure.js.map +1 -1
  19. package/dist-server/service/figure/index.d.ts +4 -1
  20. package/dist-server/service/figure/index.js +5 -2
  21. package/dist-server/service/figure/index.js.map +1 -1
  22. package/dist-server/service/index.d.ts +6 -2
  23. package/dist-server/service/index.js +17 -2
  24. package/dist-server/service/index.js.map +1 -1
  25. package/dist-server/tsconfig.tsbuildinfo +1 -0
  26. package/package.json +4 -3
  27. package/server/service/figure/event-subscriber.ts +49 -0
  28. package/server/service/figure/figure-history.ts +130 -0
  29. package/server/service/figure/figure-mutation.ts +157 -1
  30. package/server/service/figure/figure-query.ts +37 -0
  31. package/server/service/figure/figure-type.ts +6 -2
  32. package/server/service/figure/figure.ts +15 -3
  33. package/server/service/figure/index.ts +4 -1
  34. package/server/service/index.ts +23 -2
@@ -0,0 +1,21 @@
1
+ import { HistoryEntitySubscriber } from '@operato/typeorm-history';
2
+ import { Figure } from './figure.js';
3
+ import { FigureHistory } from './figure-history.js';
4
+ /**
5
+ * 판본을 남긴다 — **발행된 저장에만.**
6
+ *
7
+ * `@operato/typeorm-history` 는 원래 모든 저장을 베낀다. 그런데 도형은 저작 중에 수십 번 저장되고,
8
+ * 그 전부를 남기면 판본 목록이 「내가 오늘 몇 번 눌렀나」가 된다. 사람이 판이라고 부르는 것은
9
+ * **발행한 것**이므로 그때만 베낀다. board 가 같은 규칙으로 돈다(`board-service` 의 같은 이름 파일).
10
+ *
11
+ * 발행 메모는 Figure 의 칸이 아니다. `releaseFigure` 가 저장할 엔티티에 `__releaseComment` 로 얹어
12
+ * 두면 여기서 판본의 `comment` 로 옮긴다 — 메모는 그 판의 것이지 도형의 것이 아니다.
13
+ */
14
+ export declare class FigureHistoryEntitySubscriber extends HistoryEntitySubscriber<Figure, FigureHistory> {
15
+ get entity(): typeof Figure;
16
+ get historyEntity(): typeof FigureHistory;
17
+ beforeInsertHistory(history: FigureHistory, entity: Figure): FigureHistory;
18
+ beforeUpdateHistory(history: FigureHistory, entity: Figure): FigureHistory;
19
+ afterInsert(event: any): Promise<void>;
20
+ afterUpdate(event: any): Promise<void>;
21
+ }
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FigureHistoryEntitySubscriber = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const typeorm_1 = require("typeorm");
6
+ const typeorm_history_1 = require("@operato/typeorm-history");
7
+ const figure_js_1 = require("./figure.js");
8
+ const figure_history_js_1 = require("./figure-history.js");
9
+ /**
10
+ * 판본을 남긴다 — **발행된 저장에만.**
11
+ *
12
+ * `@operato/typeorm-history` 는 원래 모든 저장을 베낀다. 그런데 도형은 저작 중에 수십 번 저장되고,
13
+ * 그 전부를 남기면 판본 목록이 「내가 오늘 몇 번 눌렀나」가 된다. 사람이 판이라고 부르는 것은
14
+ * **발행한 것**이므로 그때만 베낀다. board 가 같은 규칙으로 돈다(`board-service` 의 같은 이름 파일).
15
+ *
16
+ * 발행 메모는 Figure 의 칸이 아니다. `releaseFigure` 가 저장할 엔티티에 `__releaseComment` 로 얹어
17
+ * 두면 여기서 판본의 `comment` 로 옮긴다 — 메모는 그 판의 것이지 도형의 것이 아니다.
18
+ */
19
+ let FigureHistoryEntitySubscriber = class FigureHistoryEntitySubscriber extends typeorm_history_1.HistoryEntitySubscriber {
20
+ get entity() {
21
+ return figure_js_1.Figure;
22
+ }
23
+ get historyEntity() {
24
+ return figure_history_js_1.FigureHistory;
25
+ }
26
+ beforeInsertHistory(history, entity) {
27
+ ;
28
+ history.comment = entity.__releaseComment ?? null;
29
+ return history;
30
+ }
31
+ beforeUpdateHistory(history, entity) {
32
+ ;
33
+ history.comment = entity.__releaseComment ?? null;
34
+ return history;
35
+ }
36
+ async afterInsert(event) {
37
+ if (event.entity?.state == 'released') {
38
+ await super.afterInsert(event);
39
+ }
40
+ }
41
+ async afterUpdate(event) {
42
+ if (event.entity?.state == 'released') {
43
+ await super.afterUpdate(event);
44
+ }
45
+ }
46
+ };
47
+ exports.FigureHistoryEntitySubscriber = FigureHistoryEntitySubscriber;
48
+ exports.FigureHistoryEntitySubscriber = FigureHistoryEntitySubscriber = tslib_1.__decorate([
49
+ (0, typeorm_1.EventSubscriber)()
50
+ ], FigureHistoryEntitySubscriber);
51
+ //# sourceMappingURL=event-subscriber.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-subscriber.js","sourceRoot":"","sources":["../../../server/service/figure/event-subscriber.ts"],"names":[],"mappings":";;;;AAAA,qCAAyC;AAEzC,8DAAkE;AAElE,2CAAoC;AACpC,2DAAmD;AAEnD;;;;;;;;;GASG;AAEI,IAAM,6BAA6B,GAAnC,MAAM,6BAA8B,SAAQ,yCAA8C;IAC/F,IAAW,MAAM;QACf,OAAO,kBAAM,CAAA;IACf,CAAC;IAED,IAAW,aAAa;QACtB,OAAO,iCAAa,CAAA;IACtB,CAAC;IAEM,mBAAmB,CAAC,OAAsB,EAAE,MAAc;QAC/D,CAAC;QAAC,OAAe,CAAC,OAAO,GAAI,MAAc,CAAC,gBAAgB,IAAI,IAAI,CAAA;QACpE,OAAO,OAAO,CAAA;IAChB,CAAC;IAEM,mBAAmB,CAAC,OAAsB,EAAE,MAAc;QAC/D,CAAC;QAAC,OAAe,CAAC,OAAO,GAAI,MAAc,CAAC,gBAAgB,IAAI,IAAI,CAAA;QACpE,OAAO,OAAO,CAAA;IAChB,CAAC;IAEM,KAAK,CAAC,WAAW,CAAC,KAAU;QACjC,IAAI,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,UAAU,EAAE,CAAC;YACtC,MAAM,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;QAChC,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,WAAW,CAAC,KAAU;QACjC,IAAI,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,UAAU,EAAE,CAAC;YACtC,MAAM,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;QAChC,CAAC;IACH,CAAC;CACF,CAAA;AA9BY,sEAA6B;wCAA7B,6BAA6B;IADzC,IAAA,yBAAe,GAAE;GACL,6BAA6B,CA8BzC","sourcesContent":["import { EventSubscriber } from 'typeorm'\n\nimport { HistoryEntitySubscriber } from '@operato/typeorm-history'\n\nimport { Figure } from './figure.js'\nimport { FigureHistory } from './figure-history.js'\n\n/**\n * 판본을 남긴다 — **발행된 저장에만.**\n *\n * `@operato/typeorm-history` 는 원래 모든 저장을 베낀다. 그런데 도형은 저작 중에 수십 번 저장되고,\n * 그 전부를 남기면 판본 목록이 「내가 오늘 몇 번 눌렀나」가 된다. 사람이 판이라고 부르는 것은\n * **발행한 것**이므로 그때만 베낀다. board 가 같은 규칙으로 돈다(`board-service` 의 같은 이름 파일).\n *\n * 발행 메모는 Figure 의 칸이 아니다. `releaseFigure` 가 저장할 엔티티에 `__releaseComment` 로 얹어\n * 두면 여기서 판본의 `comment` 로 옮긴다 — 메모는 그 판의 것이지 도형의 것이 아니다.\n */\n@EventSubscriber()\nexport class FigureHistoryEntitySubscriber extends HistoryEntitySubscriber<Figure, FigureHistory> {\n public get entity() {\n return Figure\n }\n\n public get historyEntity() {\n return FigureHistory\n }\n\n public beforeInsertHistory(history: FigureHistory, entity: Figure): FigureHistory {\n ;(history as any).comment = (entity as any).__releaseComment ?? null\n return history\n }\n\n public beforeUpdateHistory(history: FigureHistory, entity: Figure): FigureHistory {\n ;(history as any).comment = (entity as any).__releaseComment ?? null\n return history\n }\n\n public async afterInsert(event: any): Promise<void> {\n if (event.entity?.state == 'released') {\n await super.afterInsert(event)\n }\n }\n\n public async afterUpdate(event: any): Promise<void> {\n if (event.entity?.state == 'released') {\n await super.afterUpdate(event)\n }\n }\n}\n"]}
@@ -0,0 +1,43 @@
1
+ import { HistoryActionType, HistoryEntityInterface } from '@operato/typeorm-history';
2
+ import { User } from '@things-factory/auth-base';
3
+ import { Domain } from '@things-factory/shell';
4
+ import { Figure } from './figure.js';
5
+ /**
6
+ * 발행된 판 하나 — **발행할 때만 남는다.**
7
+ *
8
+ * 저작 중 저장은 여기 오지 않는다. 스냅샷을 뜨는 subscriber 가 `state === 'released'` 인 저장에만
9
+ * 움직인다(`event-subscriber.ts`) — board 가 같은 규칙으로 돈다.
10
+ *
11
+ * ## 왜 통째로 베끼나
12
+ *
13
+ * 판을 되세우려면 그때의 정본만으로는 모자란다. 이름·분류·그림·비용까지 함께 있어야 「그 판이
14
+ * 무엇이었나」를 보여 주고 되돌릴 수 있다. 파생값(점수·삼각형·묶음)도 같이 둔다 — 다시 계산하면
15
+ * 형식이 바뀐 오늘의 값이 나오고, 그것은 그 판의 값이 아니다.
16
+ */
17
+ export declare class FigureHistory implements HistoryEntityInterface<Figure> {
18
+ readonly id: string;
19
+ version?: number;
20
+ domain?: Domain;
21
+ domainId?: string;
22
+ type?: string;
23
+ name?: string;
24
+ description?: string;
25
+ category?: string;
26
+ state?: 'draft' | 'released';
27
+ source?: string;
28
+ properties?: string;
29
+ thumbnail?: string;
30
+ score?: number;
31
+ triangles?: number;
32
+ groups?: number;
33
+ comment?: string;
34
+ createdAt?: Date;
35
+ updatedAt?: Date;
36
+ creator?: User;
37
+ creatorId?: string;
38
+ updater?: User;
39
+ updaterId?: string;
40
+ deletedAt?: Date;
41
+ originalId: string;
42
+ action: HistoryActionType;
43
+ }
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FigureHistory = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const type_graphql_1 = require("type-graphql");
6
+ const typeorm_1 = require("typeorm");
7
+ const typeorm_history_1 = require("@operato/typeorm-history");
8
+ const auth_base_1 = require("@things-factory/auth-base");
9
+ const shell_1 = require("@things-factory/shell");
10
+ /**
11
+ * 발행된 판 하나 — **발행할 때만 남는다.**
12
+ *
13
+ * 저작 중 저장은 여기 오지 않는다. 스냅샷을 뜨는 subscriber 가 `state === 'released'` 인 저장에만
14
+ * 움직인다(`event-subscriber.ts`) — board 가 같은 규칙으로 돈다.
15
+ *
16
+ * ## 왜 통째로 베끼나
17
+ *
18
+ * 판을 되세우려면 그때의 정본만으로는 모자란다. 이름·분류·그림·비용까지 함께 있어야 「그 판이
19
+ * 무엇이었나」를 보여 주고 되돌릴 수 있다. 파생값(점수·삼각형·묶음)도 같이 둔다 — 다시 계산하면
20
+ * 형식이 바뀐 오늘의 값이 나오고, 그것은 그 판의 값이 아니다.
21
+ */
22
+ let FigureHistory = class FigureHistory {
23
+ constructor() {
24
+ this.version = 1;
25
+ }
26
+ };
27
+ exports.FigureHistory = FigureHistory;
28
+ tslib_1.__decorate([
29
+ (0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
30
+ (0, type_graphql_1.Field)(type => type_graphql_1.ID, { description: 'Unique identifier for this history record.' }),
31
+ tslib_1.__metadata("design:type", String)
32
+ ], FigureHistory.prototype, "id", void 0);
33
+ tslib_1.__decorate([
34
+ (0, typeorm_1.Column)({ nullable: true, default: 1 }),
35
+ (0, type_graphql_1.Field)(type => type_graphql_1.Int, { nullable: true, description: 'The published version number this record holds.' }),
36
+ tslib_1.__metadata("design:type", Number)
37
+ ], FigureHistory.prototype, "version", void 0);
38
+ tslib_1.__decorate([
39
+ (0, typeorm_1.ManyToOne)(type => shell_1.Domain),
40
+ (0, type_graphql_1.Field)(type => shell_1.Domain, { nullable: true, description: 'The domain the figure belonged to.' }),
41
+ tslib_1.__metadata("design:type", shell_1.Domain)
42
+ ], FigureHistory.prototype, "domain", void 0);
43
+ tslib_1.__decorate([
44
+ (0, typeorm_1.RelationId)((history) => history.domain),
45
+ tslib_1.__metadata("design:type", String)
46
+ ], FigureHistory.prototype, "domainId", void 0);
47
+ tslib_1.__decorate([
48
+ (0, typeorm_1.Column)({ nullable: true }),
49
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The stored identifier of the figure. It never changes.' }),
50
+ tslib_1.__metadata("design:type", String)
51
+ ], FigureHistory.prototype, "type", void 0);
52
+ tslib_1.__decorate([
53
+ (0, typeorm_1.Column)({ nullable: true }),
54
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The display name at this version.' }),
55
+ tslib_1.__metadata("design:type", String)
56
+ ], FigureHistory.prototype, "name", void 0);
57
+ tslib_1.__decorate([
58
+ (0, typeorm_1.Column)({ nullable: true }),
59
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The description at this version.' }),
60
+ tslib_1.__metadata("design:type", String)
61
+ ], FigureHistory.prototype, "description", void 0);
62
+ tslib_1.__decorate([
63
+ (0, typeorm_1.Column)({ nullable: true }),
64
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The classification code at this version.' }),
65
+ tslib_1.__metadata("design:type", String)
66
+ ], FigureHistory.prototype, "category", void 0);
67
+ tslib_1.__decorate([
68
+ (0, typeorm_1.Column)({ nullable: true }),
69
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The lifecycle state recorded with this version.' }),
70
+ tslib_1.__metadata("design:type", String)
71
+ ], FigureHistory.prototype, "state", void 0);
72
+ tslib_1.__decorate([
73
+ (0, typeorm_1.Column)({ nullable: true, ...(0, shell_1.longTextColumn)() }),
74
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The canonical FigureSource JSON at this version.' }),
75
+ tslib_1.__metadata("design:type", String)
76
+ ], FigureHistory.prototype, "source", void 0);
77
+ tslib_1.__decorate([
78
+ (0, typeorm_1.Column)({ nullable: true, ...(0, shell_1.longTextColumn)() }),
79
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The master-data field definition at this version.' }),
80
+ tslib_1.__metadata("design:type", String)
81
+ ], FigureHistory.prototype, "properties", void 0);
82
+ tslib_1.__decorate([
83
+ (0, typeorm_1.Column)({ nullable: true, ...(0, shell_1.longTextColumn)() }),
84
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The thumbnail as it looked at this version.' }),
85
+ tslib_1.__metadata("design:type", String)
86
+ ], FigureHistory.prototype, "thumbnail", void 0);
87
+ tslib_1.__decorate([
88
+ (0, typeorm_1.Column)({ type: 'float', nullable: true }),
89
+ (0, type_graphql_1.Field)(type => type_graphql_1.Float, { nullable: true, description: 'Reuse score as computed at this version.' }),
90
+ tslib_1.__metadata("design:type", Number)
91
+ ], FigureHistory.prototype, "score", void 0);
92
+ tslib_1.__decorate([
93
+ (0, typeorm_1.Column)({ nullable: true }),
94
+ (0, type_graphql_1.Field)(type => type_graphql_1.Int, { nullable: true, description: 'Triangle count at this version.' }),
95
+ tslib_1.__metadata("design:type", Number)
96
+ ], FigureHistory.prototype, "triangles", void 0);
97
+ tslib_1.__decorate([
98
+ (0, typeorm_1.Column)({ nullable: true }),
99
+ (0, type_graphql_1.Field)(type => type_graphql_1.Int, { nullable: true, description: 'Material group count at this version.' }),
100
+ tslib_1.__metadata("design:type", Number)
101
+ ], FigureHistory.prototype, "groups", void 0);
102
+ tslib_1.__decorate([
103
+ (0, typeorm_1.Column)({ nullable: true, ...(0, shell_1.longTextColumn)() }),
104
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The note left when this version was released.' }),
105
+ tslib_1.__metadata("design:type", String)
106
+ ], FigureHistory.prototype, "comment", void 0);
107
+ tslib_1.__decorate([
108
+ (0, typeorm_1.Column)({ nullable: true }),
109
+ (0, type_graphql_1.Field)({ nullable: true, description: 'When the original figure was created.' }),
110
+ tslib_1.__metadata("design:type", Date)
111
+ ], FigureHistory.prototype, "createdAt", void 0);
112
+ tslib_1.__decorate([
113
+ (0, typeorm_1.Column)({ nullable: true }),
114
+ (0, type_graphql_1.Field)({ nullable: true, description: 'When the figure was saved at this version.' }),
115
+ tslib_1.__metadata("design:type", Date)
116
+ ], FigureHistory.prototype, "updatedAt", void 0);
117
+ tslib_1.__decorate([
118
+ (0, typeorm_1.ManyToOne)(type => auth_base_1.User, { nullable: true }),
119
+ (0, type_graphql_1.Field)(type => auth_base_1.User, { nullable: true, description: 'Who created the original figure.' }),
120
+ tslib_1.__metadata("design:type", auth_base_1.User)
121
+ ], FigureHistory.prototype, "creator", void 0);
122
+ tslib_1.__decorate([
123
+ (0, typeorm_1.RelationId)((history) => history.creator),
124
+ tslib_1.__metadata("design:type", String)
125
+ ], FigureHistory.prototype, "creatorId", void 0);
126
+ tslib_1.__decorate([
127
+ (0, typeorm_1.ManyToOne)(type => auth_base_1.User, { nullable: true }),
128
+ (0, type_graphql_1.Field)(type => auth_base_1.User, { nullable: true, description: 'Who released this version.' }),
129
+ tslib_1.__metadata("design:type", auth_base_1.User)
130
+ ], FigureHistory.prototype, "updater", void 0);
131
+ tslib_1.__decorate([
132
+ (0, typeorm_1.RelationId)((history) => history.updater),
133
+ tslib_1.__metadata("design:type", String)
134
+ ], FigureHistory.prototype, "updaterId", void 0);
135
+ tslib_1.__decorate([
136
+ (0, typeorm_1.Column)({ nullable: true }),
137
+ (0, type_graphql_1.Field)({ nullable: true, description: 'When the original figure was deleted, if it was.' }),
138
+ tslib_1.__metadata("design:type", Date)
139
+ ], FigureHistory.prototype, "deletedAt", void 0);
140
+ tslib_1.__decorate([
141
+ (0, typeorm_history_1.HistoryOriginalIdColumn)(),
142
+ (0, type_graphql_1.Field)({ description: 'The id of the figure this version belongs to.' }),
143
+ tslib_1.__metadata("design:type", String)
144
+ ], FigureHistory.prototype, "originalId", void 0);
145
+ tslib_1.__decorate([
146
+ (0, typeorm_history_1.HistoryActionColumn)({ nullable: false, type: 'varchar', length: 10 }),
147
+ (0, type_graphql_1.Field)(type => String, { description: 'What produced this record (created · updated · deleted).' }),
148
+ tslib_1.__metadata("design:type", String)
149
+ ], FigureHistory.prototype, "action", void 0);
150
+ exports.FigureHistory = FigureHistory = tslib_1.__decorate([
151
+ (0, typeorm_1.Entity)(),
152
+ (0, typeorm_1.Index)('ix_figure_history_0', (history) => [history.originalId, history.version], { unique: true }),
153
+ (0, type_graphql_1.ObjectType)({ description: 'A released version of a figure — one row per release.' })
154
+ ], FigureHistory);
155
+ //# sourceMappingURL=figure-history.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"figure-history.js","sourceRoot":"","sources":["../../../server/service/figure/figure-history.ts"],"names":[],"mappings":";;;;AAAA,+CAAgE;AAChE,qCAA8F;AAE9F,8DAKiC;AACjC,yDAAgD;AAChD,iDAA8D;AAI9D;;;;;;;;;;;GAWG;AAII,IAAM,aAAa,GAAnB,MAAM,aAAa;IAAnB;QAOL,YAAO,GAAY,CAAC,CAAA;IA6FtB,CAAC;CAAA,CAAA;AApGY,sCAAa;AAGf;IAFR,IAAA,gCAAsB,EAAC,MAAM,CAAC;IAC9B,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,iBAAE,EAAE,EAAE,WAAW,EAAE,4CAA4C,EAAE,CAAC;;yCAC9D;AAInB;IAFC,IAAA,gBAAM,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IACtC,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,kBAAG,EAAE,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AC,OAAO,CAAC;;gDACtC;AAIlB;IAFC,IAAA,gBAAM,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAC1B,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,kDAAkD,EAAE,CAAC;sCAC/E,IAAI;gDAAA;AAIT;IAFN,IAAA,yCAAuB,GAAE;IACzB,IAAA,oBAAK,EAAC,EAAE,WAAW,EAAE,+CAA+C,EAAE,CAAC;;iDAC9C;AAInB;IAFN,IAAA,qCAAmB,EAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;IACrE,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,WAAW,EAAE,0DAA0D,EAAE,CAAC;;6CAClE;wBAnGtB,aAAa;IAHzB,IAAA,gBAAM,GAAE;IACR,IAAA,eAAK,EAAC,qBAAqB,EAAE,CAAC,OAAsB,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACjH,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,uDAAuD,EAAE,CAAC;GACxE,aAAa,CAoGzB","sourcesContent":["import { Field, ID, ObjectType, Float, Int } from 'type-graphql'\nimport { Column, Entity, Index, ManyToOne, PrimaryGeneratedColumn, RelationId } from 'typeorm'\n\nimport {\n HistoryActionColumn,\n HistoryActionType,\n HistoryEntityInterface,\n HistoryOriginalIdColumn\n} from '@operato/typeorm-history'\nimport { User } from '@things-factory/auth-base'\nimport { Domain, longTextColumn } from '@things-factory/shell'\n\nimport { Figure } from './figure.js'\n\n/**\n * 발행된 판 하나 — **발행할 때만 남는다.**\n *\n * 저작 중 저장은 여기 오지 않는다. 스냅샷을 뜨는 subscriber 가 `state === 'released'` 인 저장에만\n * 움직인다(`event-subscriber.ts`) — board 가 같은 규칙으로 돈다.\n *\n * ## 왜 통째로 베끼나\n *\n * 판을 되세우려면 그때의 정본만으로는 모자란다. 이름·분류·그림·비용까지 함께 있어야 「그 판이\n * 무엇이었나」를 보여 주고 되돌릴 수 있다. 파생값(점수·삼각형·묶음)도 같이 둔다 — 다시 계산하면\n * 형식이 바뀐 오늘의 값이 나오고, 그것은 그 판의 값이 아니다.\n */\n@Entity()\n@Index('ix_figure_history_0', (history: FigureHistory) => [history.originalId, history.version], { unique: true })\n@ObjectType({ description: 'A released version of a figure — one row per release.' })\nexport class FigureHistory implements HistoryEntityInterface<Figure> {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { description: 'Unique identifier for this history record.' })\n readonly id: string\n\n @Column({ nullable: true, default: 1 })\n @Field(type => Int, { nullable: true, description: 'The published version number this record holds.' })\n version?: number = 1\n\n @ManyToOne(type => Domain)\n @Field(type => Domain, { nullable: true, description: 'The domain the figure belonged to.' })\n domain?: Domain\n\n @RelationId((history: FigureHistory) => history.domain)\n domainId?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'The stored identifier of the figure. It never changes.' })\n type?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'The display name at this version.' })\n name?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'The description at this version.' })\n description?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'The classification code at this version.' })\n category?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'The lifecycle state recorded with this version.' })\n state?: 'draft' | 'released'\n\n @Column({ nullable: true, ...longTextColumn() })\n @Field({ nullable: true, description: 'The canonical FigureSource JSON at this version.' })\n source?: string\n\n @Column({ nullable: true, ...longTextColumn() })\n @Field({ nullable: true, description: 'The master-data field definition at this version.' })\n properties?: string\n\n @Column({ nullable: true, ...longTextColumn() })\n @Field({ nullable: true, description: 'The thumbnail as it looked at this version.' })\n thumbnail?: string\n\n /*\n * 그때의 비용이다. 오늘 다시 계산하면 오늘의 형식으로 나온다 — 그 판을 설명하지 못한다.\n */\n @Column({ type: 'float', nullable: true })\n @Field(type => Float, { nullable: true, description: 'Reuse score as computed at this version.' })\n score?: number\n\n @Column({ nullable: true })\n @Field(type => Int, { nullable: true, description: 'Triangle count at this version.' })\n triangles?: number\n\n @Column({ nullable: true })\n @Field(type => Int, { nullable: true, description: 'Material group count at this version.' })\n groups?: number\n\n @Column({ nullable: true, ...longTextColumn() })\n @Field({ nullable: true, description: 'The note left when this version was released.' })\n comment?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'When the original figure was created.' })\n createdAt?: Date\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'When the figure was saved at this version.' })\n updatedAt?: Date\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Who created the original figure.' })\n creator?: User\n\n @RelationId((history: FigureHistory) => history.creator)\n creatorId?: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Who released this version.' })\n updater?: User\n\n @RelationId((history: FigureHistory) => history.updater)\n updaterId?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'When the original figure was deleted, if it was.' })\n deletedAt?: Date\n\n @HistoryOriginalIdColumn()\n @Field({ description: 'The id of the figure this version belongs to.' })\n public originalId!: string\n\n @HistoryActionColumn({ nullable: false, type: 'varchar', length: 10 })\n @Field(type => String, { description: 'What produced this record (created · updated · deleted).' })\n public action!: HistoryActionType\n}\n"]}
@@ -1,8 +1,47 @@
1
+ import { Figure } from './figure.js';
1
2
  import { FigurePatch, FigureSaveResult, NewFigure } from './figure-type.js';
2
3
  import { FigureProposal, ProposeRequest } from './figure-propose-type.js';
3
4
  export declare class FigureMutation {
4
5
  createFigure(figure: NewFigure, context: ResolverContext): Promise<FigureSaveResult>;
5
6
  updateFigure(id: string, patch: FigurePatch, context: ResolverContext): Promise<FigureSaveResult>;
7
+ /**
8
+ * 발행한다 — **판이 생기는 유일한 자리.**
9
+ *
10
+ * ## 무엇이 일어나나
11
+ *
12
+ * `state` 가 `released` 가 되고, 판 번호가 하나 오르고, 그 순간의 도형이 판본으로 남는다
13
+ * (`FigureHistory` — 스냅샷은 구독자가 뜬다). 저작 중 저장은 이 셋 중 아무것도 하지 않는다.
14
+ *
15
+ * ## 왜 이미 발행된 것을 거절하나
16
+ *
17
+ * 발행은 소비처에게 하는 약속이다. 같은 판을 두 번 발행하면 무엇이 약속인지 흐려진다. 고쳐서
18
+ * 다시 내려면 초안으로 되돌린 뒤 발행한다 — board 가 같은 규칙이다.
19
+ *
20
+ * ## 번호는 판본에서 센다
21
+ *
22
+ * 도형의 현재 번호가 아니라 **판본의 최대 번호 + 1** 이다. 되돌리기로 옛 판이 현재가 되어도
23
+ * 다음 발행이 이미 쓴 번호를 다시 쓰지 않는다.
24
+ */
25
+ releaseFigure(id: string, comment: string, context: ResolverContext): Promise<Figure>;
26
+ /**
27
+ * 옛 판으로 되돌린다.
28
+ *
29
+ * ## 무엇이 돌아오나
30
+ *
31
+ * 그 판의 **정본과 속성 정의, 그리고 그림**이다. 이름·설명·분류는 그대로 둔다 — 그것들은 언제든
32
+ * 바꿔도 안전한 카탈로그의 말이고, 되돌리기가 개명까지 되돌리면 사람이 시키지 않은 일을 한다.
33
+ *
34
+ * ## 되돌려도 발행은 아니다
35
+ *
36
+ * 초안으로 돌아온다. 다시 내보내려면 발행을 한 번 더 하고, 그때 판 번호는 **이미 쓴 번호 다음**을
37
+ * 받는다 — 3판을 되살렸다고 다시 3판이 되지 않는다. board 도 같다.
38
+ *
39
+ * ## 비용은 다시 잰다
40
+ *
41
+ * 판본이 든 점수·삼각형은 **그때의 형식**으로 잰 값이다. 지금 이 도형이 그 내용이 되었으므로
42
+ * 오늘 기준으로 다시 계산한다. 옛 값은 판본에 그대로 남아 있다.
43
+ */
44
+ revertFigureVersion(id: string, version: number, context: ResolverContext): Promise<FigureSaveResult>;
6
45
  deleteFigure(id: string, context: ResolverContext): Promise<boolean>;
7
46
  /**
8
47
  * 저작 보조에게 후보를 시킨다.
@@ -5,6 +5,7 @@ const tslib_1 = require("tslib");
5
5
  const typeorm_1 = require("typeorm");
6
6
  const type_graphql_1 = require("type-graphql");
7
7
  const figure_js_1 = require("./figure.js");
8
+ const figure_history_js_1 = require("./figure-history.js");
8
9
  const figure_type_js_1 = require("./figure-type.js");
9
10
  const figure_propose_type_js_1 = require("./figure-propose-type.js");
10
11
  const figure_source_js_1 = require("./figure-source.js");
@@ -53,16 +54,145 @@ let FigureMutation = class FigureMutation {
53
54
  derived = parsed.derived;
54
55
  violations = parsed.violations;
55
56
  }
57
+ /*
58
+ **판 번호는 여기서 손대지 않는다.** 저장은 저작이고, 판은 발행에서 생긴다(`releaseFigure`).
59
+ board 의 `updateBoard` 도 같다 — 저장 경로에는 version 이 없다.
60
+ */
56
61
  const saved = await repository.save({
62
+ /*
63
+ `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.
64
+
65
+ 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은
66
+ 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은
67
+ 자리에서 domain 을 함께 넣는다.
68
+ */
69
+ domain,
57
70
  ...figure,
58
71
  ...patch,
59
72
  source,
73
+ /*
74
+ **고치면 발행이 풀린다.**
75
+
76
+ 발행은 「이 판을 써도 된다」는 약속이고, 그 뒤에 정본이 바뀌면 약속한 것과 배포된 것이
77
+ 달라진다. 그래서 저장은 언제나 초안으로 되돌리고, 다시 내보내려면 발행을 한 번 더 한다
78
+ (판 번호가 하나 오르고 판본이 하나 더 남는다). board 의 `updateBoard` 가 같은 한 줄을 쓴다.
79
+ */
80
+ state: 'draft',
60
81
  ...(derived ?? {}),
61
82
  // 썸네일이 **썸네일로서** 바뀐 때만 시각을 갱신한다. 이름·설명 변경에는 안 건드린다.
62
83
  thumbnailUpdatedAt: patch.thumbnail !== undefined && patch.thumbnail !== figure.thumbnail
63
84
  ? new Date()
64
85
  : figure.thumbnailUpdatedAt,
65
- version: (figure.version ?? 1) + 1,
86
+ updater: user
87
+ });
88
+ return { figure: saved, violations };
89
+ }
90
+ /**
91
+ * 발행한다 — **판이 생기는 유일한 자리.**
92
+ *
93
+ * ## 무엇이 일어나나
94
+ *
95
+ * `state` 가 `released` 가 되고, 판 번호가 하나 오르고, 그 순간의 도형이 판본으로 남는다
96
+ * (`FigureHistory` — 스냅샷은 구독자가 뜬다). 저작 중 저장은 이 셋 중 아무것도 하지 않는다.
97
+ *
98
+ * ## 왜 이미 발행된 것을 거절하나
99
+ *
100
+ * 발행은 소비처에게 하는 약속이다. 같은 판을 두 번 발행하면 무엇이 약속인지 흐려진다. 고쳐서
101
+ * 다시 내려면 초안으로 되돌린 뒤 발행한다 — board 가 같은 규칙이다.
102
+ *
103
+ * ## 번호는 판본에서 센다
104
+ *
105
+ * 도형의 현재 번호가 아니라 **판본의 최대 번호 + 1** 이다. 되돌리기로 옛 판이 현재가 되어도
106
+ * 다음 발행이 이미 쓴 번호를 다시 쓰지 않는다.
107
+ */
108
+ async releaseFigure(id, comment, context) {
109
+ const { domain, user, tx } = context.state;
110
+ const repository = tx.getRepository(figure_js_1.Figure);
111
+ const historyRepository = tx.getRepository(figure_history_js_1.FigureHistory);
112
+ const figure = await repository.findOne({
113
+ where: { domain: { id: (0, typeorm_1.In)([domain.id, domain.parentId].filter(Boolean)) }, id }
114
+ });
115
+ if (!figure) {
116
+ throw new Error(`Figure ${id} 를 찾을 수 없다`);
117
+ }
118
+ if (figure.state === 'released') {
119
+ throw new Error(`Figure '${figure.type}' 은 이미 발행되어 있다. 고쳐서 다시 내려면 초안으로 되돌린 뒤 발행한다`);
120
+ }
121
+ const highest = await historyRepository
122
+ .createQueryBuilder('history')
123
+ .select('MAX(history.version)', 'max')
124
+ .where('history.originalId = :id', { id: figure.id })
125
+ .getRawOne();
126
+ const nextVersion = highest?.max ? Number(highest.max) + 1 : 1;
127
+ return await repository.save({
128
+ /*
129
+ `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.
130
+
131
+ 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은
132
+ 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은
133
+ 자리에서 domain 을 함께 넣는다.
134
+ */
135
+ domain,
136
+ ...figure,
137
+ version: nextVersion,
138
+ state: 'released',
139
+ updater: user,
140
+ /* 판본 구독자가 이것을 판본의 comment 로 옮긴다. Figure 의 칸이 아니다. */
141
+ __releaseComment: comment ?? null
142
+ });
143
+ }
144
+ /**
145
+ * 옛 판으로 되돌린다.
146
+ *
147
+ * ## 무엇이 돌아오나
148
+ *
149
+ * 그 판의 **정본과 속성 정의, 그리고 그림**이다. 이름·설명·분류는 그대로 둔다 — 그것들은 언제든
150
+ * 바꿔도 안전한 카탈로그의 말이고, 되돌리기가 개명까지 되돌리면 사람이 시키지 않은 일을 한다.
151
+ *
152
+ * ## 되돌려도 발행은 아니다
153
+ *
154
+ * 초안으로 돌아온다. 다시 내보내려면 발행을 한 번 더 하고, 그때 판 번호는 **이미 쓴 번호 다음**을
155
+ * 받는다 — 3판을 되살렸다고 다시 3판이 되지 않는다. board 도 같다.
156
+ *
157
+ * ## 비용은 다시 잰다
158
+ *
159
+ * 판본이 든 점수·삼각형은 **그때의 형식**으로 잰 값이다. 지금 이 도형이 그 내용이 되었으므로
160
+ * 오늘 기준으로 다시 계산한다. 옛 값은 판본에 그대로 남아 있다.
161
+ */
162
+ async revertFigureVersion(id, version, context) {
163
+ const { domain, user, tx } = context.state;
164
+ const repository = tx.getRepository(figure_js_1.Figure);
165
+ const historyRepository = tx.getRepository(figure_history_js_1.FigureHistory);
166
+ const figure = await repository.findOne({
167
+ where: { domain: { id: (0, typeorm_1.In)([domain.id, domain.parentId].filter(Boolean)) }, id }
168
+ });
169
+ if (!figure) {
170
+ throw new Error(`Figure ${id} 를 찾을 수 없다`);
171
+ }
172
+ const history = await historyRepository.findOne({
173
+ where: { domain: { id: (0, typeorm_1.In)([domain.id, domain.parentId].filter(Boolean)) }, originalId: id, version }
174
+ });
175
+ if (!history) {
176
+ throw new Error(`Figure '${figure.type}' 에 ${version} 판이 없다`);
177
+ }
178
+ /* 형식 검사도 다시 받는다 — 옛 판이 오늘의 형식을 어길 수 있고, 그것을 조용히 들이지 않는다. */
179
+ const { source, derived, violations } = (0, figure_source_js_1.parseSource)(history.source);
180
+ const saved = await repository.save({
181
+ /*
182
+ `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.
183
+
184
+ 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은
185
+ 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은
186
+ 자리에서 domain 을 함께 넣는다.
187
+ */
188
+ domain,
189
+ ...figure,
190
+ source,
191
+ ...derived,
192
+ properties: history.properties,
193
+ thumbnail: history.thumbnail,
194
+ thumbnailUpdatedAt: history.thumbnail === figure.thumbnail ? figure.thumbnailUpdatedAt : new Date(),
195
+ state: 'draft',
66
196
  updater: user
67
197
  });
68
198
  return { figure: saved, violations };
@@ -145,6 +275,28 @@ tslib_1.__decorate([
145
275
  tslib_1.__metadata("design:paramtypes", [String, figure_type_js_1.FigurePatch, Object]),
146
276
  tslib_1.__metadata("design:returntype", Promise)
147
277
  ], FigureMutation.prototype, "updateFigure", null);
278
+ tslib_1.__decorate([
279
+ (0, type_graphql_1.Directive)('@transaction'),
280
+ (0, type_graphql_1.Directive)('@privilege(category: "figure", privilege: "mutation", domainOwnerGranted: true)'),
281
+ (0, type_graphql_1.Mutation)(returns => figure_js_1.Figure, { description: 'Releases a figure — raises its version and keeps the released state as history.' }),
282
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('id')),
283
+ tslib_1.__param(1, (0, type_graphql_1.Arg)('comment', { nullable: true })),
284
+ tslib_1.__param(2, (0, type_graphql_1.Ctx)()),
285
+ tslib_1.__metadata("design:type", Function),
286
+ tslib_1.__metadata("design:paramtypes", [String, String, Object]),
287
+ tslib_1.__metadata("design:returntype", Promise)
288
+ ], FigureMutation.prototype, "releaseFigure", null);
289
+ tslib_1.__decorate([
290
+ (0, type_graphql_1.Directive)('@transaction'),
291
+ (0, type_graphql_1.Directive)('@privilege(category: "figure", privilege: "mutation", domainOwnerGranted: true)'),
292
+ (0, type_graphql_1.Mutation)(returns => figure_type_js_1.FigureSaveResult, { description: 'Reverts a figure to one of its released versions. It comes back as a draft.' }),
293
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('id')),
294
+ tslib_1.__param(1, (0, type_graphql_1.Arg)('version')),
295
+ tslib_1.__param(2, (0, type_graphql_1.Ctx)()),
296
+ tslib_1.__metadata("design:type", Function),
297
+ tslib_1.__metadata("design:paramtypes", [String, Number, Object]),
298
+ tslib_1.__metadata("design:returntype", Promise)
299
+ ], FigureMutation.prototype, "revertFigureVersion", null);
148
300
  tslib_1.__decorate([
149
301
  (0, type_graphql_1.Directive)('@transaction'),
150
302
  (0, type_graphql_1.Directive)('@privilege(category: "figure", privilege: "mutation", domainOwnerGranted: true)'),
@@ -1 +1 @@
1
- {"version":3,"file":"figure-mutation.js","sourceRoot":"","sources":["../../../server/service/figure/figure-mutation.ts"],"names":[],"mappings":";;;;AAAA,qCAA4B;AAC5B,+CAAsE;AAItE,2CAAoC;AACpC,qDAA2E;AAC3E,qEAAyE;AACzE,yDAAgD;AAChD,2DAAmE;AAG5D,IAAM,cAAc,GAApB,MAAM,cAAc;IAInB,AAAN,KAAK,CAAC,YAAY,CACD,MAAiB,EACzB,OAAwB;QAE/B,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAA;QAC1C,MAAM,UAAU,GAAG,EAAE,CAAC,aAAa,CAAC,kBAAM,CAAC,CAAA;QAE3C,gDAAgD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,kBAAG,GAAE,CAAA;;qDADe,4BAAW;;kDAyCjC;AAKK;IAHL,IAAA,wBAAS,EAAC,cAAc,CAAC;IACzB,IAAA,wBAAS,EAAC,iFAAiF,CAAC;IAC5F,IAAA,uBAAQ,EAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,WAAW,EAAE,wBAAwB,EAAE,CAAC;IACpD,mBAAA,IAAA,kBAAG,EAAC,IAAI,CAAC,CAAA;IAAc,mBAAA,IAAA,kBAAG,GAAE,CAAA;;;;kDAQ/C;AAiBK;IAJL,IAAA,wBAAS,EAAC,iFAAiF,CAAC;IAC5F,IAAA,uBAAQ,EAAC,OAAO,CAAC,EAAE,CAAC,uCAAc,EAAE;QACnC,WAAW,EAAE,oFAAoF;KAClG,CAAC;IACmB,mBAAA,IAAA,kBAAG,EAAC,SAAS,CAAC,CAAA;;6CAAU,uCAAc;;mDAqC1D;yBApJU,cAAc;IAD1B,IAAA,uBAAQ,EAAC,kBAAM,CAAC;GACJ,cAAc,CAsJ1B","sourcesContent":["import { In } from 'typeorm'\nimport { Arg, Ctx, Directive, Mutation, Resolver } from 'type-graphql'\n\nimport { getRepository } from '@things-factory/shell'\n\nimport { Figure } from './figure.js'\nimport { FigurePatch, FigureSaveResult, NewFigure } from './figure-type.js'\nimport { FigureProposal, ProposeRequest } from './figure-propose-type.js'\nimport { parseSource } from './figure-source.js'\nimport { ProposeFailure, proposeFigure } from './figure-propose.js'\n\n@Resolver(Figure)\nexport class FigureMutation {\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Creates a figure. Rejects when the source violates the format.' })\n async createFigure(\n @Arg('figure') figure: NewFigure,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n\n // 타입 이름은 도메인 안에서 유일하다. 유니크 인덱스가 있지만 여기서 먼저 본다 —\n // DB 오류 문구는 저작자에게 아무 말도 해 주지 못한다.\n const taken = await repository.findOne({ where: { domain: { id: domain.id }, type: figure.type } })\n if (taken) {\n throw new Error(`타입 이름 '${figure.type}' 은 이미 쓰이고 있다. 만든 뒤에는 고칠 수 없으므로 다른 이름을 고른다`)\n }\n\n // 형식을 어기면 여기서 던진다. 파생값은 서버가 계산한다.\n const { source, derived, violations } = parseSource(figure.source)\n\n const saved = await repository.save({\n ...figure,\n source,\n ...derived,\n state: figure.state ?? 'draft',\n thumbnailUpdatedAt: figure.thumbnail ? new Date() : undefined,\n domain,\n creator: user,\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Updates a figure. The `type` field cannot be changed.' })\n async updateFigure(\n @Arg('id') id: string,\n @Arg('patch') patch: FigurePatch,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n // 정본이 바뀌면 파생값도 다시 계산한다. 안 바뀌었으면 손대지 않는다 —\n // 이름만 고쳤는데 점수가 흔들리면 읽는 사람이 원인을 못 찾는다.\n let derived: { score: number; triangles: number; groups: number } | undefined\n let violations = []\n let source = figure.source\n\n if (patch.source !== undefined && patch.source !== figure.source) {\n const parsed = parseSource(patch.source)\n source = parsed.source\n derived = parsed.derived\n violations = parsed.violations\n }\n\n const saved = await repository.save({\n ...figure,\n ...patch,\n source,\n ...(derived ?? {}),\n // 썸네일이 **썸네일로서** 바뀐 때만 시각을 갱신한다. 이름·설명 변경에는 안 건드린다.\n thumbnailUpdatedAt:\n patch.thumbnail !== undefined && patch.thumbnail !== figure.thumbnail\n ? new Date()\n : figure.thumbnailUpdatedAt,\n version: (figure.version ?? 1) + 1,\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Boolean, { description: 'Soft-deletes a figure.' })\n async deleteFigure(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<boolean> {\n const { domain, tx } = context.state\n\n // 소프트 삭제다 — 이미 배치된 보드가 이 타입을 참조할 수 있으므로 행을 지우지\n // 않는다. 되살릴 길을 남긴다.\n await tx.getRepository(Figure).softDelete({ domain: { id: domain.id }, id })\n\n return true\n }\n\n /**\n * 저작 보조에게 후보를 시킨다.\n *\n * **저장하지 않는다.** 후보를 돌려줄 뿐이고, 정본이 되는 것은 저작자가 보고 받은\n * 뒤다. AI 가 정본에 직접 쓰면 저작자가 무엇이 자기 것이고 무엇이 기계 것인지\n * 모르게 된다.\n *\n * 형식을 어긴 후보는 여기까지 오지 않는다 — `proposeFigure` 가 사유를 모델에\n * 돌려주고 다시 시킨다. 끝내 못 만들면 **사유와 함께 던진다.** 반쯤 만든 것을\n * 돌려주지 않는다.\n */\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureProposal, {\n description: 'Asks the authoring assistant for a figure. Returns a candidate — nothing is saved.'\n })\n async proposeFigure(@Arg('request') request: ProposeRequest): Promise<FigureProposal> {\n // 그림은 메모리로 받는다. 참고용이라 저장하지 않는다 — 남기면 지울 사람이 없다.\n let image\n if (request.image) {\n const file = await request.image\n const chunks: Buffer[] = []\n for await (const chunk of file.createReadStream()) {\n chunks.push(chunk as Buffer)\n }\n image = { data: Buffer.concat(chunks), mediaType: file.mimetype as never }\n }\n\n try {\n const result = await proposeFigure({\n prompt: request.prompt,\n base: request.base ? JSON.parse(request.base) : undefined,\n type: request.type,\n palette: request.palette,\n image\n })\n\n return {\n source: JSON.stringify(result.source),\n score: Math.round(result.score.score),\n grade: result.score.grade,\n triangles: result.cost.triangles,\n groups: result.cost.groups,\n violations: result.violations,\n attempts: result.attempts\n }\n } catch (e) {\n if (e instanceof ProposeFailure) {\n // 사유를 삼키지 않는다. 저작자가 무엇이 막혔는지 알아야 말을 고쳐 다시 시킨다.\n throw new Error([e.message, ...e.reasons].join('\\n'))\n }\n throw e\n }\n }\n\n}\n"]}
1
+ {"version":3,"file":"figure-mutation.js","sourceRoot":"","sources":["../../../server/service/figure/figure-mutation.ts"],"names":[],"mappings":";;;;AAAA,qCAA4B;AAC5B,+CAAsE;AAItE,2CAAoC;AACpC,2DAAmD;AACnD,qDAA2E;AAC3E,qEAAyE;AACzE,yDAAgD;AAChD,2DAAmE;AAG5D,IAAM,cAAc,GAApB,MAAM,cAAc;IAInB,AAAN,KAAK,CAAC,YAAY,CACD,MAAiB,EACzB,OAAwB;QAE/B,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAA;QAC1C,MAAM,UAAU,GAAG,EAAE,CAAC,aAAa,CAAC,kBAAM,CAAC,CAAA;QAE3C,gDAAgD;QAChD,kCAAkC;QAClC,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAA;QACnG,IAAI,KAAK,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,UAAU,MAAM,CAAC,IAAI,4CAA4C,CAAC,CAAA;QACpF,CAAC;QAED,kCAAkC;QAClC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,IAAA,8BAAW,EAAC,MAAM,CAAC,MAAM,CAAC,CAAA;QAElE,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,IAAI,CAAC;YAClC,GAAG,MAAM;YACT,MAAM;YACN,GAAG,OAAO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AC;IAC5F,IAAA,uBAAQ,EAAC,OAAO,CAAC,EAAE,CAAC,uCAAc,EAAE;QACnC,WAAW,EAAE,oFAAoF;KAClG,CAAC;IACmB,mBAAA,IAAA,kBAAG,EAAC,SAAS,CAAC,CAAA;;6CAAU,uCAAc;;mDAqC1D;yBA/SU,cAAc;IAD1B,IAAA,uBAAQ,EAAC,kBAAM,CAAC;GACJ,cAAc,CAiT1B","sourcesContent":["import { In } from 'typeorm'\nimport { Arg, Ctx, Directive, Mutation, Resolver } from 'type-graphql'\n\nimport { getRepository } from '@things-factory/shell'\n\nimport { Figure } from './figure.js'\nimport { FigureHistory } from './figure-history.js'\nimport { FigurePatch, FigureSaveResult, NewFigure } from './figure-type.js'\nimport { FigureProposal, ProposeRequest } from './figure-propose-type.js'\nimport { parseSource } from './figure-source.js'\nimport { ProposeFailure, proposeFigure } from './figure-propose.js'\n\n@Resolver(Figure)\nexport class FigureMutation {\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Creates a figure. Rejects when the source violates the format.' })\n async createFigure(\n @Arg('figure') figure: NewFigure,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n\n // 타입 이름은 도메인 안에서 유일하다. 유니크 인덱스가 있지만 여기서 먼저 본다 —\n // DB 오류 문구는 저작자에게 아무 말도 해 주지 못한다.\n const taken = await repository.findOne({ where: { domain: { id: domain.id }, type: figure.type } })\n if (taken) {\n throw new Error(`타입 이름 '${figure.type}' 은 이미 쓰이고 있다. 만든 뒤에는 고칠 수 없으므로 다른 이름을 고른다`)\n }\n\n // 형식을 어기면 여기서 던진다. 파생값은 서버가 계산한다.\n const { source, derived, violations } = parseSource(figure.source)\n\n const saved = await repository.save({\n ...figure,\n source,\n ...derived,\n state: figure.state ?? 'draft',\n thumbnailUpdatedAt: figure.thumbnail ? new Date() : undefined,\n domain,\n creator: user,\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Updates a figure. The `type` field cannot be changed.' })\n async updateFigure(\n @Arg('id') id: string,\n @Arg('patch') patch: FigurePatch,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n // 정본이 바뀌면 파생값도 다시 계산한다. 안 바뀌었으면 손대지 않는다 —\n // 이름만 고쳤는데 점수가 흔들리면 읽는 사람이 원인을 못 찾는다.\n let derived: { score: number; triangles: number; groups: number } | undefined\n let violations = []\n let source = figure.source\n\n if (patch.source !== undefined && patch.source !== figure.source) {\n const parsed = parseSource(patch.source)\n source = parsed.source\n derived = parsed.derived\n violations = parsed.violations\n }\n\n /*\n **판 번호는 여기서 손대지 않는다.** 저장은 저작이고, 판은 발행에서 생긴다(`releaseFigure`).\n board 의 `updateBoard` 도 같다 — 저장 경로에는 version 이 없다.\n */\n const saved = await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n ...patch,\n source,\n /*\n **고치면 발행이 풀린다.**\n\n 발행은 「이 판을 써도 된다」는 약속이고, 그 뒤에 정본이 바뀌면 약속한 것과 배포된 것이\n 달라진다. 그래서 저장은 언제나 초안으로 되돌리고, 다시 내보내려면 발행을 한 번 더 한다\n (판 번호가 하나 오르고 판본이 하나 더 남는다). board 의 `updateBoard` 가 같은 한 줄을 쓴다.\n */\n state: 'draft',\n ...(derived ?? {}),\n // 썸네일이 **썸네일로서** 바뀐 때만 시각을 갱신한다. 이름·설명 변경에는 안 건드린다.\n thumbnailUpdatedAt:\n patch.thumbnail !== undefined && patch.thumbnail !== figure.thumbnail\n ? new Date()\n : figure.thumbnailUpdatedAt,\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n /**\n * 발행한다 — **판이 생기는 유일한 자리.**\n *\n * ## 무엇이 일어나나\n *\n * `state` 가 `released` 가 되고, 판 번호가 하나 오르고, 그 순간의 도형이 판본으로 남는다\n * (`FigureHistory` — 스냅샷은 구독자가 뜬다). 저작 중 저장은 이 셋 중 아무것도 하지 않는다.\n *\n * ## 왜 이미 발행된 것을 거절하나\n *\n * 발행은 소비처에게 하는 약속이다. 같은 판을 두 번 발행하면 무엇이 약속인지 흐려진다. 고쳐서\n * 다시 내려면 초안으로 되돌린 뒤 발행한다 — board 가 같은 규칙이다.\n *\n * ## 번호는 판본에서 센다\n *\n * 도형의 현재 번호가 아니라 **판본의 최대 번호 + 1** 이다. 되돌리기로 옛 판이 현재가 되어도\n * 다음 발행이 이미 쓴 번호를 다시 쓰지 않는다.\n */\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Figure, { description: 'Releases a figure — raises its version and keeps the released state as history.' })\n async releaseFigure(\n @Arg('id') id: string,\n @Arg('comment', { nullable: true }) comment: string,\n @Ctx() context: ResolverContext\n ): Promise<Figure> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n const historyRepository = tx.getRepository(FigureHistory)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n if (figure.state === 'released') {\n throw new Error(`Figure '${figure.type}' 은 이미 발행되어 있다. 고쳐서 다시 내려면 초안으로 되돌린 뒤 발행한다`)\n }\n\n const highest = await historyRepository\n .createQueryBuilder('history')\n .select('MAX(history.version)', 'max')\n .where('history.originalId = :id', { id: figure.id })\n .getRawOne()\n\n const nextVersion = highest?.max ? Number(highest.max) + 1 : 1\n\n return await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n version: nextVersion,\n state: 'released',\n updater: user,\n /* 판본 구독자가 이것을 판본의 comment 로 옮긴다. Figure 의 칸이 아니다. */\n __releaseComment: comment ?? null\n } as any)\n }\n\n /**\n * 옛 판으로 되돌린다.\n *\n * ## 무엇이 돌아오나\n *\n * 그 판의 **정본과 속성 정의, 그리고 그림**이다. 이름·설명·분류는 그대로 둔다 — 그것들은 언제든\n * 바꿔도 안전한 카탈로그의 말이고, 되돌리기가 개명까지 되돌리면 사람이 시키지 않은 일을 한다.\n *\n * ## 되돌려도 발행은 아니다\n *\n * 초안으로 돌아온다. 다시 내보내려면 발행을 한 번 더 하고, 그때 판 번호는 **이미 쓴 번호 다음**을\n * 받는다 — 3판을 되살렸다고 다시 3판이 되지 않는다. board 도 같다.\n *\n * ## 비용은 다시 잰다\n *\n * 판본이 든 점수·삼각형은 **그때의 형식**으로 잰 값이다. 지금 이 도형이 그 내용이 되었으므로\n * 오늘 기준으로 다시 계산한다. 옛 값은 판본에 그대로 남아 있다.\n */\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureSaveResult, { description: 'Reverts a figure to one of its released versions. It comes back as a draft.' })\n async revertFigureVersion(\n @Arg('id') id: string,\n @Arg('version') version: number,\n @Ctx() context: ResolverContext\n ): Promise<FigureSaveResult> {\n const { domain, user, tx } = context.state\n const repository = tx.getRepository(Figure)\n const historyRepository = tx.getRepository(FigureHistory)\n\n const figure = await repository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n const history = await historyRepository.findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, originalId: id, version }\n })\n if (!history) {\n throw new Error(`Figure '${figure.type}' 에 ${version} 판이 없다`)\n }\n\n /* 형식 검사도 다시 받는다 — 옛 판이 오늘의 형식을 어길 수 있고, 그것을 조용히 들이지 않는다. */\n const { source, derived, violations } = parseSource(history.source)\n\n const saved = await repository.save({\n /*\n `domain` 을 명시로 넣는다 — 읽어 온 엔티티에는 관계가 안 실려 있다.\n\n 판본 스냅샷은 넘겨받은 엔티티를 베끼므로, 여기서 빠지면 판본의 도메인이 비고 그 판은\n 도메인으로 거르는 조회에 **한 줄도 안 걸린다**(실제로 그랬다). board 의 저장들도 같은\n 자리에서 domain 을 함께 넣는다.\n */\n domain,\n ...figure,\n source,\n ...derived,\n properties: history.properties,\n thumbnail: history.thumbnail,\n thumbnailUpdatedAt: history.thumbnail === figure.thumbnail ? figure.thumbnailUpdatedAt : new Date(),\n state: 'draft',\n updater: user\n })\n\n return { figure: saved, violations }\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Boolean, { description: 'Soft-deletes a figure.' })\n async deleteFigure(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<boolean> {\n const { domain, tx } = context.state\n\n // 소프트 삭제다 — 이미 배치된 보드가 이 타입을 참조할 수 있으므로 행을 지우지\n // 않는다. 되살릴 길을 남긴다.\n await tx.getRepository(Figure).softDelete({ domain: { id: domain.id }, id })\n\n return true\n }\n\n /**\n * 저작 보조에게 후보를 시킨다.\n *\n * **저장하지 않는다.** 후보를 돌려줄 뿐이고, 정본이 되는 것은 저작자가 보고 받은\n * 뒤다. AI 가 정본에 직접 쓰면 저작자가 무엇이 자기 것이고 무엇이 기계 것인지\n * 모르게 된다.\n *\n * 형식을 어긴 후보는 여기까지 오지 않는다 — `proposeFigure` 가 사유를 모델에\n * 돌려주고 다시 시킨다. 끝내 못 만들면 **사유와 함께 던진다.** 반쯤 만든 것을\n * 돌려주지 않는다.\n */\n @Directive('@privilege(category: \"figure\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => FigureProposal, {\n description: 'Asks the authoring assistant for a figure. Returns a candidate — nothing is saved.'\n })\n async proposeFigure(@Arg('request') request: ProposeRequest): Promise<FigureProposal> {\n // 그림은 메모리로 받는다. 참고용이라 저장하지 않는다 — 남기면 지울 사람이 없다.\n let image\n if (request.image) {\n const file = await request.image\n const chunks: Buffer[] = []\n for await (const chunk of file.createReadStream()) {\n chunks.push(chunk as Buffer)\n }\n image = { data: Buffer.concat(chunks), mediaType: file.mimetype as never }\n }\n\n try {\n const result = await proposeFigure({\n prompt: request.prompt,\n base: request.base ? JSON.parse(request.base) : undefined,\n type: request.type,\n palette: request.palette,\n image\n })\n\n return {\n source: JSON.stringify(result.source),\n score: Math.round(result.score.score),\n grade: result.score.grade,\n triangles: result.cost.triangles,\n groups: result.cost.groups,\n violations: result.violations,\n attempts: result.attempts\n }\n } catch (e) {\n if (e instanceof ProposeFailure) {\n // 사유를 삼키지 않는다. 저작자가 무엇이 막혔는지 알아야 말을 고쳐 다시 시킨다.\n throw new Error([e.message, ...e.reasons].join('\\n'))\n }\n throw e\n }\n }\n\n}\n"]}