123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269 |
- import { Provide, Inject } from '@midwayjs/decorator';
- import { InjectEntityModel } from '@midwayjs/typegoose';
- import { ReturnModelType } from '@typegoose/typegoose';
- import { HttpServiceFactory, HttpService } from '@midwayjs/axios';
- import { Config, InjectClient } from '@midwayjs/core';
- import {
- BaseService,
- FrameworkErrorEnum,
- ServiceError,
- } from 'free-midway-component';
- import { Personal } from '../../entity/user/personal.entity';
- import { Admin } from '../../entity/user/admin.entity';
- import {
- LoginDTO,
- QDTO_personal,
- } from '../../interface/user/personal.interface';
- import _ = require('lodash');
- import { UtilService } from '../../service/util/util';
- const Excel = require('exceljs');
- import * as fs from 'node:fs';
- import * as Path from 'node:path';
- const sep = Path.sep;
- const assert = require('assert');
- type modelType = ReturnModelType<typeof Personal>;
- @Provide()
- export class PersonalService extends BaseService<modelType> {
- @InjectEntityModel(Personal)
- model: modelType;
- @InjectEntityModel(Admin)
- adminModel: ReturnModelType<typeof Admin>;
- @Inject()
- util: UtilService;
- @Config('export.root_path')
- root_path;
- @InjectClient(HttpServiceFactory, 'Axios')
- Axios: HttpService;
- async findUserToLogin(data: LoginDTO): Promise<object> {
- const { account, password } = data;
- const user = await this.model.findOne({ account }, '+password').lean();
- if (!user)
- throw new ServiceError(
- '未找到个人用户信息',
- FrameworkErrorEnum.NOT_FOUND_DATA
- );
- if (_.get(user, 'status') !== '1')
- throw new ServiceError(
- '当前个人用户没有通过审核,拒绝登录',
- FrameworkErrorEnum.SERVICE_FAULT
- );
- if (!_.isEqual(user.password.secret, password))
- throw new ServiceError('密码错误', FrameworkErrorEnum.SERVICE_FAULT);
- return user;
- }
- async dealQueryCondition(condition: QDTO_personal): Promise<QDTO_personal> {
- const { type, code } = this.ctx.user;
- condition = this.util.dealQuery(condition);
- // 查询业务管理
- const busFind = async query =>
- await this.adminModel.find({ ...query, type: '3' }, { code: 1 });
- // 查询机构管理
- const orgFind = async query =>
- await this.adminModel.find({ ...query, type: '2' }, { code: 1 });
- // 查询管理员
- const aFind = async query =>
- await this.adminModel.find({ ...query, type: '1' }, { code: 1 });
- if (type === '1' && code) {
- // 管理员查询
- // =>获取该code下的机构管理员列表 => 用机构管理员id 获取业务管理员列表 => 将code都整理出来作为查询条件
- const a = await aFind({ code });
- if (a.length <= 0)
- throw new ServiceError(
- '未找到该管理员',
- FrameworkErrorEnum.NOT_FOUND_DATA
- );
- const aid = _.get(_.head(a), '_id');
- const orgList = await orgFind({ pid: aid });
- const busList = await busFind({ pid: orgList.map(i => i._id) });
- const codes: any = [
- ...orgList.map(i => i.code),
- ...busList.map(i => i.code),
- code,
- ];
- condition.code = codes;
- } else if (type === '2' && code) {
- // 机构查询
- // =>获取该code下的业务管理员列表 => 将code都整理出来作为查询条件
- const o = await orgFind({ code });
- if (o.length <= 0)
- throw new ServiceError(
- '未找到该机构',
- FrameworkErrorEnum.NOT_FOUND_DATA
- );
- const oid = _.get(_.head(o), '_id');
- const busList = await busFind({ pid: oid });
- const codes: any = [...busList.map(i => i.code), code];
- condition.code = codes;
- } else if (type === '3' && code) {
- // 业务查询
- // code直接查询用户返回即可
- condition.code = code;
- }
- // 没有code,超级管理员,说明不限制
- return condition;
- }
- // 导入
- async import(uri) {
- assert(uri.url, '未获取到文件地址');
- const file = await this.Axios.get(uri.url);
- if (!file) {
- throw new ServiceError(
- '未找到指定文件',
- FrameworkErrorEnum.NOT_FOUND_DATA
- );
- }
- const workbook = new Excel.Workbook();
- await workbook.xlsx.load(file);
- const sheet = workbook.getWorksheet(1);
- // 根据excel,将列序号加入meta中
- const meta: any = _.get(this.model.schema, 'tree');
- const list: any = [];
- const head = _.get(sheet.getRow(1), 'values', []);
- for (let i = 0; i < head.length; i++) {
- const e = head[i];
- if (!e) continue;
- for (const key in meta) {
- if (Object.prototype.hasOwnProperty.call(meta, key)) {
- if (e === meta[key].zh) {
- meta[key].index = i;
- meta[key].key = key;
- list.push(meta[key]);
- }
- }
- }
- }
- const errorList = [];
- const dataList = [];
- sheet.eachRow(async (row, index) => {
- if (index !== 1) {
- const values = row.values;
- const obj = {};
- for (const m of list) {
- const { required, key, zh, index } = m;
- const value = values[index];
- if (required && !value) {
- // 必填且没值的情况
- errorList.push({
- message: `第${index}行数据,缺少必填项 ${zh};`,
- });
- continue;
- }
- obj[key] = value;
- }
- dataList.push(obj);
- }
- });
- for (const data of dataList) {
- try {
- await this.model.create(data);
- } catch (error) {
- errorList.push(error);
- }
- }
- return errorList;
- }
- // 导出
- async export(headList, filter) {
- // 查询位置
- let skip = 0;
- // 一次处理多少条数据
- const limit = 500;
- const total = await this.model.count();
- // 循环次数
- const times = _.ceil(_.divide(total, limit));
- const nowDate = new Date().getTime();
- // 文件 名称 及 路径
- const filename = `个人用户导出-${nowDate}.xlsx`;
- if (!fs.existsSync(this.root_path)) {
- // 如果不存在文件夹,就创建
- this.mkdir(this.root_path);
- }
- const excel_path = `${sep}excel${sep}`;
- const path = `${this.root_path}${excel_path}`;
- if (!fs.existsSync(path)) {
- // 如果不存在文件夹,就创建
- this.mkdir(path);
- }
- const workbook = new Excel.Workbook();
- const sheet = workbook.addWorksheet('sheet');
- const eMeta: any = headList;
- const needList: any = eMeta.map(i => i.key);
- for (let i = 1; i <= times; i++) {
- const data = await this.model
- .find(filter, '+password')
- .skip(skip)
- .limit(limit);
- const list = [];
- for (const val of data) {
- const info: any = {};
- for (const i of needList) {
- if (i === 'password') info[i] = _.get(val[i], 'secret');
- info[i] = val[i];
- }
- if (info.password) info.password = info.password.secret;
- list.push(info);
- }
- sheet.columns = eMeta;
- sheet.addRows(list);
- skip += limit;
- }
- // 生成excel
- const filepath = `${path}${filename}`;
- await workbook.xlsx.writeFile(filepath);
- return `/files/excel/${filename}`;
- }
- // 创建文件夹
- mkdir(dirname) {
- if (fs.existsSync(dirname)) {
- return true;
- }
- if (this.mkdir(Path.dirname(dirname))) {
- fs.mkdirSync(dirname);
- return true;
- }
- }
- exportMeta(exportMeta) {
- const arr = [];
- if (exportMeta && exportMeta.length > 0) {
- for (const val of exportMeta) {
- const info: any = {};
- if (val.model === 'password') {
- info.header = val.label;
- info.key = val.model;
- info.type = '1';
- info.width = 30;
- info.style = {
- alignment: {
- wrapText: true,
- vertical: 'middle',
- horizontal: 'center',
- },
- };
- } else {
- info.header = val.label;
- info.key = val.model;
- info.width = 30;
- info.style = {
- alignment: {
- wrapText: true,
- vertical: 'middle',
- horizontal: 'center',
- },
- };
- }
- arr.push(info);
- }
- } else {
- throw new ServiceError(
- '未找到下载参数',
- FrameworkErrorEnum.NOT_FOUND_DATA
- );
- }
- return arr;
- }
- }
|