huangning
2026-07-17 6e62407bd607b18f2e0ca61c5ca8f0aa7008ffba
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
const http = require("http");
const fs = require("fs");
const path = require("path");
 
const root = path.resolve(__dirname, "..", "outputs");
const dataDir = path.resolve(__dirname, "..", "data");
const dataFile = path.join(dataDir, "crm_full_data.json");
const port = Number(process.env.PORT || 8090);
const accountRoles = ["supervisor", "ops", "sales", "production", "warehouse", "logistics", "finance"];
const businessKinds = {
  salesOrders: { next: "nextSalesOrderId" },
  salesBills: { next: "nextSalesBillId" },
  productionTasks: { next: "nextProductionTaskId" },
  stockItems: { next: "nextStockItemId" },
  shipments: { next: "nextShipmentId" },
  receivables: { next: "nextReceivableId" }
};
const dealStatuses = ["已成交", "待发货/执行", "已交付", "售后维护中", "复购跟进中"];
const permissionCodes = new Set([
  "customers:own",
  "customers:all",
  "customers:delete",
  "customers:assign",
  "customers:export",
  "sales:edit",
  "ops:edit",
  "orders:view",
  "orders:edit",
  "production:edit",
  "stock:edit",
  "logistics:edit",
  "finance:edit",
  "reports:view",
  "accounts:manage"
]);
const defaultUsers = [
  { username: "admin", password: "123456", name: "主管", role: "supervisor" },
  { username: "ops1", password: "123456", name: "运营一", role: "ops" },
  { username: "sales1", password: "123456", name: "销售一", role: "sales" },
  { username: "sales2", password: "123456", name: "销售二", role: "sales" },
  { username: "sales3", password: "123456", name: "销售三", role: "sales" }
];
 
function makeToken(user) {
  return Buffer.from(`${user.username}:${user.password}`).toString("base64");
}
 
function defaultPermissions(role) {
  if (role === "supervisor") return ["customers:all", "customers:delete", "customers:assign", "customers:export", "orders:view", "orders:edit", "production:edit", "stock:edit", "logistics:edit", "finance:edit", "reports:view", "accounts:manage"];
  if (role === "ops") return ["customers:all", "ops:edit", "reports:view"];
  if (role === "production") return ["orders:view", "production:edit"];
  if (role === "warehouse") return ["orders:view", "stock:edit"];
  if (role === "logistics") return ["orders:view", "logistics:edit"];
  if (role === "finance") return ["orders:view", "finance:edit", "reports:view"];
  return ["customers:own", "sales:edit", "orders:view", "orders:edit"];
}
 
function parsePermissions(value) {
  const raw = Array.isArray(value)
    ? value
    : String(value || "")
      .split(",")
      .map((item) => item.trim())
      .filter(Boolean);
  const selected = raw.filter((code) => permissionCodes.has(code));
  return [...new Set(selected)];
}
 
function getUsers(data) {
  if (!data.users) data.users = defaultUsers.map((user) => ({
    ...user,
    phone: user.username,
    status: "active",
    permissions: defaultPermissions(user.role),
    createdAt: "2026-07-14 00:00",
    updatedAt: ""
  }));
  for (const user of defaultUsers) {
    if (!data.users.some((row) => row.username === user.username)) {
      data.users.push({
        ...user,
        phone: user.username,
        status: "active",
        permissions: defaultPermissions(user.role),
        createdAt: nowText(),
        updatedAt: ""
      });
    }
  }
  for (const user of data.users) {
    user.status = user.status || "active";
    user.permissions = user.permissions || defaultPermissions(user.role);
    user.phone = user.phone || user.username;
  }
  return data.users;
}
 
function ensureBusinessData(data) {
  for (const [kind, meta] of Object.entries(businessKinds)) {
    if (!Array.isArray(data[kind])) data[kind] = [];
    if (!data[meta.next]) {
      const maxId = data[kind].reduce((max, row) => Math.max(max, Number(row.id) || 0), 0);
      data[meta.next] = maxId + 1;
    }
  }
}
 
function ensureCustomerData(data) {
  if (!Array.isArray(data.customers)) data.customers = [];
  for (const customer of data.customers) {
    if (!Object.prototype.hasOwnProperty.call(customer, "customerCategory")) {
      customer.customerCategory = customer.source || "";
    }
  }
}
 
function publicUser(user) {
  return {
    username: user.username,
    name: user.name,
    phone: user.phone || user.username,
    role: user.role,
    status: user.status || "active",
    permissions: user.permissions || defaultPermissions(user.role),
    createdAt: user.createdAt || "",
    updatedAt: user.updatedAt || ""
  };
}
 
function accountFromToken(token, data) {
  if (!token) return null;
  return getUsers(data).find((user) => user.status !== "disabled" && makeToken(user) === token) || null;
}
 
function requireAccount(req, url, body = {}, data = load()) {
  const auth = req.headers.authorization || "";
  const token = body.token || url.searchParams.get("token") || (auth.startsWith("Bearer ") ? auth.slice(7) : "");
  const account = accountFromToken(token, data);
  if (!account) {
    const err = new Error("请先登录账号");
    err.status = 401;
    throw err;
  }
  return account;
}
 
function canSeeCustomer(account, customer) {
  return account.role === "supervisor" || account.role === "ops" || customer.owner === account.name;
}
 
function requireCustomerAccess(account, customer) {
  if (!canSeeCustomer(account, customer)) {
    const err = new Error("没有权限操作这个客户");
    err.status = 403;
    throw err;
  }
}
 
function normalizeText(value) {
  return String(value || "").trim().toLowerCase().replace(/\s+/g, "");
}
 
function duplicateCandidates(data, body) {
  const phone = normalizeText(body.phone);
  const wechat = normalizeText(body.wechat);
  const platform = normalizeText(body.platformAccount);
  const leadId = normalizeText(body.leadId);
  const company = normalizeText(body.company);
  const name = normalizeText(body.name);
  return data.customers.map((c) => {
    const reasons = [];
    let strong = false;
    if (phone && normalizeText(c.phone) === phone) { reasons.push("电话相同"); strong = true; }
    if (wechat && normalizeText(c.wechat) === wechat) { reasons.push("微信相同"); strong = true; }
    if (platform && normalizeText(c.platformAccount) === platform) { reasons.push("平台ID相同"); strong = true; }
    if (leadId && (normalizeText(c.leadId) === leadId || normalizeText(c.douyinCustomerId) === leadId)) { reasons.push("线索ID相同"); strong = true; }
    if (company && normalizeText(c.company) === company) reasons.push("公司名称相同");
    if (name && normalizeText(c.name) === name) reasons.push("客户名称相同");
    if (!reasons.length) return null;
    return {
      id: c.id,
      name: c.name,
      company: c.company,
      owner: c.owner,
      firstReceiver: c.firstReceiver,
      source: c.source,
      funnel: c.funnel,
      dealStatus: c.dealStatus,
      pool: c.pool,
      lastFollowupAt: c.followups?.[0]?.at || c.lastEffectiveFollowupAt || "",
      reasons,
      strong
    };
  }).filter(Boolean).sort((a, b) => Number(b.strong) - Number(a.strong)).slice(0, 5);
}
 
function today() {
  return new Date().toISOString().slice(0, 10);
}
 
function addDays(dateText, days) {
  const d = new Date(`${dateText || today()}T00:00:00`);
  d.setDate(d.getDate() + days);
  return d.toISOString().slice(0, 10);
}
 
function nowText() {
  const d = new Date();
  const pad = (n) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
 
function seedData() {
  return {
    nextCustomerId: 6,
    nextActionId: 1,
    customers: [
      {
        id: 1,
        name: "王经理",
        company: "杭州佳源食品厂",
        phone: "138****9021",
        wechat: "wangjy",
        platformAccount: "baidu-wang",
        source: "百度",
        owner: "销售一",
        firstReceiver: "销售一",
        firstInputAt: "2026-06-18 10:20",
        firstConsultAt: "2026-06-18 10:10",
        region: "浙江杭州",
        scene: "食品车间空间消毒",
        demand: "臭氧消毒设备",
        params: "面积 800㎡,层高 4m",
        intention: "A",
        level: "A",
        funnel: "S5 已报价",
        stage: "报价",
        dealStatus: "未成交",
        dealAt: "",
        dealAmount: "",
        dealProduct: "",
        dealQuantity: "",
        dealUnitPrice: "",
        dealTotalPrice: "",
        revisitLevel: "铜",
        nextDealRevisit: "",
        protect: "即将到期",
        protectEnd: "2026-07-08",
        pool: "正常",
        poolReason: "",
        releasedAt: "",
        previousOwner: "",
        nextFollowupAt: "2026-07-07",
        lastEffectiveFollowupAt: "2026-06-27",
        remark: "客户关注设备稳定性和售后响应。",
        followups: [
          { at: "2026-06-27", user: "销售一", channel: "微信", content: "客户确认车间面积和层高,要求重新核算型号。", next: "2026-07-07", effective: true },
          { at: "2026-06-21", user: "销售一", channel: "电话", content: "已按 800㎡ 食品车间方案报价,等待客户内部审批。", next: "2026-06-27", effective: true }
        ],
        quotes: [
          { at: "2026-06-21", user: "销售一", model: "空间消毒设备 A800", amount: "¥128,000", priceType: "标准价", approval: "无需审批" }
        ],
        dealRevisits: [],
        actions: []
      },
      {
        id: 2,
        name: "李工",
        company: "苏州清源水处理",
        phone: "136****1188",
        wechat: "liwater",
        platformAccount: "aicaigou-li",
        source: "爱采购",
        owner: "销售一",
        firstReceiver: "销售一",
        firstInputAt: "2026-06-24 15:35",
        firstConsultAt: "2026-06-24 15:20",
        region: "江苏苏州",
        scene: "水处理",
        demand: "杀菌设备",
        params: "水量 30T/h",
        intention: "B",
        level: "B",
        funnel: "S4 选型方案",
        stage: "选型",
        dealStatus: "未成交",
        dealAt: "",
        dealAmount: "",
        dealProduct: "",
        dealQuantity: "",
        dealUnitPrice: "",
        dealTotalPrice: "",
        revisitLevel: "铜",
        nextDealRevisit: "",
        protect: "保护中",
        protectEnd: "2026-07-18",
        pool: "正常",
        poolReason: "",
        releasedAt: "",
        previousOwner: "",
        nextFollowupAt: "2026-07-01",
        lastEffectiveFollowupAt: "2026-06-25",
        remark: "需要确认现场水质和安装空间。",
        followups: [],
        quotes: [],
        dealRevisits: [],
        actions: []
      },
      {
        id: 3,
        name: "周主任",
        company: "常州三院实验室",
        phone: "137****2190",
        wechat: "zhoulab",
        platformAccount: "site-zhou",
        source: "官网",
        owner: "销售一",
        firstReceiver: "销售一",
        firstInputAt: "2026-04-16 11:48",
        firstConsultAt: "2026-04-16 11:30",
        region: "江苏常州",
        scene: "实验室消毒",
        demand: "维护和耗材",
        params: "复购可能",
        intention: "B",
        level: "B",
        funnel: "S7 成交/执行",
        stage: "成交",
        dealStatus: "已交付",
        dealAt: "2026-05-20",
        dealAmount: "86000",
        dealProduct: "实验室消毒设备 X2",
        dealQuantity: "2",
        dealUnitPrice: "43000",
        dealTotalPrice: "86000",
        revisitLevel: "金",
        nextDealRevisit: "2026-07-20",
        protect: "保护中",
        protectEnd: "2026-09-20",
        pool: "预公海",
        poolReason: "成交客户需要回访",
        releasedAt: "",
        previousOwner: "",
        nextFollowupAt: "2026-07-09",
        lastEffectiveFollowupAt: "2026-06-20",
        remark: "已成交客户,需要跟进耗材复购和设备维护。",
        followups: [],
        quotes: [],
        dealRevisits: [
          { at: "2026-06-20", user: "销售一", result: "设备正常,7 月中旬确认耗材需求。", next: "2026-07-20" }
        ],
        actions: []
      },
      {
        id: 4,
        name: "陈女士",
        company: "宁波海润养殖",
        phone: "135****7786",
        wechat: "chenhr",
        platformAccount: "douyin-chen",
        source: "抖音",
        owner: "销售三",
        firstReceiver: "销售三",
        firstInputAt: "2026-03-28 14:02",
        firstConsultAt: "2026-03-28 13:55",
        region: "浙江宁波",
        scene: "养殖场除味",
        demand: "除味杀菌",
        params: "2 个养殖棚",
        intention: "C",
        level: "C",
        funnel: "S8 暂缓/失败",
        stage: "暂缓",
        dealStatus: "未成交",
        dealAt: "",
        dealAmount: "",
        dealProduct: "",
        dealQuantity: "",
        dealUnitPrice: "",
        dealTotalPrice: "",
        revisitLevel: "铁",
        nextDealRevisit: "",
        protect: "已过期",
        protectEnd: "2026-06-10",
        pool: "公共客户池",
        poolReason: "保护期已过且无有效推进",
        releasedAt: "2026-07-01 09:00",
        previousOwner: "销售三",
        nextFollowupAt: "2026-06-08",
        lastEffectiveFollowupAt: "2026-04-01",
        remark: "客户预算低,后续如有补贴政策可再激活。",
        followups: [],
        quotes: [],
        dealRevisits: [],
        actions: []
      }
    ],
    actions: []
  };
}
 
function ensureData() {
  fs.mkdirSync(dataDir, { recursive: true });
  if (!fs.existsSync(dataFile)) {
    fs.writeFileSync(dataFile, JSON.stringify(seedData(), null, 2), "utf8");
  }
}
 
function load() {
  ensureData();
  const data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
  ensureBusinessData(data);
  ensureCustomerData(data);
  return data;
}
 
function save(data) {
  data._version = (Number(data._version) || 0) + 1;
  const tmpFile = `${dataFile}.${process.pid}.tmp`;
  fs.writeFileSync(tmpFile, JSON.stringify(data, null, 2), "utf8");
  fs.renameSync(tmpFile, dataFile);
}
 
function requireSupervisor(account) {
  if (account.role !== "supervisor") {
    const err = new Error("只有主管可以管理账号和权限");
    err.status = 403;
    throw err;
  }
}
 
function action(data, customer, user, type, title, content) {
  const row = { id: data.nextActionId++, customerId: customer.id, user, type, title, content, at: nowText() };
  data.actions.unshift(row);
  customer.actions = customer.actions || [];
  customer.actions.unshift(row);
}
 
function json(res, status, payload) {
  const body = JSON.stringify(payload);
  res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
  res.end(body);
}
 
function parseBody(req) {
  return new Promise((resolve, reject) => {
    let raw = "";
    req.on("data", (chunk) => { raw += chunk; });
    req.on("end", () => {
      try { resolve(raw ? JSON.parse(raw) : {}); } catch (err) { reject(err); }
    });
  });
}
 
function remindersFor(data, account) {
  const visible = data.customers.filter((c) => canSeeCustomer(account, c));
  const rows = [];
  data.manualReminders = data.manualReminders || [];
  for (const r of data.manualReminders.filter((r) => r.status !== "done")) {
    if (account.role === "supervisor" || r.user === account.name) {
      rows.push({ id: r.id, customerId: r.customerId, customer: r.customer || "手动提醒", type: "手动提醒", text: `${r.dueDate || ""} ${r.content || ""}`, manual: true });
    }
  }
  for (const c of visible) {
    const isDeal = dealStatuses.includes(c.dealStatus);
    if (!isDeal && c.nextFollowupAt && c.nextFollowupAt <= today()) {
      const overdueDays = Math.max(0, Math.floor((new Date(today() + "T00:00:00") - new Date(c.nextFollowupAt + "T00:00:00")) / 86400000));
      const type = overdueDays >= 7 ? "逾期7天主管升级" : overdueDays >= 3 ? "逾期3天提醒" : c.nextFollowupAt === today() ? "今日待跟进" : "超期未跟进";
      rows.push({ customerId: c.id, customer: c.name, type, text: `${c.company},下次跟进时间 ${c.nextFollowupAt},已逾期${overdueDays}天` });
    }
    if (c.pool === "预公海") rows.push({ customerId: c.id, customer: c.name, type: "预公海提醒", text: c.poolReason || "需要补充有效跟进或回访" });
    if (isDeal) {
      if ((!c.dealRevisits || !c.dealRevisits.length) && !c.nextDealRevisit) {
        rows.push({ customerId: c.id, customer: c.name, type: "成交回访待登记", text: `${c.company} 已成交,但还没有成交回访记录,请补充首次回访。` });
      } else if (c.nextDealRevisit && c.nextDealRevisit <= today()) {
        rows.push({ customerId: c.id, customer: c.name, type: "成交回访", text: `成交客户需要回访,计划时间 ${c.nextDealRevisit}` });
      }
    }
  }
  return rows;
}
 
async function handleApi(req, res) {
  const data = load();
  const url = new URL(req.url, `http://${req.headers.host}`);
 
  if (req.method === "POST" && url.pathname === "/api/login") {
    const body = await parseBody(req);
    const account = getUsers(data).find((user) => user.status !== "disabled" && user.username === body.username && user.password === body.password);
    if (!account) {
      json(res, 401, { error: "账号或密码不正确" });
      return;
    }
    json(res, 200, {
      token: makeToken(account),
      user: publicUser(account),
      users: getUsers(data).map(publicUser)
    });
    return;
  }
 
  if (req.method === "GET" && url.pathname === "/api/state") {
    const account = requireAccount(req, url, {}, data);
    const customers = data.customers.filter((c) => canSeeCustomer(account, c));
    json(res, 200, {
      ...data,
      customers,
      users: undefined,
      allUsers: getUsers(data).map(publicUser),
      currentAccount: publicUser(account),
      reminders: remindersFor(data, account),
      today: today()
    });
    return;
  }
 
  if (req.method === "GET" && url.pathname === "/api/export.csv") {
    const account = requireAccount(req, url, {}, data);
    const headers = ["序号", "客户", "公司", "电话", "微信", "平台账号", "来源", "客户类别", "免费/付费", "搜索词", "关键词", "时段", "经销商/终端", "客户地区", "内容/广告", "投放账号", "内容链接", "运营负责人", "线索ID", "负责人", "首次录入人", "首次录入时间", "阶段", "成交状态", "成交客户星级", "成交产品", "数量", "单价", "总价", "公海状态", "下次跟进", "备注"];
    const lines = [headers];
    data.customers.filter((c) => canSeeCustomer(account, c)).forEach((c, index) => {
      lines.push([index + 1, c.name, c.company, c.phone, c.wechat, c.platformAccount, c.source, c.customerCategory || c.source, c.trafficCostType, c.searchTerm, c.keyword, c.trafficTimeSlot, c.customerType, c.opRegion || c.region, c.contentName, c.sourceAccount, c.contentLink, c.opsOwner, c.leadId, c.owner, c.firstReceiver, c.firstInputAt, c.funnel, c.dealStatus, c.revisitLevel, c.dealProduct, c.dealQuantity, c.dealUnitPrice, c.dealTotalPrice || c.dealAmount, c.pool, c.nextFollowupAt, c.remark]);
    });
    const csv = lines.map((row) => row.map((cell) => `"${String(cell || "").replace(/"/g, '""')}"`).join(",")).join("\r\n");
    res.writeHead(200, {
      "Content-Type": "text/csv; charset=utf-8",
      "Content-Disposition": "attachment; filename=sales-crm-customers.csv"
    });
    res.end("\ufeff" + csv);
    return;
  }
 
  if (req.method !== "POST") {
    json(res, 405, { error: "Method not allowed" });
    return;
  }
 
  const body = await parseBody(req);
  const account = requireAccount(req, url, body, data);
  const user = account.name;
 
  if (url.pathname === "/api/duplicates") {
    json(res, 200, { duplicates: duplicateCandidates(data, body) });
    return;
  }
 
  if (url.pathname === "/api/accounts/save") {
    requireSupervisor(account);
    const username = String(body.username || body.phone || "").trim();
    const phone = String(body.phone || username).trim();
    const name = String(body.name || "").trim();
    const password = String(body.password || "").trim();
    const roleValue = String(body.role || "").trim();
    const status = body.status === "disabled" ? "disabled" : "active";
    const permissions = Object.prototype.hasOwnProperty.call(body, "permissions")
      ? parsePermissions(body.permissions)
      : defaultPermissions(roleValue);
    if (!username || !name || !accountRoles.includes(roleValue)) {
      json(res, 400, { error: "请填写账号、姓名和岗位" });
      return;
    }
    const accountRows = getUsers(data);
    let row = accountRows.find((item) => item.username === username);
    if (!row && accountRows.some((item) => item.phone === phone)) {
      json(res, 409, { error: "这个手机号已经存在账号" });
      return;
    }
    if (!row && !password) {
      json(res, 400, { error: "新增账号必须设置初始密码" });
      return;
    }
    if (row && row.username === account.username && status === "disabled") {
      json(res, 400, { error: "不能停用当前登录的主管账号" });
      return;
    }
    if (row) {
      row.name = name;
      row.phone = phone;
      row.role = roleValue;
      row.status = status;
      row.permissions = permissions;
      if (password) row.password = password;
      row.updatedAt = nowText();
    } else {
      row = {
        username,
        phone,
        password,
        name,
        role: roleValue,
        status,
        permissions,
        createdAt: nowText(),
        updatedAt: ""
      };
      accountRows.push(row);
    }
    save(data);
    json(res, 200, { account: publicUser(row), accounts: accountRows.map(publicUser) });
    return;
  }
 
  if (url.pathname === "/api/accounts/status") {
    requireSupervisor(account);
    const username = String(body.username || "").trim();
    const status = body.status === "disabled" ? "disabled" : "active";
    if (!username || username === account.username) {
      json(res, 400, { error: "不能修改当前登录账号状态" });
      return;
    }
    const row = getUsers(data).find((item) => item.username === username);
    if (!row) {
      json(res, 404, { error: "账号不存在" });
      return;
    }
    row.status = status;
    row.updatedAt = nowText();
    save(data);
    json(res, 200, { account: publicUser(row), accounts: getUsers(data).map(publicUser) });
    return;
  }
 
  if (url.pathname === "/api/accounts/transfer") {
    requireSupervisor(account);
    const from = String(body.from || "").trim();
    const to = String(body.to || "").trim();
    if (!from || !to || from === to) {
      json(res, 400, { error: "请选择原负责人和新负责人" });
      return;
    }
    const users = getUsers(data);
    const target = users.find((item) => item.name === to && item.role === "sales" && item.status !== "disabled");
    if (!target) {
      json(res, 400, { error: "新负责人必须是启用中的销售账号" });
      return;
    }
    let count = 0;
    for (const customer of data.customers) {
      if (customer.owner === from) {
        customer.previousOwner = customer.owner;
        customer.owner = to;
        customer.pool = customer.pool || "正常";
        action(data, customer, user, "transfer_owner", "客户负责人转接", `${from} -> ${to}`);
        count++;
      }
    }
    save(data);
    json(res, 200, { ok: true, count });
    return;
  }
 
  if (url.pathname === "/api/reminders") {
    data.manualReminders = data.manualReminders || [];
    const reminder = { id: Date.now(), customerId: Number(body.customerId) || null, customer: body.customer || "", user, dueDate: body.dueDate || today(), content: body.content || "", status: "open", createdAt: nowText() };
    data.manualReminders.unshift(reminder);
    save(data);
    json(res, 200, { reminder });
    return;
  }
 
  if (url.pathname === "/api/reminders/complete") {
    data.manualReminders = data.manualReminders || [];
    const reminder = data.manualReminders.find((r) => r.id === Number(body.id));
    if (reminder) reminder.status = "done";
    save(data);
    json(res, 200, { reminder });
    return;
  }
 
  if (url.pathname === "/api/run-rules") {
    const now = new Date(today() + "T00:00:00");
    for (const c of data.customers) {
      if (c.pool === "公共客户池") continue;
      if (dealStatuses.includes(c.dealStatus)) continue;
      const base = c.lastEffectiveFollowupAt || c.firstInputAt?.slice(0, 10);
      if (!base) continue;
      const days = Math.floor((now - new Date(base + "T00:00:00")) / 86400000);
      if (days >= 30) {
        c.previousOwner = c.owner;
        c.pool = "公共客户池";
        c.poolReason = `自动公海:${days}天无有效跟进`;
        c.releasedAt = nowText();
        c.protect = "已过期";
        action(data, c, "系统", "auto_public_pool", "自动进入公海", c.poolReason);
      }
    }
    save(data);
    json(res, 200, { ok: true });
    return;
  }
 
  if (url.pathname === "/api/customers/delete") {
    if (account.role !== "supervisor") {
      json(res, 403, { error: "只有主管可以删除客户" });
      return;
    }
    const index = data.customers.findIndex((c) => c.id === Number(body.customerId));
    if (index < 0) {
      json(res, 404, { error: "客户不存在" });
      return;
    }
    const [removed] = data.customers.splice(index, 1);
    action(data, removed, user, "delete_customer", "删除客户", `${removed.name} / ${removed.company}`);
    save(data);
    json(res, 200, { ok: true });
    return;
  }
 
  if (url.pathname === "/api/customers") {
    if (!body.name || !body.company) {
      json(res, 400, { error: "客户姓名和公司名称必填" });
      return;
    }
    if (!body.phone && !body.wechat && !body.platformAccount && !body.leadId) {
      json(res, 400, { error: "手机号、微信、平台账号、线索ID至少填写一项" });
      return;
    }
    const strongDup = duplicateCandidates(data, body).find((row) => row.strong || row.reasons.includes("公司名称相同"));
    if (strongDup) {
      json(res, 409, { error: `发现强重复客户:${strongDup.name} / ${strongDup.company},不能重复录入`, duplicate: strongDup });
      return;
    }
    const customer = {
      id: data.nextCustomerId++,
      name: body.name || "",
      company: body.company || "",
      phone: body.phone || "",
      wechat: body.wechat || "",
      platformAccount: body.platformAccount || "",
      source: body.source || "",
      customerCategory: body.customerCategory || body.source || "",
      trafficCostType: body.trafficCostType || "免费",
      searchTerm: body.searchTerm || "",
      keyword: body.keyword || "",
      trafficTimeSlot: body.trafficTimeSlot || "",
      customerType: body.customerType || "",
      opRegion: body.opRegion || body.region || "",
      trafficType: body.trafficType || "",
      marketingType: body.marketingType || "",
      interactionScene: body.interactionScene || "",
      conversionStatus: body.conversionStatus || "",
      leadId: body.leadId || "",
      douyinCustomerId: body.douyinCustomerId || "",
      sourceAccount: body.sourceAccount || "",
      contentName: body.contentName || "",
      contentLink: body.contentLink || "",
      campaignId: body.campaignId || "",
      unitId: body.unitId || "",
      unitName: body.unitName || "",
      isPrivateLead: body.isPrivateLead || "",
      leadCreatedAt: body.leadCreatedAt || "",
      lastLeaveAt: body.lastLeaveAt || "",
      leaveCount: body.leaveCount || "",
      opsOwner: body.opsOwner || "",
      owner: account.role === "sales" ? user : (body.owner || "销售一"),
      firstReceiver: body.firstReceiver || user,
      firstInputAt: nowText(),
      firstConsultAt: body.firstConsultAt || nowText(),
      region: body.region || "",
      scene: body.scene || "",
      demand: body.demand || "",
      params: body.params || "",
      intention: body.intention || "C",
      level: body.intention || "C",
      funnel: body.funnel || "S1 新线索",
      stage: body.stage || "初询",
      dealStatus: body.dealStatus || "未成交",
      dealAt: "",
      dealAmount: "",
      dealProduct: "",
      dealQuantity: "",
      dealUnitPrice: "",
      dealTotalPrice: "",
      revisitLevel: body.revisitLevel || "铜",
      nextDealRevisit: "",
      protect: "保护中",
      protectEnd: body.protectEnd || "",
      pool: "正常",
      poolReason: "",
      releasedAt: "",
      previousOwner: "",
      nextFollowupAt: body.nextFollowupAt || "",
      lastEffectiveFollowupAt: "",
      remark: body.remark || "",
      followups: [],
      quotes: [],
      dealRevisits: [],
      actions: []
    };
    action(data, customer, user, "create_customer", "新增客户", "录入客户并生成首次录入记录");
    data.customers.unshift(customer);
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/business/create") {
    const kind = String(body.kind || "");
    const meta = businessKinds[kind];
    if (!meta) {
      json(res, 400, { error: "业务类型不正确" });
      return;
    }
    const row = {
      ...(body.row || {}),
      id: data[meta.next]++,
      createdBy: user,
      createdAt: nowText(),
      updatedAt: nowText()
    };
    if (!row.status) row.status = "待处理";
    data[kind].unshift(row);
    save(data);
    json(res, 200, { row });
    return;
  }
 
  if (url.pathname === "/api/business/update") {
    const kind = String(body.kind || "");
    const meta = businessKinds[kind];
    if (!meta) {
      json(res, 400, { error: "业务类型不正确" });
      return;
    }
    const row = data[kind].find((item) => item.id === Number(body.id));
    if (!row) {
      json(res, 404, { error: "记录不存在" });
      return;
    }
    Object.assign(row, body.patch || {}, { updatedBy: user, updatedAt: nowText() });
    save(data);
    json(res, 200, { row });
    return;
  }
 
  if (url.pathname === "/api/business/delete") {
    const kind = String(body.kind || "");
    if (!businessKinds[kind]) {
      json(res, 400, { error: "业务类型不正确" });
      return;
    }
    const index = data[kind].findIndex((item) => item.id === Number(body.id));
    if (index < 0) {
      json(res, 404, { error: "记录不存在" });
      return;
    }
    const [row] = data[kind].splice(index, 1);
    save(data);
    json(res, 200, { row });
    return;
  }
 
  const customer = data.customers.find((c) => c.id === Number(body.customerId));
  if (!customer) {
    json(res, 404, { error: "客户不存在" });
    return;
  }
  requireCustomerAccess(account, customer);
 
  if (url.pathname === "/api/customers/update") {
    const fields = ["name", "company", "phone", "wechat", "platformAccount", "source", "customerCategory", "trafficCostType", "searchTerm", "keyword", "trafficTimeSlot", "customerType", "opRegion", "trafficType", "marketingType", "interactionScene", "conversionStatus", "leadId", "douyinCustomerId", "sourceAccount", "contentName", "contentLink", "campaignId", "unitId", "unitName", "isPrivateLead", "leadCreatedAt", "lastLeaveAt", "leaveCount", "opsOwner", "owner", "firstReceiver", "firstInputAt", "region", "scene", "demand", "params", "intention", "funnel", "stage", "dealStatus", "pool", "poolReason", "nextFollowupAt", "remark"];
    for (const field of fields) {
      if (field === "owner" && account.role !== "supervisor") continue;
      if (Object.prototype.hasOwnProperty.call(body, field)) customer[field] = body[field] || "";
    }
    action(data, customer, user, "update_customer", "编辑客户信息", "修改客户基础资料");
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/followups") {
    const row = { at: body.at || today(), user, channel: body.channel || "电话", content: body.content || "", next: body.nextFollowupAt || "", effective: !!body.effective };
    customer.followups.unshift(row);
    customer.nextFollowupAt = row.next || customer.nextFollowupAt;
    if (row.effective) customer.lastEffectiveFollowupAt = row.at;
    if (body.funnel) {
      const before = customer.funnel;
      customer.funnel = body.funnel;
      customer.stage = body.stage || body.funnel.replace(/^S\d+\s*/, "");
      if (before !== customer.funnel) {
        action(data, customer, user, "change_funnel_stage", "调整客户阶段", `${before || "未设置"} -> ${customer.funnel}`);
      }
    }
    action(data, customer, user, "add_followup", "新增跟进记录", row.content);
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/quotes") {
    customer.quotes = customer.quotes || [];
    const quantity = Number(body.quantity || 0);
    const unitPrice = Number(body.unitPrice || 0);
    const totalPrice = body.totalPrice || (quantity && unitPrice ? String(quantity * unitPrice) : "");
    const row = {
      at: body.at || today(),
      user,
      model: body.model || "",
      quantity: body.quantity || "",
      unitPrice: body.unitPrice || "",
      amount: totalPrice,
      priceType: body.priceType || "标准价",
      approval: body.approval || "无需审批",
      quoteNo: body.quoteNo || "",
      remark: body.remark || ""
    };
    customer.quotes.unshift(row);
    action(data, customer, user, "add_quote", "新增报价记录", `${row.model} ${row.amount}`);
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/followups/update") {
    const index = Number(body.followupIndex);
    if (!customer.followups || !customer.followups[index]) {
      json(res, 404, { error: "跟进记录不存在" });
      return;
    }
    customer.followups[index] = {
      ...customer.followups[index],
      channel: body.channel || customer.followups[index].channel,
      content: body.content || "",
      next: body.nextFollowupAt || "",
      effective: !!body.effective
    };
    action(data, customer, user, "update_followup", "编辑跟进记录", customer.followups[index].content);
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/followups/delete") {
    const index = Number(body.followupIndex);
    if (!customer.followups || !customer.followups[index]) {
      json(res, 404, { error: "跟进记录不存在" });
      return;
    }
    const [removed] = customer.followups.splice(index, 1);
    action(data, customer, user, "delete_followup", "删除跟进记录", removed.content || "");
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/deal") {
    const nextStatus = body.dealStatus || "未成交";
    customer.dealStatus = nextStatus;
    if (nextStatus === "未成交") {
      customer.stage = body.stage || "初询";
      customer.funnel = body.funnel || "S2 已联系";
      customer.dealAt = "";
      customer.dealAmount = "";
      customer.dealProduct = "";
      customer.dealQuantity = "";
      customer.dealUnitPrice = "";
      customer.dealTotalPrice = "";
      customer.nextDealRevisit = "";
      action(data, customer, user, "update_deal_status", "修改成交状态", "已改为未成交,并清空成交信息");
    } else {
      customer.stage = "成交";
      customer.funnel = "S7 成交/执行";
      customer.dealAt = body.dealAt || today();
      customer.dealAmount = body.dealAmount || "";
      customer.dealProduct = body.dealProduct || "";
      customer.dealQuantity = body.dealQuantity || "";
      customer.dealUnitPrice = body.dealUnitPrice || "";
      customer.dealTotalPrice = body.dealTotalPrice || body.dealAmount || "";
      customer.revisitLevel = body.revisitLevel || customer.revisitLevel || "铜";
      customer.nextDealRevisit = body.nextDealRevisit || addDays(customer.dealAt, 7);
      action(data, customer, user, "mark_deal", "修改成交状态", `${nextStatus} ${customer.dealProduct} ${customer.dealAmount}`);
    }
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/deal-revisits") {
    const row = { at: body.at || today(), user, result: body.result || "", next: body.nextDealRevisit || "" };
    customer.dealRevisits.unshift(row);
    customer.nextDealRevisit = row.next || customer.nextDealRevisit;
    action(data, customer, user, "add_deal_revisit", "新增成交回访", row.result);
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/release") {
    if (account.role !== "supervisor") {
      json(res, 403, { error: "只有主管可以释放客户到公海" });
      return;
    }
    customer.previousOwner = customer.owner;
    customer.pool = "公共客户池";
    customer.poolReason = body.reason || "主管释放";
    customer.releasedAt = nowText();
    customer.protect = "已过期";
    action(data, customer, user, "release_to_pool", "释放到公海", customer.poolReason);
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  if (url.pathname === "/api/assign") {
    if (account.role !== "supervisor") {
      json(res, 403, { error: "只有主管可以分配公海客户" });
      return;
    }
    const to = body.owner || "销售一";
    const target = getUsers(data).find((item) => item.name === to && item.role === "sales" && item.status !== "disabled");
    if (!target) {
      json(res, 400, { error: "只能分配给启用中的销售账号" });
      return;
    }
    customer.previousOwner = customer.owner;
    customer.owner = to;
    customer.pool = "正常";
    customer.poolReason = "";
    action(data, customer, user, "assign_from_pool", "公海重新分配", `分配给 ${to}`);
    save(data);
    json(res, 200, { customer });
    return;
  }
 
  json(res, 404, { error: "API not found" });
}
 
function serveFile(req, res) {
  const url = new URL(req.url, `http://${req.headers.host}`);
  let pathname = decodeURIComponent(url.pathname);
  if (pathname === "/") pathname = "/sales_crm_full_demo.html";
  const file = path.resolve(root, `.${pathname}`);
  if (!file.startsWith(root)) {
    res.writeHead(403);
    res.end("Forbidden");
    return;
  }
  fs.readFile(file, (err, data) => {
    if (err) {
      res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
      res.end("Not found");
      return;
    }
    const ext = path.extname(file).toLowerCase();
    const type = ext === ".html" ? "text/html; charset=utf-8" : "application/octet-stream";
    res.writeHead(200, { "Content-Type": type });
    res.end(data);
  });
}
 
const server = http.createServer((req, res) => {
  if (req.url.startsWith("/api/")) {
    handleApi(req, res).catch((err) => json(res, err.status || 500, { error: err.message }));
  } else {
    serveFile(req, res);
  }
});
 
ensureData();
server.listen(port, "0.0.0.0", () => {
  console.log(`Full CRM demo is running at http://127.0.0.1:${port}/`);
});