summaryrefslogtreecommitdiff
path: root/db/seeds_2/itmeSeed.ts
blob: 6d725c22df129886116eb30c17c947957653923d (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
// db/seed/itemSeed.ts
import { faker } from "@faker-js/faker"
import db from "@/db/db"
import { items } from "../schema/items"
import { desc } from "drizzle-orm"

function generateItemName(category: string): string {
  const namePattern = Math.random()
  if (namePattern < 0.4) {
    // 일반적인 제품명
    return `${category} ${faker.commerce.productName()}`
  } else if (namePattern < 0.7) {
    // 기술 사양이 포함된 이름
    const spec = faker.number.int({ min: 100, max: 9999 })
    return `${category} ${faker.commerce.productName()} ${spec}`
  } else {
    // 브랜드가 포함된 이름
    const brand = faker.company.name().split(" ")[0]
    return `${brand} ${category} ${faker.commerce.productName()}`
  }
}

async function generateItem(industry: string, category: string, index: number) {
  const itemCode = `${industry.substring(0, 3).toUpperCase()}-${category.substring(0, 3).toUpperCase()}-${String(index + 1).padStart(4, "0")}`
  
  return {
    itemCode,
    itemName: generateItemName(category),
    description: `${industry} - ${category}: ${faker.commerce.productDescription()}`,
  }
}

export async function seedItems(input: { itemsPerCategory: number }) {
  try {
    // 다양한 산업군별 아이템 카테고리 정의
    const categories = {
      Electronics: ["Semiconductors", "PCB Components", "Sensors", "Displays", "Batteries"],
      Automotive: ["Engine Parts", "Transmission", "Suspension", "Electrical", "Interior"],
      Chemical: ["Industrial Chemicals", "Polymers", "Coatings", "Adhesives", "Solvents"],
      Construction: ["Steel", "Concrete", "Lumber", "Insulation", "Hardware"],
      Manufacturing: ["Tools", "Machinery", "Spare Parts", "Raw Materials", "Equipment"]
    } as const;

    // 현재 가장 큰 itemCode 찾기
    const lastItems = await db.select()
      .from(items)
      .orderBy(desc(items.itemCode))
      .limit(Object.keys(categories).length * 5); // 각 산업별 서브카테고리 수

    // 각 카테고리별 마지막 인덱스 추적
    const lastIndices: Record<keyof typeof categories, Record<string, number>> = {
      Electronics: {},
      Automotive: {},
      Chemical: {},
      Construction: {},
      Manufacturing: {},
    };
    
    // 기존 아이템의 itemCode에서 카테고리와 인덱스 추출
    for (const item of lastItems) {
      if (!item.itemCode) continue;
      
      const [industryCode, categoryCode, indexStr] = item.itemCode.split("-");
      if (!industryCode || !categoryCode || !indexStr) continue;

      // 코드로부터 원래 카테고리 찾기
      const industry = Object.keys(categories).find(ind => ind.substring(0, 3).toUpperCase() === industryCode) as keyof typeof categories;
      if (!industry) continue;

      const category = categories[industry].find(cat => cat.substring(0, 3).toUpperCase() === categoryCode);
      if (!category) continue;

      if (!lastIndices[industry]) {
        lastIndices[industry] = {};
      }

      const itemIndex = parseInt(indexStr);
      if (!lastIndices[industry][category] || itemIndex > lastIndices[industry][category]) {
        lastIndices[industry][category] = itemIndex;
      }
    }

    const allItems = [];

    for (const [industry, subcategories] of Object.entries(categories)) {
      for (const category of subcategories) {
        const startIndex = (lastIndices[industry as keyof typeof categories]?.[category] ?? 0);
        
        for (let i = 0; i < input.itemsPerCategory; i++) {
          allItems.push(await generateItem(industry, category, startIndex + i));
        }
      }
    }

    console.log("📝 Inserting items", allItems.length);

    const result = await db.insert(items)
      .values(allItems)
      .onConflictDoNothing()
      .returning();

    console.log(`✅ Successfully added ${result.length} new items across ${Object.keys(categories).length} industries`);
    return result;
  } catch (err) {
    console.error("Failed to seed items:", err);
    throw err;
  }
}