summaryrefslogtreecommitdiff
path: root/db/schema/templates.ts
blob: e9efc777c8681a5f87d674e9d27f44ceb0beffb0 (plain)
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
// db/schema/templates.ts & template-views.ts (subject 필드 추가)
import {
  pgView,
  pgTable,
  text,
  timestamp,
  uuid,
  boolean,
  jsonb,
  integer,
} from 'drizzle-orm/pg-core';
import { relations, sql } from 'drizzle-orm';
import { users } from './users';

// ────────────────────────────────────────────────────────────────────────────────
// Template base tables (subject 필드 추가)
// ────────────────────────────────────────────────────────────────────────────────

export const templates = pgTable('templates', {
  id: uuid('id').primaryKey().defaultRandom(),
  name: text('name').notNull(),
  slug: text('slug').notNull().unique(),
  subject: text('subject').notNull(), // 🆕 이메일 제목 템플릿 추가
  content: text('content').notNull(),
  description: text('description'),
  category: text('category'),
  sampleData: jsonb('sample_data').$type<Record<string, any>>().default({}),
  isActive: boolean('is_active').default(true),
  version: integer('version').default(1),

  // integer FK → users.id
  createdBy: integer('created_by')
    .notNull()
    .references(() => users.id, { onDelete: 'set null' }),

  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull(),
});

export const templateVariables = pgTable('template_variables', {
  id: uuid('id').primaryKey().defaultRandom(),
  templateId: uuid('template_id')
    .references(() => templates.id, { onDelete: 'cascade' })
    .notNull(),
  variableName: text('variable_name').notNull(),
  variableType: text('variable_type').notNull(),
  defaultValue: text('default_value'),
  isRequired: boolean('is_required').default(false),
  description: text('description'),
  validationRule: jsonb('validation_rule').$type<{
    minLength?: number;
    maxLength?: number;
    pattern?: string;
    options?: string[];
  }>(),
  displayOrder: integer('display_order').default(0),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull(),
});

export const templateHistory = pgTable('template_history', {
  id: uuid('id').primaryKey().defaultRandom(),
  templateId: uuid('template_id')
    .references(() => templates.id, { onDelete: 'cascade' })
    .notNull(),
  version: integer('version').notNull(),
  subject: text('subject').notNull(), // 🆕 히스토리에도 subject 추가
  content: text('content').notNull(),
  changeDescription: text('change_description'),
  changedBy: integer('changed_by')
    .notNull()
    .references(() => users.id, { onDelete: 'set null' }),
  createdAt: timestamp('created_at').defaultNow().notNull(),
});

// ────────────────────────────────────────────────────────────────────────────────
// Relations
// ────────────────────────────────────────────────────────────────────────────────
export const templatesRelations = relations(templates, ({ many }) => ({
  variables: many(templateVariables),
  history: many(templateHistory),
}));
export const templateVariablesRelations = relations(templateVariables, ({ one }) => ({
  template: one(templates, {
    fields: [templateVariables.templateId],
    references: [templates.id],
  }),
}));
export const templateHistoryRelations = relations(templateHistory, ({ one }) => ({
  template: one(templates, {
    fields: [templateHistory.templateId],
    references: [templates.id],
  }),
}));

// ────────────────────────────────────────────────────────────────────────────────
// Types
// ────────────────────────────────────────────────────────────────────────────────
export type Template = typeof templates.$inferSelect;
export type NewTemplate = typeof templates.$inferInsert;
export type TemplateVariable = typeof templateVariables.$inferSelect;
export type NewTemplateVariable = typeof templateVariables.$inferInsert;
export type TemplateHistory = typeof templateHistory.$inferSelect;
export type NewTemplateHistory = typeof templateHistory.$inferInsert;

export type TemplateWithVariables = Template & { variables: TemplateVariable[] };
export type TemplateWithFull = Template & {
  variables: TemplateVariable[];
  history: TemplateHistory[];
};

export const TEMPLATE_CATEGORIES = {
  WELCOME: 'welcome-email',
  PASSWORD_RESET: 'password-reset',
  NOTIFICATION: 'notification',
  INVOICE: 'invoice',
  MARKETING: 'marketing',
  SYSTEM: 'system',
} as const;
export type TemplateCategory =
  (typeof TEMPLATE_CATEGORIES)[keyof typeof TEMPLATE_CATEGORIES];

// ────────────────────────────────────────────────────────────────────────────────
// Views (subject 필드 포함하여 업데이트)
// ────────────────────────────────────────────────────────────────────────────────

// Template list view (subject 추가)
export const templateListView = pgView('template_list_view', {
  id: uuid('id').notNull(),
  name: text('name').notNull(),
  slug: text('slug').notNull(),
  subject: text('subject').notNull(), // 🆕 subject 추가
  description: text('description'),
  category: text('category'),
  isActive: boolean('is_active'),
  version: integer('version'),
  createdBy: integer('created_by'),
  createdByName: text('created_by_name'),
  createdByEmail: text('created_by_email'),
  createdAt: timestamp('created_at'),
  updatedAt: timestamp('updated_at'),
  variableCount: integer('variable_count').notNull(),
  requiredVariableCount: integer('required_variable_count').notNull(),
}).as(sql`
  SELECT
    t.id,
    t.name,
    t.slug,
    t.subject,
    t.description,
    t.category,
    t.is_active,
    t.version,
    t.created_by,
    u.name  AS created_by_name,
    u.email AS created_by_email,
    t.created_at,
    t.updated_at,
    COALESCE(v.variable_count, 0) AS variable_count,
    COALESCE(v.required_variable_count, 0) AS required_variable_count
  FROM ${templates} t
  LEFT JOIN ${users} u ON t.created_by = u.id
  LEFT JOIN (
    SELECT
      template_id,
      COUNT(*) AS variable_count,
      COUNT(*) FILTER (WHERE is_required) AS required_variable_count
    FROM ${templateVariables}
    GROUP BY template_id
  ) v ON t.id = v.template_id
`);

// Template detail view (subject 추가)
export const templateDetailView = pgView('template_detail_view', {
  id: uuid('id').notNull(),
  name: text('name').notNull(),
  slug: text('slug').notNull(),
  subject: text('subject').notNull(), // 🆕 subject 추가
  content: text('content').notNull(),
  description: text('description'),
  category: text('category'),
  sampleData: jsonb('sample_data'),
  isActive: boolean('is_active'),
  version: integer('version'),
  createdBy: integer('created_by'),
  createdByName: text('created_by_name'),
  createdByEmail: text('created_by_email'),
  createdAt: timestamp('created_at'),
  updatedAt: timestamp('updated_at'),
  variables: jsonb('variables'),
}).as(sql`
  SELECT
    t.id,
    t.name,
    t.slug,
    t.subject,
    t.content,
    t.description,
    t.category,
    t.sample_data,
    t.is_active,
    t.version,
    t.created_by,
    u.name  AS created_by_name,
    u.email AS created_by_email,
    t.created_at,
    t.updated_at,
    COALESCE(
      json_agg(
        json_build_object(
          'id', v.id,
          'variableName', v.variable_name,
          'variableType', v.variable_type,
          'defaultValue', v.default_value,
          'isRequired', v.is_required,
          'description', v.description,
          'displayOrder', v.display_order
        ) ORDER BY v.display_order
      ) FILTER (WHERE v.id IS NOT NULL),
      '[]'::json
    ) AS variables
  FROM ${templates} t
  LEFT JOIN ${users} u ON t.created_by = u.id
  LEFT JOIN ${templateVariables} v ON t.id = v.template_id
  GROUP BY
    t.id,
    t.name,
    t.slug,
    t.subject,
    t.content,
    t.description,
    t.category,
    t.sample_data,
    t.is_active,
    t.version,
    t.created_by,
    u.name,
    u.email,
    t.created_at,
    t.updated_at
`);

export type TemplateListView = typeof templateListView.$inferSelect;
export type TemplateDetailView = typeof templateDetailView.$inferSelect;