@infly/libs 2.0.25 → 2.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,88 +1,89 @@
1
- {
2
- "name": "@infly/libs",
3
- "version": "2.0.25",
4
- "description": "工具组件库",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1",
8
- "postinstall": "node index.js",
9
- "publishPkg": "npm version patch && npm publish --access=public --registry=https://registry.npmjs.org/",
10
- "preview": "infly-libs --preview",
11
- "preview:no-build": "infly-libs --preview --no-build"
12
- },
13
- "bin": {
14
- "infly-libs": "bin/cli.js"
15
- },
16
- "exports": {
17
- "./module/*": "./module/*",
18
- "./dataInit/*": "./dataInit/*",
19
- "./tools/*": "./tools/*",
20
- "./store/*": "./store/*",
21
- "./build/*": "./build/*"
22
- },
23
- "repository": {
24
- "type": "git",
25
- "url": "https://gitee.com/kahal/npm-package"
26
- },
27
- "keywords": [
28
- "infly",
29
- "infly-libs",
30
- "libs"
31
- ],
32
- "types-为了直接点击进入引用文件所以去掉": "types/index.d.ts",
33
- "author": "Kahal",
34
- "license": "ISC",
35
- "dependencies": {},
36
- "devDependencies-仅在需要webpack时候删除": {
37
- "@babel/core": "^7.27.3",
38
- "@babel/preset-env": "^7.27.2",
39
- "babel-loader": "^10.0.0",
40
- "webpack": "^5.99.9",
41
- "webpack-cli": "^6.0.1",
42
- "webpack-node-externals": "^3.0.0"
43
- },
44
- "peerDependencies": {
45
- "axios": "^0.27.2",
46
- "html-webpack-plugin": "^5.5.3"
47
- },
48
- "optionalDependencies": {
49
- "axios": "^0.27.2",
50
- "html-webpack-plugin": "^5.5.3"
51
- },
52
- "infly": {
53
- "zipOptions": {
54
- "buildFoldName": "[构建后目录名] 可选, 默认取值vue.config.js的outputDir, 配置化 eg: postal-benefits-level-pc",
55
- "outputPath": "[输出文件目录链接] eg: ./ ",
56
- "enabled": "[是否启用压缩] eg: true",
57
- "gitAuto": "[是否自动提交git] eg: true",
58
- "gitAutoPushRepos": "[自动提交推送git构建仓库] eg: frontend",
59
- "gitAutoPushReposBranchMap": {
60
- "release-eg": "develop-eg [自动提交推送项目构建分支和构建仓库推送分支对应配置,必须]"
61
- },
62
- "gitAutoCommitText": "[自动提交文案] eg: build: 更新版本为v{version}, 推送构建文件与zip压缩包 --build by infly-libs",
63
- "enablePreview": "[是否启用项目预览] eg: true",
64
- "enableClipboard": "[是否启用粘贴板粘贴git信息] eg: true",
65
- "openExplorer": "[是否自动打开资源管理器] eg: true",
66
- "webhookUrl": "[消息推送机器人链接配置] eg: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2417edd3-8f74-4c30-a7a8-5a72826d40d2",
67
- "webhookAtUser": [
68
- "@人手机号"
69
- ],
70
- "webhookExtraText": "[消息推送额外文案] eg: 麻烦发下版",
71
- "compressionLevel": 9
72
- },
73
- "versionConfig": {
74
- "mainVersion": "[主版本号] 可选, 默认取值项目package version, eg: 1",
75
- "links": {
76
- "master": "[master分支构建文件推送地址] eg: e.sutpay.com",
77
- "release": "[release分支构建文件推送地址] eg: http://114.132.55.214:8081/"
78
- },
79
- "platformName": "[用以split的项目平台名称] eg: 邮惠权益平台-运营端",
80
- "baseName": "v{version}-{timestamp}.zip",
81
- "versionList": [],
82
- "disableUpdateVersionEnv": [
83
- "development",
84
- "staging [禁用更新版本号的环境, 比如测试环境构建不需要更新version, 不配置默认禁用stage测试环境]"
85
- ]
86
- }
87
- }
88
- }
1
+ {
2
+ "name": "@infly/libs",
3
+ "version": "2.0.36",
4
+ "description": "工具组件库",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1",
8
+ "postinstall": "node index.js",
9
+ "publishPkg": "npm version patch && npm publish --access=public --registry=https://registry.npmjs.org/",
10
+ "preview": "infly-libs --preview",
11
+ "preview:no-build": "infly-libs --preview --no-build",
12
+ "origin:preview": "infly-libs --preview",
13
+ "origin:preview:no-build": "infly-libs --preview --no-build"
14
+ },
15
+ "bin": {
16
+ "infly-libs": "bin/cli.js"
17
+ },
18
+ "exports": {
19
+ "./module/*": "./module/*",
20
+ "./dataInit/*": "./dataInit/*",
21
+ "./tools/*": "./tools/*",
22
+ "./store/*": "./store/*",
23
+ "./build/*": "./build/*"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://gitee.com/kahal/npm-package"
28
+ },
29
+ "keywords": [
30
+ "infly",
31
+ "infly-libs",
32
+ "libs"
33
+ ],
34
+ "types-为了直接点击进入引用文件所以去掉": "types/index.d.ts",
35
+ "author": "Kahal",
36
+ "license": "ISC",
37
+ "dependencies": {},
38
+ "devDependencies-仅在需要webpack时候删除": {
39
+ "@babel/core": "^7.27.3",
40
+ "@babel/preset-env": "^7.27.2",
41
+ "babel-loader": "^10.0.0",
42
+ "webpack": "^5.99.9",
43
+ "webpack-cli": "^6.0.1",
44
+ "webpack-node-externals": "^3.0.0"
45
+ },
46
+ "peerDependencies": {
47
+ "axios": "^0.27.2",
48
+ "html-webpack-plugin": "^5.5.3"
49
+ },
50
+ "optionalDependencies": {
51
+ "axios": "^0.27.2",
52
+ "html-webpack-plugin": "^5.5.3"
53
+ },
54
+ "infly": {
55
+ "buildConfigs": {
56
+ "buildFoldName": "[构建后目录名] 可选, 默认取值vue.config.js的outputDir, 配置化 eg: postal-benefits-level-pc",
57
+ "outputPath": "[输出文件目录链接] eg: ./ ",
58
+ "enabled": "[是否启用压缩] eg: true",
59
+ "gitAuto": "[是否自动提交git] eg: true",
60
+ "gitAutoPushReposBranchMap": {
61
+ "release-eg": "develop-eg [自动提交推送项目构建分支和构建仓库推送分支对应配置,必须]"
62
+ },
63
+ "gitAutoCommitText": "[自动提交文案] eg: build: 更新版本为v{version}, 推送构建文件与zip压缩包 --build by infly-libs",
64
+ "enablePreview": "[是否启用项目预览] eg: true",
65
+ "enableClipboard": "[是否启用粘贴板粘贴git信息] eg: true",
66
+ "openExplorer": "[是否自动打开资源管理器] eg: true",
67
+ "webhookUrl": "[消息推送机器人链接配置] eg: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2417edd3-8f74-4c30-a7a8-5a72826d40d2",
68
+ "webhookAtUser": [
69
+ "@人手机号"
70
+ ],
71
+ "webhookExtraText": "[消息推送额外文案] eg: 麻烦发下版",
72
+ "compressionLevel": 9
73
+ },
74
+ "versionConfig": {
75
+ "mainVersion": "[主版本号] 可选, 默认取值项目package version, eg: 1",
76
+ "links": {
77
+ "master": "[master分支构建文件推送地址] eg: https://e.sutpay.com",
78
+ "release": "[release分支构建文件推送地址] eg: http://114.132.55.214:8081/"
79
+ },
80
+ "platformName": "[用以split的项目平台名称] eg: 邮惠权益平台-运营端",
81
+ "baseName": "v{version}-{timestamp}.zip",
82
+ "versionList": [],
83
+ "disableUpdateVersionEnv": [
84
+ "development",
85
+ "staging [禁用更新版本号的环境, 比如测试环境构建不需要更新version, 不配置默认禁用stage测试环境]"
86
+ ]
87
+ }
88
+ }
89
+ }
@@ -84,7 +84,10 @@ function getLastCommitByFile(filePath) {
84
84
  * @param {String} gitStatusLine 带文件状态的
85
85
  * @returns
86
86
  */
87
- function isBuildFile(targetProjectOutputDir = "", gitLine = "", sliceLen = -2) {
87
+ function isBuildFile(targetProjectOutputDir = "", gitLine = "", sliceLen = -1) {
88
+ if (!targetProjectOutputDir) {
89
+ return true;
90
+ }
88
91
  // 统一路径分隔符
89
92
  targetProjectOutputDir = targetProjectOutputDir.replace(/\\/g, "/");
90
93
 
@@ -119,25 +122,23 @@ function checkGitStatus(excludeDir, extraFilter, extraParams) {
119
122
  const files = execSync(`git${targetProjectOutputDirCmd} status --porcelain -z`, { encoding: "utf8" })
120
123
  .toString()
121
124
  .split("\u0000")
122
- .filter((line) => line.trim());
123
- // .map((line) => line.substring(3).trim()); // 提取文件路径
125
+ .filter((file) => file.trim() && isBuildFile(targetProjectOutputDir, file));
124
126
  const excludeFiles = []; // 非指定构建相关文件
125
127
  const includeFiles = []; // 指定的构建相关文件
126
128
 
127
- if (onlyCheckStatus) {
129
+ if (onlyCheckStatus || targetProjectOutputDirCmd) {
128
130
  return files || [];
129
131
  }
130
132
 
131
133
  console.log(global.logColor.success, `🚀 ${startLogText}`);
132
134
 
135
+ // 进行当前项目文件检查,如果有其它非配置文件则取消自动提交改为用户手动确认
133
136
  files.forEach((file) => {
134
137
  const existsDelFile = deleteOldFile.find((item) => file.includes(item));
135
138
  if (
136
139
  file.includes(`${excludeDir}/`) ||
137
140
  file.includes(versionFileName) ||
138
141
  file.includes(extraFilter) ||
139
- isBuildFile(targetProjectOutputDir, file) ||
140
- file.includes(`${gitAutoPushRepos}/`) || // 放宽文件判断条件,因为可能存在同时构建frontend/ea、frontend/e的情况
141
142
  existsDelFile
142
143
  ) {
143
144
  includeFiles.push(file);
@@ -149,6 +150,8 @@ function checkGitStatus(excludeDir, extraFilter, extraParams) {
149
150
  if (excludeFiles.length > 0) {
150
151
  throw new Error(`存在非构建文件未提交,请手动确定提交信息,本次自动提交终止\n${excludeFiles.join("\n")}`);
151
152
  }
153
+
154
+ return includeFiles || [];
152
155
  } catch (err) {
153
156
  console.error(global.logColor.error, `❌ 自动化构建Git状态检查存在问题:${err.message}`);
154
157
  process.exit(1);
@@ -186,8 +189,11 @@ function autoGitProcess(buildFoldName, newFileName, extraParams = {}) {
186
189
  targetProjectOutputDir,
187
190
  gitAutoPushReposBranchMap = {},
188
191
  targetProjectOutputDirCmd = gitAutoPushRepos ? ` -C ${targetProjectOutputDir}` : "",
189
- projectName,
192
+ projectName
190
193
  } = extraParams || {};
194
+ // 每次执行自动分支提交先先进行校验
195
+ const fileList = checkGitStatus(buildFoldName, newFileName, extraParams) || [];
196
+
191
197
  const { commitMsg, branch } = gitInfo || {};
192
198
  const gitRepos = gitAutoPushRepos ? `构建仓库: ${targetProjectOutputDir}` : `当前项目: ${projectName}`;
193
199
  let tempGitAutoCommitText = gitAutoCommitText ? gitAutoCommitText.replace("{version}", newVersion) : "";
@@ -211,17 +217,21 @@ function autoGitProcess(buildFoldName, newFileName, extraParams = {}) {
211
217
  }
212
218
 
213
219
  // 先执行构建仓库的推送,防止git提交信息被覆盖
214
- runGitCommand(addCmd);
215
- runGitCommand(commitCmd);
216
- runGitCommand(pushCommand);
220
+ if (fileList.length > 0) {
221
+ runGitCommand(addCmd);
222
+ runGitCommand(commitCmd);
223
+ runGitCommand(pushCommand);
224
+ }
217
225
 
218
226
  // 后执行当前项目的分支自动推送
219
227
  if (gitAutoPushRepos) {
220
- const overrideParams = { ...extraParams, gitAutoPushRepos: false };
221
- const fileList = checkGitStatus(buildFoldName, newFileName, { ...overrideParams, onlyCheckStatus: true });
222
- if (fileList.length > 0) {
223
- autoGitProcess(buildFoldName, newFileName, overrideParams); // 执行自动推送当前项目的git信息
224
- }
228
+ const overrideParams = {
229
+ ...extraParams,
230
+ targetProjectOutputDir: "",
231
+ targetProjectOutputDirCmd: "",
232
+ gitAutoPushRepos: false
233
+ }; // 确保所有配置为非构建仓库配置
234
+ autoGitProcess(buildFoldName, newFileName, overrideParams); // 执行自动推送当前项目的git信息
225
235
  }
226
236
 
227
237
  console.log(global.logColor.success, `✅ Git \x1b[34m${gitRepos}\x1b[32m 自动提交和推送成功!`);
@@ -240,6 +250,7 @@ async function autoBranchProcess(config) {
240
250
  const pullCmd = `git${targetProjectOutputDirCmd} pull origin ${tempBranch}`;
241
251
  const fileList = checkGitStatus(undefined, undefined, {
242
252
  onlyCheckStatus: true,
253
+ targetProjectOutputDir,
243
254
  targetProjectOutputDirCmd,
244
255
  startLogText: "Git自动化开始执行..."
245
256
  });
@@ -254,7 +265,7 @@ async function autoBranchProcess(config) {
254
265
  }
255
266
 
256
267
  if (fileList.length > 0) {
257
- console.error(global.logColor.error, `❌ 构建仓库存在未提交文件,请检查`);
268
+ console.error(global.logColor.error, `❌ 构建仓库 ${targetProjectOutputDir} 存在未提交文件,请检查`);
258
269
  process.exit(1);
259
270
  }
260
271
 
@@ -390,7 +401,7 @@ function pullPackagesFromMaster(packagesDir, targetBranch = "master") {
390
401
  stdio: "pipe"
391
402
  });
392
403
 
393
- console.log(global.logColor.success, `✅ ${module}: 成功更新到最新代码`);
404
+ console.log(global.logColor.success, `✅ \x1b[34m${module}\x1b[32m[${targetBranch}]: 更新到最新代码`);
394
405
  results.push({ module, success: true });
395
406
  } catch (error) {
396
407
  console.error(global.logColor.error, `❌ ${module}: 操作失败 - ${error.message}`);
@@ -425,6 +436,104 @@ function findPackagesDir(currentDir) {
425
436
  return null;
426
437
  }
427
438
 
439
+ /**
440
+ * 检查指定目录的 Git 状态
441
+ * @param {string} dirPath - 目录的绝对路径
442
+ * @param {string} dirName - 目录名称(用于日志显示)
443
+ */
444
+ function checkSingleDirGitStatus(dirPath, dirName) {
445
+ const fs = require("fs");
446
+
447
+ if (!fs.existsSync(dirPath)) {
448
+ console.log(global.logColor.warning, `⚠️ ${dirName} 目录不存在: ${dirPath}`);
449
+ return { hasUncommitted: false, changes: [] };
450
+ }
451
+
452
+ const gitPath = path.join(dirPath, ".git");
453
+ if (!fs.existsSync(gitPath)) {
454
+ console.log(global.logColor.warning, `⚠️ ${dirName} 不是 git 仓库,跳过检查`);
455
+ return { hasUncommitted: false, changes: [] };
456
+ }
457
+
458
+ try {
459
+ const statusOutput = execSync("git status --porcelain", {
460
+ cwd: dirPath,
461
+ encoding: "utf8"
462
+ }).trim();
463
+
464
+ if (statusOutput) {
465
+ console.log(global.logColor.error, `❌ ${dirName}: 存在未提交的更改`);
466
+ console.log(global.logColor.error, ` ${statusOutput.split("\n").join("\n ")}`);
467
+ return {
468
+ hasUncommitted: true,
469
+ changes: statusOutput.split("\n"),
470
+ path: dirPath
471
+ };
472
+ } else {
473
+ // console.log(global.logColor.success, `✅ ${dirName}: 工作区干净`);
474
+ return { hasUncommitted: false, changes: [] };
475
+ }
476
+ } catch (error) {
477
+ console.error(global.logColor.error, `❌ ${dirName}: 检查失败 - ${error.message}`);
478
+ return {
479
+ hasUncommitted: true,
480
+ error: error.message,
481
+ path: dirPath
482
+ };
483
+ }
484
+ }
485
+
486
+ /**
487
+ * 切换指定目录到目标分支并拉取最新代码
488
+ * @param {string} dirPath - 目录的绝对路径
489
+ * @param {string} dirName - 目录名称(用于日志显示)
490
+ * @param {string} targetBranch - 目标分支名
491
+ */
492
+ function pullSingleDirFromBranch(dirPath, dirName, targetBranch = "master") {
493
+ const fs = require("fs");
494
+
495
+ if (!fs.existsSync(dirPath)) {
496
+ console.log(global.logColor.warning, `⚠️ ${dirName} 目录不存在: ${dirPath}`);
497
+ return { success: false, reason: "目录不存在" };
498
+ }
499
+
500
+ const gitPath = path.join(dirPath, ".git");
501
+ if (!fs.existsSync(gitPath)) {
502
+ console.log(global.logColor.warning, `⚠️ ${dirName} 不是 git 仓库,跳过操作`);
503
+ return { success: false, reason: "不是 git 仓库" };
504
+ }
505
+
506
+ try {
507
+ // 获取当前分支
508
+ const currentBranch = execSync("git rev-parse --abbrev-ref HEAD", {
509
+ cwd: dirPath,
510
+ encoding: "utf8"
511
+ }).trim();
512
+
513
+ // 如果不在目标分支,则切换
514
+ if (currentBranch !== targetBranch) {
515
+ // console.log(global.logColor.info, ` ${dirName}: 切换到 ${targetBranch} 分支...`);
516
+ execSync(`git checkout ${targetBranch}`, {
517
+ cwd: dirPath,
518
+ stdio: "pipe"
519
+ });
520
+ }
521
+
522
+ // 拉取最新代码
523
+ // console.log(global.logColor.info, ` ${dirName}: 拉取 ${targetBranch} 最新代码...`);
524
+ execSync(`git pull origin ${targetBranch}`, {
525
+ cwd: dirPath,
526
+ stdio: "pipe"
527
+ });
528
+
529
+ console.log(global.logColor.success, `✅ \x1b[34m${dirName}\x1b[32m[${targetBranch}]: 更新到最新代码`);
530
+ return { success: true };
531
+ } catch (error) {
532
+ console.error(global.logColor.error, `❌ ${dirName}: 操作失败 - ${error.message}`);
533
+ return { success: false, reason: error.message };
534
+ }
535
+ }
536
+
428
537
  /**
429
538
  * 完整的 packages 检查和更新流程
430
539
  * @param {string} packagesDir - packages 目录的绝对路径
@@ -465,6 +574,42 @@ async function checkAndUpdatePackages(outPackagesDir, targetBranch = "master") {
465
574
  console.log(global.logColor.warning, `\n⚠️ 有 ${failedUpdates.length} 个模块更新失败,但可以继续执行`);
466
575
  }
467
576
 
577
+ // 4. 检查和更新 postal-benefits-platform(如果当前是 postal-benefits-platform-level)
578
+ const currentProjectName = require(path.resolve(process.cwd(), "package.json")).name;
579
+ if (currentProjectName === "postal-benefits-platform-level") {
580
+ // console.log(global.logColor.info, `\n🚀 开始检查和更新 postal-benefits-platform...`);
581
+
582
+ // 获取 postal-benefits-platform 的路径
583
+ const appsDir = path.resolve(packagesDir, "..", "apps");
584
+ const postalPlatformDir = path.join(appsDir, "postal-benefits-platform");
585
+
586
+ // 获取 postal-benefits-platform-level 当前分支
587
+ const currentLevelBranch = execSync("git rev-parse --abbrev-ref HEAD", {
588
+ cwd: process.cwd(),
589
+ encoding: "utf8"
590
+ }).trim();
591
+
592
+ // 检查 postal-benefits-platform 是否有未提交的更改
593
+ const platformCheckResult = checkSingleDirGitStatus(postalPlatformDir, "postal-benefits-platform");
594
+
595
+ if (platformCheckResult.hasUncommitted) {
596
+ console.log(global.logColor.error, `\n❌ postal-benefits-platform 存在未提交的更改`);
597
+ console.log(global.logColor.error, `\n请先提交或储藏这些更改后再继续执行!`);
598
+ process.exit(1);
599
+ }
600
+
601
+ // 切换到与 postal-benefits-platform-level 相同的分支并拉取最新代码
602
+ const platformUpdateResult = pullSingleDirFromBranch(
603
+ postalPlatformDir,
604
+ "postal-benefits-platform",
605
+ currentLevelBranch
606
+ );
607
+
608
+ if (!platformUpdateResult.success) {
609
+ console.log(global.logColor.warning, `\n⚠️ postal-benefits-platform 更新失败,但可以继续执行`);
610
+ }
611
+ }
612
+
468
613
  // console.log(global.logColor.success, `\n🎉 packages 检查和更新流程完成!`);
469
614
  return updateResults;
470
615
  } catch (error) {
@@ -484,5 +629,7 @@ module.exports = {
484
629
  autoBranchProcess,
485
630
  checkPackagesGitStatus,
486
631
  pullPackagesFromMaster,
487
- checkAndUpdatePackages
632
+ checkAndUpdatePackages,
633
+ checkSingleDirGitStatus,
634
+ pullSingleDirFromBranch
488
635
  };
package/script/index.js CHANGED
@@ -11,15 +11,15 @@ module.exports = {
11
11
  ],
12
12
  buildList: [
13
13
  {
14
- key: "infly:build:prod",
14
+ key: "build:prod",
15
15
  value: "infly-libs beforeBuild && vue-cli-service build && infly-libs afterBuild"
16
16
  },
17
17
  {
18
- key: "infly:build:stage",
18
+ key: "build:stage",
19
19
  value: "infly-libs beforeBuild && vue-cli-service build --mode staging && infly-libs afterBuild"
20
20
  },
21
21
  {
22
- key: "infly:build:test",
22
+ key: "build:test",
23
23
  value: "infly-libs beforeBuild && infly-libs afterBuild"
24
24
  }
25
25
  ]
@@ -7,9 +7,10 @@ function postVersionFileAndMsg(publishText, extraParams = {}) {
7
7
  webhookAtUser = [],
8
8
  webhookExtraText = "",
9
9
  gitAutoPushRepos,
10
- gitAutoPushReposBranchMap
10
+ gitAutoPushReposBranchMap,
11
+ repos
11
12
  } = extraParams || {};
12
- const { branch, commitMsg } = gitInfo || {};
13
+ const { branch, commitMsg, author } = gitInfo || {};
13
14
  const GITPATH = `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`;
14
15
  const UPLOADURL = `https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=08ea37af-c6f5-47dc-8fab-0833707c70b8&type=file`;
15
16
  /* const data = {
@@ -24,8 +25,8 @@ function postVersionFileAndMsg(publishText, extraParams = {}) {
24
25
  });
25
26
  } */
26
27
  let content = publishText;
27
- if (gitAutoPushRepos) {
28
- content = `${publishText}\n构建文件:已推送对应仓库【${gitAutoPushRepos}】分支【${gitAutoPushReposBranchMap[branch]}】`;
28
+ if (gitAutoPushReposBranchMap) {
29
+ content = `${publishText}\n构建文件:已推送对应仓库【${repos}】- 分支【${gitAutoPushReposBranchMap[branch]}】\n构建人:${author}`;
29
30
  } else {
30
31
  content = `${publishText}\n构建文件下载地址:${GITPATH}\n${webhookExtraText}\n`;
31
32
  }
@@ -6,7 +6,7 @@ const CONFIG = {
6
6
  settings: {},
7
7
  login: () => Promise.resolve(),
8
8
  getInfo: () => Promise.resolve(),
9
- resetRouter: () => {}
9
+ redirectRoute: {}
10
10
  };
11
11
 
12
12
  function init(config = {}) {
@@ -76,13 +76,22 @@ const userModule = {
76
76
  SET_CHAT_TOKEN: (state, token) => {
77
77
  state.chatToken = token;
78
78
  TokenService.setChatToken(token);
79
+ },
80
+ SET_PERMISSION_CODES: (state, codes) => {
81
+ state.permission_codes = codes || [];
82
+ Uts.storage.set(CONFIG.settings.permissionsCodeKey, codes);
83
+ },
84
+ UPDATE_ROUTES: (state, menus_permission_codes) => {
85
+ const constantRoutes = CONFIG?.router?.options?.routes || [];
86
+ updateRoutesPermission(constantRoutes, menus_permission_codes);
87
+ CONFIG?.router?.resetRouter?.(constantRoutes);
79
88
  }
80
89
  },
81
90
  actions: {
82
91
  login({ commit }, userInfo) {
83
92
  const { mobile, sms_code } = userInfo;
84
93
  return new Promise((resolve, reject) => {
85
- CONFIG.login({
94
+ CONFIG?.login?.({
86
95
  mobile: mobile,
87
96
  sms_code: sms_code
88
97
  })
@@ -104,8 +113,18 @@ const userModule = {
104
113
  reject("验证失败,请重新登录。");
105
114
  }
106
115
 
107
- const { name, header, map_key, merchantinfo } = response;
116
+ const {
117
+ name,
118
+ header,
119
+ map_key,
120
+ merchantinfo,
121
+ permission_codes = [],
122
+ menus,
123
+ menus_permission_codes = Uts.pluck(menus, "path") || []
124
+ } = response;
108
125
  const { service_token } = merchantinfo || {};
126
+ const fullePermissionCodes = [...permission_codes, ...menus_permission_codes];
127
+
109
128
  commit("SET_USER", response);
110
129
  commit("SET_NAME", name);
111
130
  commit("SET_AVATAR", header);
@@ -115,7 +134,15 @@ const userModule = {
115
134
  commit("SET_CHAT_TOKEN", service_token);
116
135
  }
117
136
 
118
- resolve(response);
137
+ if (
138
+ CONFIG.settings.permissionsCodeKey &&
139
+ JSON.stringify(fullePermissionCodes) !==
140
+ JSON.stringify(Uts.storage.get(CONFIG.settings.permissionsCodeKey))
141
+ ) {
142
+ commit("SET_PERMISSION_CODES", fullePermissionCodes);
143
+ }
144
+ commit("UPDATE_ROUTES", menus_permission_codes);
145
+ resolve({ ...response, PMRedirectPath: CONFIG.redirectRoute.redirect });
119
146
  })
120
147
  .catch((error) => {
121
148
  reject(error);
@@ -123,16 +150,16 @@ const userModule = {
123
150
  });
124
151
  },
125
152
 
126
- logout({ commit, state }) {
153
+ logout({ commit, state }, payload) {
127
154
  return new Promise((resolve, reject) => {
128
155
  TokenService.removeAllTokens();
129
156
  commit("RESET_STATE");
130
157
  commit("SET_MAPKEY", "");
158
+ commit("SET_CHAT_TOKEN", "");
159
+ commit("SET_PERMISSION_CODES", "");
131
160
 
132
- if (CONFIG.router) {
133
- Uts.isFunction(CONFIG.router.push) && CONFIG.router.push("/login");
134
- Uts.isFunction(CONFIG.router.resetRouter) &&
135
- CONFIG.router.resetRouter();
161
+ if (payload?.redirectLogin) {
162
+ CONFIG?.router?.push?.("/login");
136
163
  }
137
164
 
138
165
  if (TokenService.getUrlToken()) {
@@ -160,6 +187,64 @@ const userModule = {
160
187
  }
161
188
  };
162
189
 
190
+ // 递归更新路由权限
191
+ const updateRoutesPermission = (
192
+ routes = [],
193
+ userPermissions = [],
194
+ redirectRoute = {
195
+ level0: "",
196
+ level1: "",
197
+ level2: ""
198
+ },
199
+ lastNoVerPMRoute = {
200
+ level0: "",
201
+ level1: "",
202
+ level2: ""
203
+ },
204
+ level = 0
205
+ ) => {
206
+ const curLevelKey = `level${level}`;
207
+
208
+ routes.forEach((route) => {
209
+ const { path } = route;
210
+ if (route.meta && route.meta.permission && !route.hidden) {
211
+ route.hidden = !Uts.getPM(route.meta.permission);
212
+
213
+ // 记录第一级有权限控制的路由,用于重定向
214
+ if (!route.hidden && !redirectRoute[curLevelKey]) {
215
+ redirectRoute[curLevelKey] = route.path;
216
+ }
217
+ }
218
+
219
+ // 记录最后一级没有权限控制的路由,用于重定向
220
+ if ((!route.meta || !route.meta.permission) && !route.hidden && path) {
221
+ lastNoVerPMRoute[`level${level}`] = path;
222
+ }
223
+
224
+ if (route.children) {
225
+ updateRoutesPermission(route.children, userPermissions, redirectRoute, lastNoVerPMRoute, level + 1);
226
+ }
227
+
228
+ // 处理重定向
229
+ if (path === "") {
230
+ let tempRoute = redirectRoute;
231
+ if (!redirectRoute.level0 && !redirectRoute.level1 && !redirectRoute.level2 && lastNoVerPMRoute.level0) {
232
+ tempRoute = lastNoVerPMRoute;
233
+ }
234
+ route.redirect = `${tempRoute.level1}/${tempRoute.level2}`;
235
+ if (!tempRoute.level2) {
236
+ route.redirect = `${tempRoute.level0}/${tempRoute.level1}`;
237
+ }
238
+
239
+ if (route.redirect === "/") {
240
+ route.redirect = "*";
241
+ }
242
+
243
+ CONFIG.redirectRoute = route || {};
244
+ }
245
+ });
246
+ };
247
+
163
248
  export default {
164
249
  ...userModule,
165
250
  init