summaryrefslogtreecommitdiff
path: root/db/seeds/test-table-v2.ts
blob: 07bf8914b321e178d2506529ea4d89c63b525693 (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
/**
 * Test Table V2 Seeding Script
 * 
 * 사용법:
 * npx tsx db/seeds/test-table-v2.ts
 */

import db from "@/db/db";
import { faker } from "@faker-js/faker";
import {
  testProducts,
  testCustomers,
  testOrders,
  NewTestProduct,
  NewTestCustomer,
  NewTestOrder,
} from "../schema/test-table-v2";

// === Generators ===

const CATEGORIES = [
  "Electronics",
  "Clothing",
  "Home & Garden",
  "Sports",
  "Books",
  "Toys",
  "Food",
  "Health",
];

const PRODUCT_STATUSES = ["active", "inactive", "discontinued"] as const;
const ORDER_STATUSES = ["pending", "processing", "shipped", "delivered", "cancelled"] as const;
const CUSTOMER_TIERS = ["standard", "premium", "vip"] as const;
const COUNTRIES = ["Korea", "USA", "Japan", "Germany", "UK", "France", "China", "Singapore"];

function generateProduct(): NewTestProduct {
  const category = faker.helpers.arrayElement(CATEGORIES);
  const price = faker.number.float({ min: 10, max: 1000, fractionDigits: 2 });
  
  return {
    name: faker.commerce.productName(),
    sku: faker.string.alphanumeric({ length: 8, casing: "upper" }),
    description: faker.commerce.productDescription(),
    category,
    price: price.toString(),
    stock: faker.number.int({ min: 0, max: 500 }),
    status: faker.helpers.arrayElement(PRODUCT_STATUSES),
    isNew: faker.datatype.boolean({ probability: 0.2 }),
    createdAt: faker.date.past({ years: 2 }),
    updatedAt: faker.date.recent({ days: 30 }),
  };
}

function generateCustomer(): NewTestCustomer {
  return {
    name: faker.person.fullName(),
    email: faker.internet.email(),
    phone: faker.phone.number(),
    country: faker.helpers.arrayElement(COUNTRIES),
    tier: faker.helpers.arrayElement(CUSTOMER_TIERS),
    totalOrders: faker.number.int({ min: 0, max: 100 }),
    createdAt: faker.date.past({ years: 3 }),
  };
}

function generateOrder(
  customerId: number,
  productId: number | null,
  productPrice: number
): NewTestOrder {
  const quantity = faker.number.int({ min: 1, max: 10 });
  const unitPrice = productPrice || faker.number.float({ min: 10, max: 500, fractionDigits: 2 });
  const totalAmount = quantity * unitPrice;
  const status = faker.helpers.arrayElement(ORDER_STATUSES);
  const orderedAt = faker.date.past({ years: 1 });
  
  let shippedAt: Date | undefined;
  let deliveredAt: Date | undefined;
  
  if (status === "shipped" || status === "delivered") {
    shippedAt = faker.date.between({ from: orderedAt, to: new Date() });
  }
  if (status === "delivered") {
    deliveredAt = faker.date.between({ from: shippedAt || orderedAt, to: new Date() });
  }

  return {
    orderNumber: `ORD-${faker.string.alphanumeric({ length: 8, casing: "upper" })}`,
    customerId,
    productId,
    quantity,
    unitPrice: unitPrice.toString(),
    totalAmount: totalAmount.toString(),
    status,
    notes: faker.datatype.boolean({ probability: 0.3 }) ? faker.lorem.sentence() : null,
    orderedAt,
    shippedAt,
    deliveredAt,
  };
}

// === Main Seeding Function ===

export async function seedTestTableV2(options: {
  productCount?: number;
  customerCount?: number;
  orderCount?: number;
} = {}) {
  const {
    productCount = 100,
    customerCount = 50,
    orderCount = 200,
  } = options;

  console.log("🗑️  Clearing existing test data...");
  
  // Delete in order (orders first due to FK)
  await db.delete(testOrders);
  await db.delete(testCustomers);
  await db.delete(testProducts);

  console.log(`📦 Generating ${productCount} products...`);
  const products: NewTestProduct[] = [];
  for (let i = 0; i < productCount; i++) {
    products.push(generateProduct());
  }
  const insertedProducts = await db.insert(testProducts).values(products).returning();
  console.log(`✅ Inserted ${insertedProducts.length} products`);

  console.log(`👥 Generating ${customerCount} customers...`);
  const customers: NewTestCustomer[] = [];
  for (let i = 0; i < customerCount; i++) {
    customers.push(generateCustomer());
  }
  const insertedCustomers = await db.insert(testCustomers).values(customers).returning();
  console.log(`✅ Inserted ${insertedCustomers.length} customers`);

  console.log(`🛒 Generating ${orderCount} orders...`);
  const orders: NewTestOrder[] = [];
  for (let i = 0; i < orderCount; i++) {
    const customer = faker.helpers.arrayElement(insertedCustomers);
    const product = faker.helpers.arrayElement(insertedProducts);
    orders.push(generateOrder(customer.id, product.id, parseFloat(product.price)));
  }
  const insertedOrders = await db.insert(testOrders).values(orders).returning();
  console.log(`✅ Inserted ${insertedOrders.length} orders`);

  console.log("🎉 Test table v2 seeding completed!");
  
  return {
    products: insertedProducts.length,
    customers: insertedCustomers.length,
    orders: insertedOrders.length,
  };
}

// === CLI Runner ===

async function main() {
  console.log("⏳ Starting test-table-v2 seed...");
  const start = Date.now();

  try {
    const result = await seedTestTableV2({
      productCount: 100,
      customerCount: 50,
      orderCount: 200,
    });

    const end = Date.now();
    console.log(`\n📊 Summary:`);
    console.log(`   Products: ${result.products}`);
    console.log(`   Customers: ${result.customers}`);
    console.log(`   Orders: ${result.orders}`);
    console.log(`\n✅ Seed completed in ${end - start}ms`);
  } catch (err) {
    console.error("❌ Seed failed:", err);
    process.exit(1);
  }

  process.exit(0);
}

// Run if called directly
main();