customer-broker-store.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. const fs = require('fs');
  2. const path = require('path');
  3. const { categoryDir } = require('./output-paths');
  4. function customersDir() {
  5. return categoryDir('customers');
  6. }
  7. function brokersDir() {
  8. return categoryDir('brokers');
  9. }
  10. function customerFilePath(customerId) {
  11. return path.join(customersDir(), `${customerId}.json`);
  12. }
  13. function brokerFilePath(brokerId) {
  14. return path.join(brokersDir(), `${brokerId}.json`);
  15. }
  16. function phoneIndexPath() {
  17. return path.join(customersDir(), 'index-phone.json');
  18. }
  19. function externalUserIdIndexPath() {
  20. return path.join(customersDir(), 'index-external-user-id.json');
  21. }
  22. function safeReadJson(filePath, fallback = null) {
  23. try {
  24. if (!filePath || !fs.existsSync(filePath)) return fallback;
  25. return JSON.parse(fs.readFileSync(filePath, 'utf8'));
  26. } catch {
  27. return fallback;
  28. }
  29. }
  30. function atomicWriteJson(filePath, data) {
  31. const dir = path.dirname(filePath);
  32. fs.mkdirSync(dir, { recursive: true });
  33. const tmpPath = `${filePath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
  34. try {
  35. fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf8');
  36. fs.renameSync(tmpPath, filePath);
  37. } catch (err) {
  38. try { fs.unlinkSync(tmpPath); } catch {}
  39. throw err;
  40. }
  41. return filePath;
  42. }
  43. function normalizePhone(raw) {
  44. if (!raw) return '';
  45. let value = String(raw).trim().replace(/[^\d]/g, '');
  46. if (value.length >= 12 && /^(?:86)?1[3-9]\d{9}$/.test(value)) value = value.replace(/^86/, '');
  47. return value;
  48. }
  49. function buildCustomerId(input = {}) {
  50. if (input.customerId) return String(input.customerId).trim();
  51. if (input.externalUserId) return String(input.externalUserId).trim();
  52. const phone = normalizePhone(input.phone);
  53. if (phone) return phone;
  54. return `cust-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
  55. }
  56. function readCustomerById(customerId) {
  57. if (!customerId) return null;
  58. return safeReadJson(customerFilePath(customerId));
  59. }
  60. function writeCustomer(customer) {
  61. if (!customer || !customer.customerId) throw new Error('customer.customerId 必填');
  62. const filePath = customerFilePath(customer.customerId);
  63. const existing = safeReadJson(filePath) || {};
  64. const now = new Date().toISOString();
  65. const record = {
  66. ...existing,
  67. ...customer,
  68. customerId: customer.customerId,
  69. createdAt: existing.createdAt || now,
  70. updatedAt: now
  71. };
  72. atomicWriteJson(filePath, record);
  73. rebuildCustomerIndexIfNeeded();
  74. return record;
  75. }
  76. function readPhoneIndex() {
  77. return safeReadJson(phoneIndexPath(), {});
  78. }
  79. function readExternalUserIdIndex() {
  80. return safeReadJson(externalUserIdIndexPath(), {});
  81. }
  82. function writePhoneIndex(index) {
  83. atomicWriteJson(phoneIndexPath(), index);
  84. }
  85. function writeExternalUserIdIndex(index) {
  86. atomicWriteJson(externalUserIdIndexPath(), index);
  87. }
  88. function rebuildCustomerIndexIfNeeded() {
  89. const dir = customersDir();
  90. if (!fs.existsSync(dir)) return;
  91. const phoneIndex = {};
  92. const externalUserIdIndex = {};
  93. for (const file of fs.readdirSync(dir)) {
  94. if (!file.endsWith('.json') || file.startsWith('index-')) continue;
  95. const customerId = file.replace(/\.json$/, '');
  96. const customer = safeReadJson(path.join(dir, file));
  97. if (!customer) continue;
  98. const phone = normalizePhone(customer.phone);
  99. if (phone) phoneIndex[phone] = customer.customerId || customerId;
  100. if (customer.externalUserId) externalUserIdIndex[customer.externalUserId] = customer.customerId || customerId;
  101. }
  102. writePhoneIndex(phoneIndex);
  103. writeExternalUserIdIndex(externalUserIdIndex);
  104. }
  105. function readCustomerByExternalUserId(externalUserId) {
  106. if (!externalUserId) return null;
  107. const index = readExternalUserIdIndex();
  108. const customerId = index[externalUserId];
  109. if (customerId) {
  110. const customer = readCustomerById(customerId);
  111. if (customer) return customer;
  112. }
  113. // fallback: 扫描文件
  114. const dir = customersDir();
  115. if (!fs.existsSync(dir)) return null;
  116. for (const file of fs.readdirSync(dir)) {
  117. if (!file.endsWith('.json') || file.startsWith('index-')) continue;
  118. const customer = safeReadJson(path.join(dir, file));
  119. if (customer && customer.externalUserId === externalUserId) return customer;
  120. }
  121. return null;
  122. }
  123. function readCustomerByPhone(phone) {
  124. const normalized = normalizePhone(phone);
  125. if (!normalized) return null;
  126. const index = readPhoneIndex();
  127. const customerId = index[normalized];
  128. if (customerId) {
  129. const customer = readCustomerById(customerId);
  130. if (customer) return customer;
  131. }
  132. // fallback: 扫描文件
  133. const dir = customersDir();
  134. if (!fs.existsSync(dir)) return null;
  135. for (const file of fs.readdirSync(dir)) {
  136. if (!file.endsWith('.json') || file.startsWith('index-')) continue;
  137. const customer = safeReadJson(path.join(dir, file));
  138. if (customer && normalizePhone(customer.phone) === normalized) return customer;
  139. }
  140. return null;
  141. }
  142. function readBrokerById(brokerId) {
  143. if (!brokerId) return null;
  144. return safeReadJson(brokerFilePath(brokerId));
  145. }
  146. function writeBroker(broker) {
  147. if (!broker || !broker.brokerId) throw new Error('broker.brokerId 必填');
  148. const filePath = brokerFilePath(broker.brokerId);
  149. const existing = safeReadJson(filePath) || {};
  150. const now = new Date().toISOString();
  151. const guidList = Array.from(new Set([
  152. ...(existing.guidList || []),
  153. ...(broker.guidList || [])
  154. ].filter(Boolean)));
  155. const record = {
  156. ...existing,
  157. ...broker,
  158. brokerId: broker.brokerId,
  159. guidList,
  160. createdAt: existing.createdAt || now,
  161. updatedAt: now
  162. };
  163. atomicWriteJson(filePath, record);
  164. return record;
  165. }
  166. function readBrokerByWecomUserId(wecomUserId) {
  167. if (!wecomUserId) return null;
  168. const dir = brokersDir();
  169. if (!fs.existsSync(dir)) return null;
  170. for (const file of fs.readdirSync(dir)) {
  171. if (!file.endsWith('.json')) continue;
  172. const broker = safeReadJson(path.join(dir, file));
  173. if (broker && broker.wecomUserId === wecomUserId) return broker;
  174. }
  175. return null;
  176. }
  177. function bindBrokerToDevice(brokerId, guid) {
  178. if (!brokerId || !guid) return null;
  179. const broker = readBrokerById(brokerId) || { brokerId };
  180. broker.guidList = Array.from(new Set([...(broker.guidList || []), guid].filter(Boolean)));
  181. return writeBroker(broker);
  182. }
  183. function buildCustomerPhoneIndex() {
  184. rebuildCustomerIndexIfNeeded();
  185. return readPhoneIndex();
  186. }
  187. function buildCustomerExternalUserIdIndex() {
  188. rebuildCustomerIndexIfNeeded();
  189. return readExternalUserIdIndex();
  190. }
  191. module.exports = {
  192. normalizePhone,
  193. buildCustomerId,
  194. readCustomerById,
  195. writeCustomer,
  196. readCustomerByExternalUserId,
  197. readCustomerByPhone,
  198. readBrokerById,
  199. writeBroker,
  200. readBrokerByWecomUserId,
  201. bindBrokerToDevice,
  202. buildCustomerPhoneIndex,
  203. buildCustomerExternalUserIdIndex,
  204. customerFilePath,
  205. brokerFilePath,
  206. phoneIndexPath,
  207. externalUserIdIndexPath
  208. };