seed-product-knowledge.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import 'dotenv/config';
  2. import { loadConfig } from '../src/config/env.js';
  3. import { ParseRestClient } from '../src/db/parse-rest.client.js';
  4. import { VOC_PARSE_CLASSES } from '../src/db/parse-rest.schema.js';
  5. interface ProductObject {
  6. workspaceId: string;
  7. productKey: string;
  8. productId: string;
  9. role: 'own' | 'competitor';
  10. category1?: string;
  11. category2?: string;
  12. category3?: string;
  13. summary?: { gmv?: number; soldUnits?: number };
  14. }
  15. const config = loadConfig();
  16. if (config.storageDriver !== 'parse_rest') throw new Error('STORAGE_DRIVER must be parse_rest');
  17. const workspaceId = process.argv[2] || config.auth.defaultWorkspaceId;
  18. const limitArgument = process.argv[3] || '8';
  19. const limit = Math.max(1, Math.min(50, Number.parseInt(limitArgument, 10) || 8));
  20. const actorUserId = config.auth.localUserId || 'bootstrap';
  21. const client = new ParseRestClient({
  22. serverUrl: config.parse.serverUrl,
  23. appId: config.parse.appId,
  24. masterKey: config.parse.masterKey,
  25. timeoutMs: config.parse.timeoutMs,
  26. });
  27. const products = await client.findAll<ProductObject>(VOC_PARSE_CLASSES.product, {
  28. workspaceId,
  29. role: 'own',
  30. });
  31. const candidates = products
  32. .sort((left, right) => Number(right.summary?.gmv ?? 0) - Number(left.summary?.gmv ?? 0)
  33. || Number(right.summary?.soldUnits ?? 0) - Number(left.summary?.soldUnits ?? 0))
  34. .slice(0, limit);
  35. let created = 0;
  36. let existing = 0;
  37. for (const product of candidates) {
  38. const naturalKey = `${workspaceId}:${product.productKey}`;
  39. if (await client.findOne(VOC_PARSE_CLASSES.productKnowledge, { naturalKey })) {
  40. existing += 1;
  41. continue;
  42. }
  43. const category = product.category3 || product.category2 || product.category1 || '';
  44. await client.create(VOC_PARSE_CLASSES.productKnowledge, {
  45. naturalKey,
  46. workspaceId,
  47. productKey: product.productKey,
  48. productId: product.productId,
  49. productRole: product.role,
  50. featured: true,
  51. status: 'active',
  52. tags: ['经营TOP', ...(category ? [category] : [])],
  53. note: '按成交金额初始化的重点商品,可在知识库内补充关注事项。',
  54. ownerUserId: '',
  55. createdBy: actorUserId,
  56. updatedBy: actorUserId,
  57. });
  58. created += 1;
  59. }
  60. console.log(JSON.stringify({ workspaceId, candidates: candidates.length, created, existing }, null, 2));