项目初始化

This commit is contained in:
Taric Xin
2021-11-26 16:34:35 +08:00
parent 66644bcf0a
commit 5287578452
354 changed files with 45736 additions and 0 deletions

View File

@ -0,0 +1,112 @@
/*
* @Author: Maple
* @Date: 2021-03-22 11:42:26
* @LastEditors: Do not edit
* @LastEditTime: 2021-05-27 11:22:02
* @Description: 全局账号服务
*/
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { CoreService, StartupService } from '@core';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { BaseService } from '../core/base.service';
@Injectable({
providedIn: 'root',
})
export class EAAccountService extends BaseService {
// 验证码登录
public $api_login_by_captcha = `/scm/cuc/cuc/user/sms/login?_allow_anonymous=true`;
// 账号密码登录
public $api_login_by_account = `/scm/cuc/cuc/user/login?_allow_anonymous=true`;
// 退出登录
public $api_logout = `/chia/user/logout`;
constructor(public injector: Injector) {
super(injector);
}
// 注入核心服务
private get coreSrv(): CoreService {
return this.injector.get(CoreService);
}
// 注入路由
private get router(): Router {
return this.injector.get(Router);
}
// 注入路由复用服务
private get reuseTabService(): ReuseTabService {
return this.injector.get(ReuseTabService);
}
// 注入全局启动服务
private get startSrv(): StartupService {
return this.injector.get(StartupService);
}
// 登录状态
public get loginStatus(): boolean {
return this.coreSrv.loginStatus;
}
/**
* 账号密码登录
* @param username 登录账号
* @param password 登录密码
*/
loginByAccount(username: string, password: string): void {
this.asyncRequest(this.$api_login_by_account, { username, password, type: 0 }, 'POST', true, 'FORM').then((res) => {
console.log(res);
this.doAfterLogin(res);
});
}
/**
* 短信验证码登录
* @param phone 手机号码
* @param smsCode 短信验证码
*/
loginByCaptcha(phone: string, smsCode: string): void {
this.asyncRequest(this.$api_login_by_captcha, { phone, smsCode }, 'POST', true, 'FORM').then((res) => {
this.doAfterLogin(res);
});
}
private doAfterLogin(res: any): void {
const token = res?.token;
if (token) {
// 清空路由复用信息
this.reuseTabService.clear();
// 设置用户Token信息
// TODO: Mock expired value
// res.user.expired = +new Date() + 1000 * 60 * 5;
this.coreSrv.tokenSrv.set({ token });
// 重新获取 StartupService 内容,我们始终认为应用信息一般都会受当前用户授权范围而影响
this.startSrv.load().then(() => {
let url = this.coreSrv.tokenSrv.referrer!.url || '/';
if (url.includes('/passport')) {
url = '/';
}
this.router.navigateByUrl(url);
});
}
}
/**
* 登出系统
* @param showMsg 是否显示登录过期弹窗
*/
logout(showMsg: boolean): void {
this.coreSrv.logout(showMsg);
}
/**
* 向服务器请求登出
*/
requestLogout(): void {
this.asyncRequest(this.$api_logout).finally(() => {
this.logout(false);
});
}
}

View File

@ -0,0 +1,88 @@
/*
* @Author: Maple
* @Date: 2021-03-22 11:42:26
* @LastEditors: Do not edit
* @LastEditTime: 2021-06-17 14:58:35
* @Description: 全局权限服务
*/
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { cacheConf } from '@conf/cache.conf';
import { StartupService } from '@core';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { SettingsService } from '@delon/theme';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { BaseService } from '../core/base.service';
import { EACacheService } from '../core/cache.service';
@Injectable({
providedIn: 'root',
})
export class EAAuthorizationService extends BaseService {
// 获取我的角色
public $api_get_my_roles = `/chia/roleInfo/getMyRoleList`;
constructor(public injector: Injector) {
super(injector);
}
// 注入路由
private get router(): Router {
return this.injector.get(Router);
}
// 注入缓存服务
private get cacheSrv(): EACacheService {
return this.injector.get(EACacheService);
}
// 注入令牌服务
private get tokenSrv(): ITokenService {
return this.injector.get(DA_SERVICE_TOKEN);
}
// 注入路由复用服务
private get reuseTabService(): ReuseTabService {
return this.injector.get(ReuseTabService);
}
// 注入全局启动服务
private get startSrv(): StartupService {
return this.injector.get(StartupService);
}
// 注入全局设置服务
private get settingSrv(): SettingsService {
return this.injector.get(SettingsService);
}
/**
* 获取角色列表
* @param force 强制刷新 默认值false
* @returns 角色列表, 类型 Array<any> | Observable<Array<any>>
*/
getMyRoles(force: boolean = false): Observable<Array<any>> {
// 强制刷新
if (force) {
return this.refreshRoles();
}
// 从缓存中提取角色
const roles = this.cacheSrv.get(cacheConf.role) || [];
// 当缓存中不存在角色时,尝试从服务器拉取角色数据
if (roles.length > 0) {
return of(roles);
}
return this.refreshRoles();
}
/**
* 刷新角色权限
*/
private refreshRoles(): Observable<Array<any>> {
return this.request(this.$api_get_my_roles).pipe(
tap((res) => {
this.cacheSrv.set(cacheConf.role, res);
}),
);
}
}

View File

@ -0,0 +1,76 @@
/*
* @Author: Maple
* @Date: 2021-03-22 11:42:26
* @LastEditors: Do not edit
* @LastEditTime: 2021-03-29 14:45:43
* @Description: 全局验证码服务
*/
import { ComponentRef, Injectable, Injector } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { BaseService } from '../core/base.service';
@Injectable({
providedIn: 'root',
})
export class EACaptchaService extends BaseService {
// 通过手机号发送短信验证码
private $api_send_sms_by_mobile = `/scm/sms/sms/verification/getSMVerificationCode?_allow_anonymous=true&_allow_badcode=true`;
// 验证手机号为平台用户后发送短信验证码
private $api_send_sms__by_validate_mobile = `/chiauserBasicInfo/forgetPassword/getAccountSMVerificationCode`;
// 滑块验证码获取短信
$api_dun_sms = `/scce/pbc/pbc/verification/verificationSlider?_allow_anonymous=true&_allow_badcode=true`;
// 根据当前登录用户绑定的手机号码获取短信验证码
$api_captcha_sms_code = `/scce/pbc/pbc/verification/getSMVerificationCodeByToken`;
// 获取应用租户的管理员用户发送验证码
$api_getAppLesseeAdminSMVerificationCode = `/chiauserBasicInfo/getAppLesseeAdminSMVerificationCode`;
/**
* 根据当前登录用户绑定的手机号码获取短信验证码
*/
getCaptchaBySMSNoPhone(): Observable<any> {
return this.request(this.$api_captcha_sms_code, { appId: this.envSrv.getEnvironment().appId }, 'POST', true, 'FORM');
}
/**
* 获取应用租户的管理员用户发送验证码
*/
getAppLesseeAdminSMVerificationCode(): Observable<any> {
return this.request(this.$api_getAppLesseeAdminSMVerificationCode, { appId: this.envSrv.getEnvironment().appId }, 'POST', true, 'FORM');
}
constructor(public injector: Injector) {
super(injector);
}
/**
* 发送短信验证码
* @param mobile 手机号码
*/
sendSMSCaptchaByMobile(mobile: string): Observable<any> {
return this.request(
this.$api_send_sms_by_mobile,
{ appId: this.envSrv.getEnvironment()?.appId, phoneNumber: mobile },
'POST',
true,
'FORM',
);
}
/**
* 滑块验证获取短信码
* @param tel 手机号
* @param validate 滑动验证通过字符串
* @param url api地址
*/
getCaptchaByDun(mobile: string, validate: string, url?: string): Observable<any> {
return this.request(
url || this.$api_dun_sms,
{ appId: this.envSrv.getEnvironment()?.appId, phoneNumber: mobile, user: mobile, validate },
'POST',
true,
'FORM',
);
}
}

View File

@ -0,0 +1,125 @@
import { Injectable, Injector } from '@angular/core';
import { cacheConf } from '@conf/cache.conf';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { BaseService } from '../core/base.service';
import { EACacheService } from '../core/cache.service';
@Injectable({
providedIn: 'root',
})
export class EAEnterpriseService extends BaseService {
// 获取当前用户绑定的分销商/代理商/供应商
public $api_get_my_enterprises = `/chia/enterpriseInfo/list/queryMyAppInfo`;
// 向服务器变更默认企业
public $api_selectEnterprise = '/chia/userApp/selectEnterprise';
constructor(public injector: Injector) {
super(injector);
}
// 注入缓存服务
private get cacheSrv(): EACacheService {
return this.injector.get(EACacheService);
}
/**
* 加载企业信息
*/
loadEnterpises(): Observable<any> {
return this.request(this.$api_get_my_enterprises);
}
/**
* 根据租户ID获取指定的企业
* @param tenantId 租户ID
*/
getOne(tenantId: string): any {
const enterprises = this.getAll();
return enterprises.find((r) => r.tenantId === tenantId);
}
/**
* 获取所有企业
*/
getAll(): Array<any> {
return this.cacheSrv.get(cacheConf.enterprise) || [];
}
/**
* 获取默认企业
*/
getDefault(): any {
const list = this.getAll();
return list.find((r) => r.defaultState) || list[0] || null;
}
/**
* 设置默认企业
*/
setDefault(tenantId: string): void {
// 获取指定tenantId的企业
const enterprise = this.getOne(tenantId);
if (enterprise) {
let enterpriseList = this.getAll();
// 设置指定tenantId的企业为默认企业其他的企业为非默认企业
enterpriseList = enterpriseList.map((m) => {
if (m.tenantId === enterprise.tenantId) {
m.defaultState = true;
} else {
m.defaultState = false;
}
return m;
});
// 重新缓存新的企业列表
this.setCache(enterpriseList);
// 广播当前环境信息
this.envSrv.setEnvironment(enterprise.appId, enterprise.tenantId);
}
}
/**
* 设置缓存企业信息
* @param enterpriseData 企业信息信息
*/
setCache(enterpriseData: any): void {
this.cacheSrv.set(cacheConf.enterprise, enterpriseData);
}
/**
* 选择企业
* @param item 企业实体
* 选择企业进入管理后台
* 1. 判断当前企业是否被冻结如企业为冻结状态则toast提示“供应商已被冻结无法访问请联系客服处理”
* 2. 向服务器请求变更当前企业身份
* 3. 服务器变更当前企业后,刷新本地缓存中的企业信息
* 4. 跳转到管理后台首页
*/
changeDefaultEnterprise(item: any): Observable<any> {
// 1. 判断冻结状态
// if (item.stateLocked) {
// this.msgSrv.warning('代理商已被冻结,无法访问,请联系客服处理');
// return of(false);
// }
// 2.判断用户状态userStatus0-正常1-冻结2-废弃
// if (item.userStatus === 1) {
// this.msgSrv.warning('您的帐号已被企业冻结,无法访问,请联系客服处理');
// return of(false);
// }
// if (item.userStatus === 2) {
// this.msgSrv.warning('您的帐号已被企业废弃,无法访问,请联系客服处理');
// return of(false);
// }
// 3. 向服务器请求变更当前企业身份
return this.request(this.$api_selectEnterprise, { tenantId: item.tenantId }).pipe(
tap((data) => {
if (data) {
// 切换成功则广播当前环境信息
this.envSrv.setEnvironment(item.appId, item.tenantId);
}
}),
);
}
}

View File

@ -0,0 +1,306 @@
/*
* @Author: Maple
* @Date: 2021-03-22 11:42:26
* @LastEditors: Do not edit
* @LastEditTime: 2021-05-27 11:07:18
* @Description: 全局系统服务
*/
import { Injectable, Injector } from '@angular/core';
import { Observable, zip } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { CoreService } from 'src/app/core/core.service';
import { EAEncryptUtil } from '../../utils';
import { BaseService } from '../core/base.service';
@Injectable({
providedIn: 'root',
})
export class EAPlatformService extends BaseService {
public $api_update_platform_name = `/chia/operationInfo/updatePlatformName`; // 修改当前登录平台名称
/**
* 判断是否已经设置平台名称
*/
private $api_is_set_platform_name = `/chia/operationInfo/judgeSetPlatformName`;
/**
* 获取当前登录用户绑定的运营商有效期
*/
private $api_get_validity_period_of_operator = `/chia/operationInfo/getOperationDetailByToken`;
/**
* 缓存平台状态键名
*/
private _cachePlatformStatusKey = '_cpsk';
/**
* 运营商剩余有效期
*/
private _validityPeriodOfOperator: Observable<number> | null = null;
/**
* 允许运营商超出有效期时登录
*/
private _allowLoginBeyondValidity = true;
/**
* 获取基础配置
*/
// public $api_get_config = `/scce/pbc/pbc/baseConfig/getBaseConfigList?_allow_anonymous=true`;
constructor(public injector: Injector) {
super(injector);
}
// 注入核心服务
private get coreSrv(): CoreService {
return this.injector.get(CoreService);
}
/**
* 获取平台状态(参考Http状态码)
* 200平台状态正常
* 401: 未设置平台名称
* 403
*/
getPlatformStatus(): number {
const encryptStatus = this.coreSrv.cacheSrv.getNone<string>(this._cachePlatformStatusKey);
try {
const status = EAEncryptUtil.deencryptByDeAES(encryptStatus);
return +status;
} catch (error) {
return 0;
}
}
/**
* 获取当前运营商剩余有效期
* @returns 有效期天数
*/
getValidityPeriodOfOperator(): Observable<number> {
return this.loadValidityPeriodOfOperator();
}
/**
* 加载平台状态
*
* @returns 平台状态码
*/
loadPlatformStatus(): Promise<void> {
return new Promise((resolve) => {
zip(this.loadIsSetPlatformName(), this.loadValidityPeriodOfOperator())
.pipe(
catchError((res) => {
console.error(`加载平台状态时发生错误:`, res);
this.msgSrv.error(`加载平台状态时发生错误!`);
resolve();
return [];
}),
)
.subscribe(
([nameStauts, validityPeriod]) => this.setPlatformStatus(nameStauts, validityPeriod),
() => {},
() => resolve(),
);
});
}
/**
* 获取平台名称设置状态
* @param nameStatus 平台名称设置状态
* @param validityPeriod 运营剩余有效期天数
*/
setPlatformStatus(nameStatus: boolean, validityPeriod: number) {
let status = 0;
// 判断平台名称
if (status !== 200) {
status = nameStatus ? 200 : 401;
}
// 判断运营商有效期
if (!this._allowLoginBeyondValidity && status === 200) {
status = validityPeriod > 0 ? 200 : 402;
}
// 加密并保存平台状态
const ciphertext = EAEncryptUtil.encryptByEnAES(status.toString());
this.coreSrv.cacheSrv.set(this._cachePlatformStatusKey, ciphertext);
}
/**
* 获取平台是否设置平台名称
* @returns true | false
*/
private loadIsSetPlatformName(): Observable<boolean> {
return this.request(this.$api_is_set_platform_name).pipe(switchMap(async (sm) => sm === true));
}
/**
* 获取当前账户绑定的运营商有效期
* @returns 有效期时间(天)
*/
private loadValidityPeriodOfOperator(): Observable<number> {
return this.request(this.$api_get_validity_period_of_operator);
}
/**
* 获取指定平台的地址
* @param platformName 平台名称
* @param hasOperationCode 是否需要运营商代码
*/
getPlatfomrUrl(platformName: string, hasOperationCode = true) {
const url: string = this.getAllPlatformUrls().find((r: any) => r.name === platformName)?.url || '';
if (hasOperationCode) {
return url;
}
return url.includes('?') ? url.substring(0, url.indexOf('?')) : url;
}
/**
* 获取所有平台的地址
*/
getAllPlatformUrls() {
let platforms: any = [];
const sc = this.coreSrv.tokenSrv.get()?.sc;
const protocol = window.location.protocol;
const hostname = window.location.hostname;
const port = window.location.port;
switch (hostname) {
case 'localhost':
platforms = [
{
name: '运营后台',
url: `${protocol}//${hostname}:8001/#/?v=${sc}`,
},
{
name: '开放平台',
url: `${protocol}//localhost:8005/#/?v=${sc}`,
},
{
name: '供应商平台',
url: `${protocol}//localhost:8004/#/?v=${sc}`,
},
{
name: '分销商平台',
url: `${protocol}//localhost:8003/#/?v=${sc}`,
},
{
name: '代理商平台',
url: `${protocol}//localhost:8002/#/?v=${sc}`,
},
];
break;
case 'sce-ows-test.380star.com':
platforms = [
{
name: '运营后台',
url: `${protocol}//${hostname}${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '开放平台',
url: `${protocol}//sce-opc-test.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '供应商平台',
url: `${protocol}//sce-cvc-test.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '分销商平台',
url: `${protocol}//sce-cdc-test.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '代理商平台',
url: `${protocol}//sce-cac-test.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
];
break;
case 'sce-ows-pre.380star.com':
platforms = [
{
name: '运营后台',
url: `${protocol}//${hostname}${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '开放平台',
url: `${protocol}//sce-opc-pre.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '供应商平台',
url: `${protocol}//sce-cvc-pre.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '分销商平台',
url: `${protocol}//sce-cdc-pre.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '代理商平台',
url: `${protocol}//sce-cac-pre.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
];
break;
case 'sce-ows-demo.380star.com':
platforms = [
{
name: '运营后台',
url: `${protocol}//${hostname}${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '开放平台',
url: `${protocol}//sce-opc-demo.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '供应商平台',
url: `${protocol}//sce-cvc-demo.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '分销商平台',
url: `${protocol}//sce-cdc-demo.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '代理商平台',
url: `${protocol}//sce-cac-demo.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
];
break;
case 'sce-ows.380star.com':
platforms = [
{
name: '运营后台',
url: `${protocol}//${hostname}${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '开放平台',
url: `${protocol}//sce-opc.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '供应商平台',
url: `${protocol}//sce-cvc.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '分销商平台',
url: `${protocol}//sce-cdc.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
{
name: '代理商平台',
url: `${protocol}//sce-cac.380star.com${port ? ':' + port : ''}/#/?v=${sc}`,
},
];
break;
}
return platforms;
}
/**
* 获取运营商代码
* @returns 运营商代码
*/
getOperatorCode() {
return this.coreSrv.tokenSrv.get()?.sc || this.coreSrv.settingSrv.getData('app')?.v || '';
}
/**
* 获取平台配置信息列表
*/
// getPlatformConfigurationList(): Observable<Array<any>> {
// return this.request(this.$api_get_config, {
// pageIndex: 1,
// pageSize: 999,
// });
// }
}

View File

@ -0,0 +1,204 @@
/*
* @Description:
* @Author: wsm
* @Date: 2021-06-22 10:25:33
* @LastEditTime: 2021-06-23 20:25:05
* @LastEditors: Do not edit
* @Reference:
*/
import { Inject, Injectable, Injector } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { cacheConf } from '@conf/cache.conf';
import { eventConf } from '@conf/event.conf';
import { sysConf } from '@conf/sys.conf';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { SettingsService } from '@delon/theme';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { BaseService } from '../core/base.service';
import { EACacheService } from '../core/cache.service';
import { EAEventService } from '../core/event.service';
@Injectable({
providedIn: 'root',
})
export class EAUserService extends BaseService {
/**
* 账号密码登录
*/
$api_login_by_account = `/scce/cuc/cuc/user/login?_allow_anonymous=true`;
/**
* 手机号登录
*/
$api_login_by_mobile = `/scce/cuc/cuc/user/sms/login?_allow_anonymous=true`;
// 登录路径
private $api_login = `/scce/cuc/cuc/user/login?_allow_anonymous=true`;
private $api_captcha_login = `/scce/cuc/cuc/user/sms/login?_allow_anonymous=true`;
private $api_register: any = ``;
// 获取协议信息
public $api_get_agreement_info = `/scce/pbc/pbc/agreementInfo/getAgreementInfoByType?_allow_anonymous=true`;
// 未登录验证身份
public $forgetPasswordVerifyIdentity = `/scm/cuc/cuc/userBasicInfo/forgetPassword/verifyIdentity?_allow_anonymous=true`;
// 未登录账号发送验证码
public $getAccountSMVerificationCode = `/scm/cuc/cuc/userBasicInfo/forgetPassword/getAccountSMVerificationCode?_allow_anonymous=true`;
// 未设置密码的用户设置用户密码
public $api_set_password = `/scce/cuc/cuc/userBasicInfo/setPassword`;
// 凭证修改密码
public $voucherUpdatePassword = `/scm/cuc/cuc/userBasicInfo/forgetPassword/voucherUpdatePassword?_allow_anonymous=true`;
// 检测用户名是否存在
public $api_validate_username_exists = `/tms/cuc/cuc/userBasicInfo/checkUserName?_allow_badcode=true`;
// 获取当前用户信息
public $api_get_current_user = `/scce/cuc/cuc/user/getUserDetail`;
// 校验手机号是否可注册
private $api_vaild_register: any = ``;
/**
* 登出
*/
$api_logout = `/scce/cuc/cuc/user/logout`;
/**
* 根据Token获取用户详情
*/
$api_get_user_by_token = `/scce/cuc/cuc/user/getUserDetail`;
/**
* 获取用户菜单
*/
$api_get_user_menus = `/scce/cuc/cuc/functionInfo/queryUserHaveFunctionsList`;
/**
* 获取用户角色
*/
$api_get_user_roles = `/scce/cuc/cuc/roleInfo/getMyRoleList`;
// 获取一、二、三级地区详情
public $api_getRegionToThree = `/scce/pbc/pbc/region/getRegionToThree?_allow_anonymous=true`;
constructor(
public injector: Injector,
public cacheSrv: EACacheService,
public eventSrv: EAEventService,
public router: Router,
public ar: ActivatedRoute,
@Inject(DA_SERVICE_TOKEN) public tokenSrv: ITokenService,
private settingSrv: SettingsService,
) {
super(injector);
}
/**
* 登录状态
*/
public get loginStatus(): boolean {
try {
return !!this.tokenSrv.get()?.token;
} catch (error) {
return false;
}
}
/**
* @description 手机号登录
* @param mobile 手机号
* @param captcha 验证码
*/
loginByMobile(mobile: string, captcha: string, sc: string) {
this.asyncRequest(this.$api_login_by_mobile, { phone: mobile, smsCode: captcha, sc }, 'POST', true, 'FORM').then((res) => {
if (res?.token) {
this.cacheSrv.set(cacheConf.token, res.token);
this.doAfterLogin();
this.eventSrv.event.emit(eventConf.reflesh_login_status);
this.router.navigate([this.ar.snapshot.queryParams.returnUrl || '/']);
}
});
}
/**
* @description 账号密码登录
* @param account 账号
* @param password 密码
*/
loginByAccount(account: string, password: string, sc: string) {
this.request(this.$api_login_by_account, { username: account, password, sc }, 'POST', true, 'FORM').subscribe((res: any) => {
if (res?.token) {
this.tokenSrv.set({ token: res.token });
this.doAfterLogin();
this.eventSrv.event.emit(eventConf.reflesh_login_status, this.ar.snapshot.queryParams.returnUrl || '/');
}
});
}
async doAfterLogin() {
await this.loadUserInfo();
await this.loadUserMenus();
await this.loadUserRoles();
}
/**
* 加载用户信息
*/
async loadUserInfo() {
return this.asyncRequest(this.$api_get_user_by_token).then((res) => {
this.cacheSrv.set(cacheConf.user, res);
});
}
/**
* 加载用户菜单
*/
async loadUserMenus() {
return this.asyncRequest(this.$api_get_user_menus, { appId: sysConf.appId }).then((res) => {
this.cacheSrv.set(cacheConf.menu, res);
});
}
/**
* 加载用户角色
*/
loadUserRoles() {}
/**
* 登出
*/
logout() {
this.settingSrv.setApp({});
this.tokenSrv.clear();
this.cacheSrv.clear();
this.router.navigate(['/']);
}
/**
* 用户注册
*/
register(params: any): Observable<boolean> {
const obj: any = {};
obj.appId = sysConf.appId;
obj.masterAccount = 0;
if (params.regType === 'account') {
obj.account = params.account;
obj.loginCipher = params.loginCipher;
obj.type = 0;
} else if (params.regType === 'phone') {
obj.phone = params.phone;
obj.smsVerificationCode = params.smsVerificationCode;
obj.type = 1;
}
return this.http.post(this.$api_register, obj).pipe(
map((res: any): any => {
if (res.success === true) {
return true;
}
}),
);
}
/**
* 校验手机号是否可注册
*/
checkPhoneHasRegister(params: any): Observable<boolean> {
const formdata = new FormData();
formdata.append('appId', sysConf.appId);
formdata.append('phoneNumber', params);
return this.http.post(this.$api_vaild_register, formdata).pipe(
map((res: any): any => {
if (res.success === true) {
return true;
}
}),
);
}
}

View File

@ -0,0 +1,516 @@
/*
* @Author: Maple
* @Date: 2021-03-20 16:38:44
* @LastEditors: Do not edit
* @LastEditTime: 2021-06-17 15:06:37
* @Description: 全局基础服务:
* 所有实体类服务必须使用extends扩展此类
* 几个特别的Get参数
* 1. _allow_anonymous=true: 匿名访问可绕开Http拦截器验证拦截
* 使用方法: $api_xxx = `xxx?_allow_anonymous=true`
*
* 2. _allow_badcode=true: 请求坏状态可使Http拦截放还完整的HttpResponse
* 使用方法: $api_xxx = `xxxx?_allow_badcode=true`
*
* 3. _custom_header="[{key: string, value: string}]": 自定义Header,
* 一些特殊的请求需要额外附加特别的Header时使用
* 使用方法:
* const headers = [{ key: xxx, value: xxx},
* { key: xxx, value: xxxx}];
* this.service.request(
* this.encodeUrlHeader(
* this.service.$api_xxx, headers))
*
*/
import { Injectable, Injector } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { EnvironmentService } from '@env/environment.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { IBase } from '../../interfaces';
import { EAFileUtil } from '../../utils';
@Injectable({
providedIn: 'root',
})
export class BaseService implements IBase {
// 新增实例接口地址
public $api_add_one!: string;
// 新增多个实例地址
public $api_add_many!: string;
// 修改实例接口地址
public $api_edit_one!: string;
// 修改多个实例地址
public $api_edit_many!: string;
// 删除单个实例接口地址
public $api_del_one!: string;
// 删除多个实例接口地址
public $api_del_many!: string;
// 获取多个实例接口地址
public $api_get_many!: string;
// 获取单个实例接口地址
public $api_get_one!: string;
// 获取分页数据
public $api_get_page!: string;
// 导出数据接口地址
public $api_export!: string;
// 导入数据接口地址
public $api_import!: string;
// 导入数据模板下载地址
public $api_import_download_tpl!: string;
// 获取字典选项
public $api_get_dict!: string;
constructor(public injector: Injector) {}
get http(): _HttpClient {
return this.injector.get(_HttpClient);
}
get msgSrv(): NzMessageService {
return this.injector.get(NzMessageService);
}
get fileUtil(): EAFileUtil {
return this.injector.get(EAFileUtil);
}
get envSrv(): EnvironmentService {
return this.injector.get(EnvironmentService);
}
/**
* 异步请求
* @param parameter 请求参数
* @param url 请求路径
* @param method 请求方法
*/
private httpRequest(
url: string,
parameter: any = {},
method: 'POST' | 'GET',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
if (paramType === 'FORM') {
parameter = this.getFormData(parameter);
}
// 判断请求是否需要返回完整请求体
const allowBadCode = this.getParams('_allow_badcode', url);
return this.http
.request(method, url, {
body: paramInBody ? parameter : null,
params: paramInBody ? null : parameter,
})
.pipe(
map((res: any) => {
if (res.success === true) {
const data = res?.data;
if (allowBadCode) {
return res;
} else {
if (data === undefined || data === null) {
return true;
}
return data;
}
} else {
this.msgSrv.warning(res.msg);
return allowBadCode ? res : null;
}
}),
);
}
/**
* 把实体对象转换为FormData
*/
private getFormData(entity: any) {
const formdata = new FormData();
for (const key in entity) {
if (Object.prototype.hasOwnProperty.call(entity, key)) {
formdata.append(key, entity[key]);
}
}
return formdata;
}
request(
url: string,
parameter: any = {},
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
return this.httpRequest(url, parameter, method, paramInBody, paramType);
}
asyncRequest(
url: string,
parameter: any = {},
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any> {
return this.request(url, parameter, method, paramInBody, paramType).toPromise();
}
// 增
addOne(
parameter: any,
url: string = this.$api_add_one,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
return this.request(url, parameter, method, paramInBody, paramType);
}
asyncAddOne(
parameter: any,
url: string = this.$api_add_one,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any> {
return this.addOne(parameter, url, method, paramInBody, paramType).toPromise();
}
addMany(
parameter: any[],
url: string = this.$api_add_many,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
return this.request(url, parameter, method, paramInBody, paramType);
}
asyncAddMany(
parameter: any,
url: string = this.$api_add_many,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any> {
return this.addMany(parameter, url, method, paramInBody, paramType).toPromise();
}
// 删
delOne(
parameter: any,
url: string = this.$api_del_one,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
return this.request(url, parameter, method, paramInBody, paramType);
}
asyncDelOne(
parameter: any,
url: string = this.$api_del_one,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any> {
return this.delOne(parameter, url, method, paramInBody, paramType).toPromise();
}
delMany(
parameter: any[],
url: string = this.$api_del_many,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
return this.request(url, parameter, method, paramInBody, paramType);
}
asyncDelMany(
parameter: any[],
url: string = this.$api_del_many,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any> {
return this.delMany(parameter, url, method, paramInBody, paramType).toPromise();
}
// 改
updateOne(
parameter: any,
url: string = this.$api_edit_one,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
return this.request(url, parameter, method, paramInBody, paramType);
}
asyncUpdateOne(
parameter: any,
url: string = this.$api_edit_one,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any> {
return this.updateOne(parameter, url, method, paramInBody, paramType).toPromise();
}
updateMany(
parameter: any[],
url: string = this.$api_edit_many,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
return this.request(url, parameter, method, paramInBody, paramType);
}
asyncUpdateMany(
parameter: any[],
url: string = this.$api_edit_many,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any> {
return this.updateMany(parameter, url, method, paramInBody, paramType).toPromise();
}
/**
* 查询一个实例
*/
getOne(
parameter: any,
url: string = this.$api_get_one,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any> {
return this.request(url, parameter, method, paramInBody, paramType);
}
asyncGetOne(
parameter: any,
url: string = this.$api_get_one,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any> {
return this.getOne(parameter, url, method, paramInBody, paramType).toPromise();
}
/**
* 查询一个实例
*/
getMany(
parameter: any,
url: string = this.$api_get_many,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Observable<any[]> {
return this.httpRequest(url, parameter, method, paramInBody, paramType).pipe(
map((res) => {
return (res as any[]) || [];
}),
);
}
asyncGetMany(
parameter: any,
url: string = this.$api_get_many,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
): Promise<any[]> {
return this.getMany(parameter, url, method, paramInBody, paramType).toPromise();
}
/**
* @description: 异步导出文件
* 采用this.request相同的传参方式调用
* 支持多种传参方法及自定义头(推荐)
* @param parameter 条件参数
* @param url API地址
* @param method Http方法默认POST
* @param paramInBody 参数是否在body内
* @param paramType 参数类型: JSON | FORM 默认FORM
* @param allowBadCode 允许完整响应代码
* @param async 是否同步
* @returns Http响应结果
*/
exportStart(
parameter: any,
url: string = this.$api_export,
method: 'POST' | 'GET' = 'POST',
paramInBody: boolean = true,
paramType: 'JSON' | 'FORM' = 'JSON',
allowBadCode: boolean = true,
async: boolean = true,
): Observable<any> | Promise<any> {
if (allowBadCode) {
url += `?_allow_badcode=true`;
}
const response = this.httpRequest(url, parameter, method, paramInBody, paramType).pipe(
tap((res) => {
if (res.success) {
this.msgSrv.success(`创建下载任务成功,请前往下载任务列表下载您的文件!`);
window.open('#/download');
}
return res;
}),
);
return async ? response.toPromise() : response;
}
/**
* 导出文件
* @param body Http body参数
*/
exportFile(body: any = {}, url: string = this.$api_export): void {
this.fileUtil.download(url, body, {}, 'POST');
}
/**
* 异步导出文件:
* 采用HttpClient POST方式调用
* 仅支持POST方法传参仅支持JSON对象不推荐
* @deprecated 不建议使用请使用exportStart方法代替
*/
asyncExport(params: any, url: string = this.$api_export): Promise<any> {
return this.http
.post(url, params)
.pipe(
map((m: any) => {
if (m.success) {
this.msgSrv.success('创建导出文件任务成功,请前往下载管理中下载您的文件!');
window.open('#/download');
return m.data;
} else {
this.msgSrv.warning(m.msg);
return false;
}
}),
)
.toPromise();
}
/**
* 直接下载文件
*/
openDownload(url: string, body: any = {}): void {
if (url.startsWith('/')) {
url = url.substr(1);
}
let newUrl = `${environment.api}/${url}`;
if (body && JSON.stringify(body) !== '{}') {
newUrl = newUrl + '?';
for (const key in body) {
if (Object.prototype.hasOwnProperty.call(body, key)) {
newUrl = newUrl + key + '=' + body[key] + '&';
}
}
}
if (newUrl.endsWith('&')) {
newUrl = newUrl.substr(0, newUrl.length - 1);
}
window.open(newUrl);
}
/**
* 下载文件
* @param url 请求路径
* @param body Http body参数
* @param params Http params参数
*/
downloadFile(url: string, body: any = {}, params: any = {}, method: 'POST' | 'GET' = 'POST'): void {
this.fileUtil.download(url, body, params, method);
}
/**
* 下载模版
* @param body Http body参数
* @param params Http params参数
*/
downloadTpl(body: any = {}, params: any = {}): void {
this.fileUtil.download(this.$api_import_download_tpl, body, params);
}
/**
* 处理上传状态
*/
handleUpload({ file, fileList }: NzUploadChangeParam): void {
const status = file.status;
if (status !== 'uploading') {
// console.log(file, fileList);
}
if (status === 'done') {
this.msgSrv.success(`${file.name} 上传成功.`);
} else if (status === 'error') {
this.msgSrv.error(`${file.name} 上传失败.`);
}
}
/**
* 获取字典
*/
getDict(key: string): Observable<any[]> {
return this.http.post(this.$api_get_dict, { dict: key }).pipe(
map((res) => {
if (res.success === true) {
return res.data.map((r: any) => {
return {
label: r.itemValue,
value: r.itemKey,
};
});
} else {
this.msgSrv.warning(`获取取字典【${key}】时发生错误:${res.msg || '未知错误!'}`);
return [];
}
}),
);
}
/**
* 编码自定义头
* @param url 需要请求的URL
* @param customHeader 自定义头集合
* @returns 编码后的URL
*/
encodeUrlHeader(url: string, customHeader: { key: string; value: string }[]): string {
if (customHeader && customHeader.length > 0) {
let newUrl = '';
if (url.includes('?')) {
newUrl = url + '&_custom_header=' + encodeURI(JSON.stringify(customHeader));
} else {
newUrl = url + '?_custom_header=' + encodeURI(JSON.stringify(customHeader));
}
return newUrl;
}
return url;
}
/**
* 获取URL指定参数的值
*/
private getParams(paramName: string, url: string): string {
const paramsIndex = url.indexOf('?');
if (paramsIndex > -1) {
const paramsStr = url.substr(paramsIndex + 1);
const params = paramsStr.split('&');
const keyMap = params.find((e) => e.includes(paramName));
const value = keyMap ? keyMap.split('=')[1] : '';
return value;
}
return '';
}
}

View File

@ -0,0 +1,130 @@
/* eslint-disable no-underscore-dangle */
/*
* @Author: Maple
* @Date: 2021-03-22 09:35:02
* @LastEditors: Do not edit
* @LastEditTime: 2021-06-18 00:34:01
* @Description: 全局缓存服务
*/
import { Injectable } from '@angular/core';
import { cacheConf } from '@conf/cache.conf';
import { CacheService } from '@delon/cache';
import { BehaviorSubject } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
import { ICacheObj } from '../../interfaces/core/i-cache-obj';
import { EADateUtil } from '../../utils';
import { EAEncryptUtil } from '../../utils/encrypt.util';
@Injectable({
providedIn: 'root',
})
export class EACacheService {
// 监听最后操作时间值变化
private listen$ = new BehaviorSubject<number>(0);
private listen = this.listen$.asObservable();
constructor(private service: CacheService) {
this.listen.pipe(distinctUntilChanged()).subscribe((res) => {
this.set(cacheConf.last_operation_time, res);
});
}
/**
* @description 设置缓存
* @param key 缓存键值
* @param data 缓存数据
* @param vld 有效时间
* @param encrypt 是否加密
*/
set(key: string, data: any, vld: number = 0, encrypt: boolean = false) {
// 去除缓存数据两侧空格
if (typeof data === 'string') {
data = data.trim();
}
const cahceObj: ICacheObj = {
pd: new Date().getTime(),
data,
vld,
encrypt,
};
if (encrypt) {
// 加密
cahceObj.data = EAEncryptUtil.encryptByEnAES(JSON.stringify(data));
}
this.service.set(key, cahceObj);
// 更新系统最后操作时间
this.refleshLastOperationTime();
}
/**
* @description 获取缓存
* @param key 缓存键名
*/
get(key: string) {
// 获取缓存对象
const cacheObj = this.service.getNone<any>(key);
// 判断是否存在
if (!cacheObj) {
// 更新系统最后操作时间
this.refleshLastOperationTime();
return null;
}
// 判断有效期
if (cacheObj.vld > 0) {
// 获取系统最后操作时间
const last_operation_time: number = this.getLastOperationTime();
const start = cacheObj.pd > last_operation_time ? cacheObj.pd : last_operation_time;
const vld: Date = EADateUtil.timestampToDate(start + cacheObj.vld);
const expired = EADateUtil.dateDiff(vld, new Date()) <= 0;
if (expired) {
// 已过期,清除缓存
this.remove(key);
// 更新系统最后操作时间
this.refleshLastOperationTime();
return null;
}
}
// 判断是否加密
if (cacheObj.encrypt) {
const encryptJson = EAEncryptUtil.deencryptByDeAES(cacheObj.data);
// 更新系统最后操作时间
this.refleshLastOperationTime();
return JSON.parse(encryptJson);
}
// 更新系统最后操作时间
this.refleshLastOperationTime();
return cacheObj.data;
}
/**
* @description 移除缓存
* @param key 缓存键名
*/
remove(key: string) {
this.service.remove(key);
}
/**
* @description 清除所有缓存
*/
clear(): void {
this.service.clear();
}
/**
* 刷新系统最后操作时间
*/
refleshLastOperationTime() {
this.listen$.next(new Date().getTime());
}
/**
* 获取系统最后操作时间
*/
private getLastOperationTime(): number {
// 获取缓存对象
const cacheObj: ICacheObj = this.service.getNone<ICacheObj>(cacheConf.last_operation_time);
return cacheObj?.data || 0;
}
}

View File

@ -0,0 +1,19 @@
/*
* @Author: Maple
* @Date: 2021-03-22 09:35:02
* @LastEditors: Do not edit
* @LastEditTime: 2021-06-11 17:00:07
* @Description: 全局事件监听服务
*/
import { Injectable } from '@angular/core';
import * as EventEmitter from 'eventemitter3';
@Injectable({
providedIn: 'root',
})
export class EAEventService {
event: EventEmitter;
constructor() {
this.event = new EventEmitter();
}
}

View File

@ -0,0 +1,104 @@
/*
* @Author: Maple
* @Date: 2021-03-22 11:42:26
* @LastEditors: Do not edit
* @LastEditTime: 2021-03-29 14:47:54
* @Description: 全局验证服务
*/
import { Injectable, Injector } from '@angular/core';
import { BaseService } from '../core/base.service';
@Injectable({
providedIn: 'root',
})
export class EAValidateService extends BaseService {
constructor(public injector: Injector) {
super(injector);
}
/**
* 通过正则表达式验证字符串
* @param value 待验证的字符串
* @param partern 正则表达式
* @returns 验证结果
*/
validate(value: string, partern: RegExp): boolean {
const reg = new RegExp(partern);
return reg.test(value);
}
/**
* 验证手机号码
* @param value 待验证的值
* @returns 验证结果
*/
validateChineseCharacters(value: string, star: number): boolean {
const express = /^[\u4e00-\u9fa5]{2, 4}$/;
return this.validate(value, express);
}
/**
* 验证手机号码
* @param value 待验证的值
* @returns 验证结果
*/
validateMobile(value: string): boolean {
const express = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
return this.validate(value, express);
}
/**
* 验证固定电话
* @param value 待验证的值
* @returns 验证结果
*/
validateTel(value: string): boolean {
const express = /^(0\d{2,3})-?(\d{7,8})$/;
return this.validate(value, express);
}
/**
* 验证身份证号码
* @param value 待验证的值
* @param mode 匹配模式indistinct - 模糊匹配 | accurate - 精准匹配默认值indistinct
* @param length 号码长度 (默认值18)
* @returns 验证结果
*/
validateIDCard(value: string, mode: 'indistinct' | 'accurate' = 'indistinct', length: 15 | 18 = 18): boolean {
// 模糊校验
let express = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
// 精准校验18位身份证号码
const express1 = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
// 精准校验15位身份证号码
const express2 = /^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/;
if (mode === 'accurate') {
if (length === 18) {
express = express1;
} else if (length === 15) {
express = express2;
}
}
return this.validate(value, express);
}
/**
* 验证邮政编码
* @param value 待验证的值
* @returns 验证结果
*/
validatePostalCode(value: string): boolean {
const express = /^[1-9]\d{5}$/;
return this.validate(value, express);
}
/**
* 验证邮箱地址
* @param value 待验证的值
* @returns 验证结果
*/
validateEmail(value: string): boolean {
const express = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
return this.validate(value, express);
}
}

View File

@ -0,0 +1,12 @@
// Core
export * from './core/base.service';
export * from './core/cache.service';
export * from './core/validate.service';
// Bussiness
export * from './business/account.service';
export * from './business/authorization.service';
export * from './business/enterprise.service';
export * from './business/captcha.service';
export * from './business/user.service';
export * from './business/sl-platform.service';