From 2b662657c5bc5bc45b69f475c7b2edcf8fc92f0c Mon Sep 17 00:00:00 2001
From: wangzhibo <wangzhibo@shsening.com>
Date: 星期二, 28 七月 2026 10:58:49 +0800
Subject: [PATCH] Merge branch 'master' of http://124.222.109.197:10000/r/jingshen/cool-admin-midway
---
src/modules/basicdata/controller/admin/iot.ts | 5 +
src/modules/monitor/controller/admin/ys7.ts | 19 +++
/dev/null | 56 -----------
src/modules/base/service/sys/param.ts | 24 ++++
src/modules/basicdata/service/iot.ts | 95 +++++++++---------
src/modules/monitor/service/ys7.ts | 76 +++++++++++++++
src/modules/monitor/config.ts | 6 -
src/modules/base/controller/admin/sys/param.ts | 5 +
8 files changed, 178 insertions(+), 108 deletions(-)
diff --git a/src/modules/base/controller/admin/sys/param.ts b/src/modules/base/controller/admin/sys/param.ts
index 304a97b..6c3ac88 100644
--- a/src/modules/base/controller/admin/sys/param.ts
+++ b/src/modules/base/controller/admin/sys/param.ts
@@ -31,4 +31,9 @@
async htmlByKey(@Query('key') key: string) {
this.ctx.body = await this.baseSysParamService.htmlByKey(key);
}
+
+ @Get('/stringbykey', { summary: '鑾峰緱缃戦〉鍐呭鐨勫弬鏁板��' })
+ async stringByKey(@Query('key') key: string) {
+ this.ctx.body = await this.baseSysParamService.getByKey(key);
+ }
}
diff --git a/src/modules/base/service/sys/param.ts b/src/modules/base/service/sys/param.ts
index 0cbc777..cf24d82 100644
--- a/src/modules/base/service/sys/param.ts
+++ b/src/modules/base/service/sys/param.ts
@@ -45,6 +45,30 @@
}
/**
+ * 鏍规嵁key鑾峰緱瀵瑰簲鐨勫弬鏁�
+ * @param key
+ */
+ async getByKey(key) {
+ const result = await this.baseSysParamEntity.findOneBy({ keyName: key });
+ if (result) {
+ if (result.dataType == 0) {
+ try {
+ return JSON.parse(result.data);
+ } catch (error) {
+ return result.data;
+ }
+ }
+ if (result.dataType == 1) {
+ return result.data;
+ }
+ if (result.dataType == 2) {
+ return result.data.split(',');
+ }
+ }
+ return;
+ }
+
+ /**
* 淇℃伅
* @param id
* @param infoIgnoreProperty
diff --git a/src/modules/basicdata/controller/admin/iot.ts b/src/modules/basicdata/controller/admin/iot.ts
index 0f129d3..70bb6f2 100644
--- a/src/modules/basicdata/controller/admin/iot.ts
+++ b/src/modules/basicdata/controller/admin/iot.ts
@@ -43,4 +43,9 @@
return this.ok(devices);
}
+ @Post('/getSitelist', { summary: '鑾峰彇绔欑偣鍒楄〃' })
+ async getSitelist() {
+ const sitelist = await this.basicdataIotService.sitelist();
+ return this.ok(sitelist);
+ }
}
\ No newline at end of file
diff --git a/src/modules/basicdata/service/iot.ts b/src/modules/basicdata/service/iot.ts
index a39f305..a267df3 100644
--- a/src/modules/basicdata/service/iot.ts
+++ b/src/modules/basicdata/service/iot.ts
@@ -5,7 +5,7 @@
import { BaseSysDepartmentEntity } from '../../base/entity/sys/department';
import { BasicdataIotEntity } from '../entity/iot';
import { BaseSysPermsService } from '../../base/service/sys/perms';
-import { BaseSysParamService } from '../../base/service/sys/param';
+import { BaseSysParamEntity } from '../../base/entity/sys/param';
import * as _ from 'lodash';
/**
@@ -19,8 +19,8 @@
@InjectEntityModel(BaseSysDepartmentEntity)
baseSysDepartmentEntity: Repository<BaseSysDepartmentEntity>;
- @Inject()
- baseSysParamService: BaseSysParamService;
+ @InjectEntityModel(BaseSysParamEntity)
+ baseSysParamEntity: Repository<BaseSysParamEntity>;
@Inject()
baseSysPermsService: BaseSysPermsService;
@@ -28,45 +28,52 @@
@Inject()
ctx;
-
/**
- * 鑾峰緱閮ㄩ棬鑿滃崟
+ * 鑾峰緱閮ㄩ棬+绔欑偣鍚堝苟鏍戯紙閬靛惊 Cool 鏁版嵁鏉冮檺瑙勮寖锛�
*/
- async list() {
- const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
- this.ctx.admin.userId
- );
- // 杩囨护閮ㄩ棬鏉冮檺
+ async sitelist() {
+ const { userId, username } = this.ctx.admin;
+
+ // 瓒呯涓嶅彈闄�
+ const isAdmin = username === 'admin';
+ let deptIds: any[] = [];
+
+ if (!isAdmin) {
+ deptIds = await this.baseSysPermsService.departmentIds(userId);
+ // 娌¢厤閮ㄩ棬鏉冮檺鏃剁粰涓繀瀹氫负绌虹殑鍊硷紝闃叉鏌ュ嚭鍏ㄥ簱
+ if (_.isEmpty(deptIds)) deptIds = [null];
+ }
+
const sql = `
- (
- SELECT
- a.id AS a_id,
- a.tenantId AS a_tenantId,
- a.name AS a_name,
- a.parentId AS a_parentId,
- a.orderNum AS a_orderNum
- FROM base_sys_department a
- WHERE 1=1
- ${this.setSql(
- this.ctx.admin.username !== 'admin',
- `and (a.departmentId in (?) `,
- [!_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null]]
- )}
- )
- UNION ALL
- (
- SELECT
- b.businessId AS a_id,
- a.tenantId AS a_tenantId,
- b.businessName AS a_name,
- b.departmentId AS a_parentId,
- a.orderNum AS a_orderNum
- FROM t_basicdata_site b
- LEFT JOIN base_sys_department a ON b.departmentId = a.id
- )
- ORDER BY a_orderNum ASC`;
- const result = await this.nativeQuery(sql);
- return result;
+ (
+ SELECT
+ a.id AS a_id,
+ a.tenantId AS a_tenantId,
+ a.name AS a_name,
+ a.parentId AS a_parentId,
+ a.orderNum AS a_orderNum
+ FROM base_sys_department a
+ ${isAdmin ? 'WHERE 1=1' : 'WHERE a.id IN (?)'}
+ )
+ UNION ALL
+ (
+ SELECT
+ b.businessId AS a_id,
+ a.tenantId AS a_tenantId,
+ b.businessName AS a_name,
+ b.departmentId AS a_parentId,
+ COALESCE(a.orderNum, 999) AS a_orderNum
+ FROM t_basicdata_site b
+ LEFT JOIN base_sys_department a ON b.departmentId = a.id
+ ${!isAdmin ? 'WHERE b.departmentId IN (?)' : ''}
+ )
+ ORDER BY a_orderNum ASC
+ `;
+
+ // nativeQuery 绗簩涓弬鏁板繀椤绘樉寮忎紶鍙傛暟缁�
+ const params = isAdmin ? [] : [deptIds, deptIds];
+
+ return this.nativeQuery(sql, params);
}
/**
@@ -74,7 +81,7 @@
*/
async getYsDevices(businessId: string) {
// 淇鍘熷厛key銆乻ecret鍙栧�奸鍊抌ug + 澧炲姞await
- const ys7_appKey: string = await this.baseSysParamService.dataByKey('ys7.appKey');
+ // const appKey_result = await this.baseSysParamEntity.findOneBy({ keyName: 'ys7.appKey' });
// departmentId 鏄暟瀛楋紝灏濊瘯杞崲锛涜浆鎹㈠け璐ヨ祴鍊� null
const deptId = /^\d+$/.test(businessId) ? Number(businessId) : null;
const qb = this.basicdataIotEntity.createQueryBuilder('a')
@@ -104,13 +111,7 @@
qb.andWhere('a.businessId = :businessId', { businessId });
}
const result = await qb.orderBy('a.iotName', 'ASC').getMany();
- const deviceList = result.map(item => {
- return {
- ...item,
- iotKey: ys7_appKey
- };
- });
- return deviceList;
+ return result;
}
diff --git a/src/modules/monitor/config.ts b/src/modules/monitor/config.ts
index 05331da..285fdf4 100644
--- a/src/modules/monitor/config.ts
+++ b/src/modules/monitor/config.ts
@@ -6,10 +6,6 @@
description: '钀ょ煶浜戣棰戠洃鎺фā鍧�',
enable: true,
middleware: [],
- // globalGuard: [],
- // globalFilter: [],
- // globalPipe: [],
- // 闈欐�佽祫婧愰厤缃紙钀ょ煶涓嶉渶瑕侊紝棰勭暀锛�
- // static: {},
+ globalMiddlewares: [],
} as ModuleConfig;
};
\ No newline at end of file
diff --git a/src/modules/monitor/controller/admin/ys7.ts b/src/modules/monitor/controller/admin/ys7.ts
new file mode 100644
index 0000000..9f3db4e
--- /dev/null
+++ b/src/modules/monitor/controller/admin/ys7.ts
@@ -0,0 +1,19 @@
+import {CoolController, BaseController } from '@cool-midway/core';
+import { Post, Inject } from '@midwayjs/core';
+import { Ys7Service } from '../../service/ys7';
+
+@CoolController()
+export class Ys7Controller extends BaseController {
+ @Inject()
+ ys7Service: Ys7Service;
+
+ /**
+ * 鑾峰彇钀ょ煶浜� AccessToken
+ * 鍓嶇 POST /admin/monitor/ys7/getToken
+ */
+ @Post('/getToken')
+ async getToken() {
+ const tokenInfo = await this.ys7Service.getAccessToken();
+ return this.ok(tokenInfo);
+ }
+}
\ No newline at end of file
diff --git a/src/modules/monitor/controller/ys7.controller.ts b/src/modules/monitor/controller/ys7.controller.ts
deleted file mode 100644
index e6f8b49..0000000
--- a/src/modules/monitor/controller/ys7.controller.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { Controller, Post } from '@midwayjs/core';
-import { Inject } from '@midwayjs/core';
-import { BaseController } from '@cool-midway/core';
-import { Ys7Service } from '../service/ys7.service';
-
-@Controller('/admin/monitor/ys7')
-export class Ys7Controller extends BaseController {
- @Inject()
- ys7Service: Ys7Service;
-
- /**
- * 鑾峰彇钀ょ煶浜� AccessToken
- * GET/POST 鍧囧彲锛屽墠绔� POST 璋�
- */
- @Post('/getToken')
- async getToken() {
- const token = await this.ys7Service.getAccessToken();
- return this.ok(token);
- }
-}
\ No newline at end of file
diff --git a/src/modules/monitor/dto/ys7.dto.ts b/src/modules/monitor/dto/ys7.dto.ts
deleted file mode 100644
index 4006471..0000000
--- a/src/modules/monitor/dto/ys7.dto.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { Rule, RuleType } from '@midwayjs/validate';
-
-export class GetYs7TokenDTO {
- @Rule(RuleType.string().required())
- appKey: string;
-
- @Rule(RuleType.string().required())
- appSecret: string;
-}
\ No newline at end of file
diff --git a/src/modules/monitor/service/ys7.service.ts b/src/modules/monitor/service/ys7.service.ts
deleted file mode 100644
index a5294e3..0000000
--- a/src/modules/monitor/service/ys7.service.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { Provide, Inject } from '@midwayjs/core';
-import { BaseService } from '@cool-midway/core';
-import axios from 'axios';
-import { BaseSysParamService } from '../../base/service/sys/param';
-
-@Provide()
-export class Ys7Service extends BaseService {
- @Inject()
- baseSysParamService: BaseSysParamService;
-
- /**
- * 鑾峰彇钀ょ煶浜� AccessToken
- * 鍐呴儴鑷姩璇荤郴缁熷弬鏁帮紝涓嶈蛋缂撳瓨寤鸿涓婂眰鍖呬竴灞� Redis
- */
- async getAccessToken(): Promise<{
- accessToken: string;
- expireTime: number;
- }> {
- // 浠� Cool-Admin 绯荤粺鍙傛暟琛ㄨ鍙�
- const appKey = await this.baseSysParamService.dataByKey('ys7.appKey');
- const appSecret = await this.baseSysParamService.dataByKey('ys7.appSecret');
-
- if (!appKey || !appSecret) {
- throw new Error('钀ょ煶浜� appKey/appSecret 鏈厤缃紝璇峰湪绯荤粺鍙傛暟涓淮鎶� ys7.appKey / ys7.appSecret');
- }
-
- try {
- const res = await axios.post(
- 'https://open.ys7.com/api/lapp/token/get',
- new URLSearchParams({
- appKey,
- appSecret,
- }),
- {
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- timeout: 8000,
- }
- );
-
- const { code, msg, data } = res.data;
-
- if (String(code) !== '200') {
- throw new Error(`钀ょ煶浜戣幏鍙� Token 澶辫触锛�${msg}锛坈ode: ${code}锛塦);
- }
-
- return {
- accessToken: data.accessToken,
- expireTime: data.expireTime,
- };
- } catch (err) {
- throw err;
- }
- }
-}
\ No newline at end of file
diff --git a/src/modules/monitor/service/ys7.ts b/src/modules/monitor/service/ys7.ts
new file mode 100644
index 0000000..91037e3
--- /dev/null
+++ b/src/modules/monitor/service/ys7.ts
@@ -0,0 +1,76 @@
+import { Provide, Inject } from '@midwayjs/core';
+import { BaseService } from '@cool-midway/core';
+import axios from 'axios';
+import { BaseSysParamEntity } from '../../base/entity/sys/param';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { Repository } from 'typeorm';
+
+interface Ys7TokenData {
+ accessToken: string;
+ /** 钀ょ煶杩斿洖鐨勬绉掔骇杩囨湡鏃堕棿鎴� */
+ expireTime: number;
+}
+
+@Provide()
+export class Ys7Service extends BaseService {
+ @InjectEntityModel(BaseSysParamEntity)
+ baseSysParamEntity: Repository<BaseSysParamEntity>;
+
+ /** 鍐呭瓨骞跺彂閿� */
+ private refreshing: Promise<Ys7TokenData> | null = null;
+
+ /**
+ * 瀵瑰鏆撮湶锛氭嬁 token锛堣嚜鍔ㄨ缂撳瓨 / 缁锛�
+ */
+ async getAccessToken() {
+ const token = await this.baseSysParamEntity.findOneBy({ keyName: 'ys7.accessToken' });
+ if (
+ !token ||
+ !token.updateTime ||
+ Date.now() - new Date(token.updateTime).getTime() > 6 * 24 * 60 * 60 * 1000
+ ) {
+ await this.fetchAndSaveRemote();
+ }
+ }
+
+ /** 鐪熸璋冭悿鐭� */
+ private async fetchAndSaveRemote(): Promise<Ys7TokenData> {
+ const appKey_result = await this.baseSysParamEntity.findOneBy({ keyName: 'ys7.appKey' });
+ const appSecret_result = await this.baseSysParamEntity.findOneBy({ keyName: 'ys7.appSecret' });
+
+ if (!appKey_result || !appSecret_result) {
+ throw new Error(
+ '钀ょ煶浜� appKey/appSecret 鏈厤缃紝璇峰湪銆愮郴缁熷弬鏁般�戜腑缁存姢 ys7.appKey / ys7.appSecret'
+ );
+ }
+
+ const { data: res } = await axios.post(
+ 'https://open.ys7.com/api/lapp/token/get',
+ new URLSearchParams({ appKey: appKey_result.data, appSecret: appSecret_result.data }),
+ {
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ timeout: 8000,
+ }
+ );
+
+ if (String(res.code) !== '200') {
+ throw new Error(`钀ょ煶浜戣幏鍙� Token 澶辫触锛�${res.msg}锛坈ode: ${res.code}锛塦);
+ }
+
+ const tokenData: Ys7TokenData = {
+ accessToken: res.data.accessToken,
+ expireTime: res.data.expireTime,
+ };
+
+ // 鍐欏洖绯荤粺鍙傛暟琛紙Cool-Admin 鑷甫 upsert锛�
+ const token = await this.baseSysParamEntity.findOneBy({ keyName: 'ys7.accessToken' });
+ this.baseSysParamEntity.save({
+ ...token,
+ data: tokenData.accessToken,
+ updateTime: new Date(),
+ }).catch(() => {
+ // 蹇界暐鍐欏洖澶辫触
+ });
+ return tokenData;
+ }
+}
\ No newline at end of file
--
Gitblit v1.9.1