Skip to content

Commit

Permalink
Merge pull request #12 from graywenn/feature/addPostgresql
Browse files Browse the repository at this point in the history
add postgresql
  • Loading branch information
greywen authored Jul 4, 2022
2 parents 4bddcbe + 8251201 commit e315257
Show file tree
Hide file tree
Showing 16 changed files with 352 additions and 36 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@nestjs/platform-express": "^8.0.0",
"@nestjs/platform-socket.io": "^8.4.4",
"@nestjs/schedule": "^1.1.0",
"@nestjs/typeorm": "^8.1.4",
"@nestjs/websockets": "^8.4.4",
"config": "^3.3.7",
"ioredis": "^5.0.5",
Expand All @@ -38,9 +39,11 @@
"openid-client": "^5.1.6",
"passport": "^0.5.2",
"passport-jwt": "^4.0.0",
"pg": "^8.7.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"typeorm": "^0.3.7",
"uuid": "^8.3.2"
},
"devDependencies": {
Expand Down
16 changes: 13 additions & 3 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
} from './controllers';
import { jwtModuleOptions, redisModuleOptions } from './modules';
import { TimeSheetSocket } from './sockets';
import { DingTalkSchedule, TimeSheetSchedule } from './schedules';
import { TimeSheetSchedule } from './schedules';
import {
AttendanceService,
AuthService,
Expand All @@ -25,13 +25,24 @@ import {
InformService,
} from './services';
import { JwtStrategy, WsGuard } from './strategys';

import { TypeOrmModule } from '@nestjs/typeorm';
import { join } from 'path';
import config from '@config/config';
import { UserTimesheet } from './entities/timesheet.enetity';
@Module({
imports: [
PassportModule,
JwtModule.register(jwtModuleOptions),
RedisModule.forRoot(redisModuleOptions),
ScheduleModule.forRoot(),
TypeOrmModule.forRoot({
type: 'postgres',
...config.postgresql,
entities: [join(__dirname, '**', '*.entity.{ts,js}')],
migrationsTableName: 'migration',
migrations: ['src/migration/*.ts'],
}),
TypeOrmModule.forFeature([UserTimesheet]),
],
controllers: [
AppController,
Expand All @@ -53,7 +64,6 @@ import { JwtStrategy, WsGuard } from './strategys';
UserService,
InformService,
TimeSheetSocket,
DingTalkSchedule,
TimeSheetSchedule,
],
exports: [AuthService],
Expand Down
14 changes: 14 additions & 0 deletions src/config/config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { ServerEnvironment } from '@constants/server';
import * as config from 'config';
interface IConfig {
server: {
port: number;
environment: ServerEnvironment;
};
dingTalk: {
bossId: string;
Expand Down Expand Up @@ -49,11 +51,22 @@ interface IConfig {
secret: string;
expiresIn: string;
};
postgresql: {
host: string;
port: number;
username: string;
password: string;
database: string;
autoLoadEntities: boolean;
synchronize: boolean;
logging: boolean;
};
}

export default <IConfig>{
server: {
port: config.get('server.port'),
environment: config.get('server.environment'),
},
dingTalk: {
bossId: config.get('dingTalk.bossId'),
Expand Down Expand Up @@ -100,4 +113,5 @@ export default <IConfig>{
secret: config.get('jwt.secret'),
expiresIn: config.get('jwt.expiresIn'),
},
postgresql: config.get('postgresql'),
};
1 change: 0 additions & 1 deletion src/constants/index.ts

This file was deleted.

4 changes: 4 additions & 0 deletions src/constants/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export enum ServerEnvironment {
'development',
'production',
}
4 changes: 2 additions & 2 deletions src/controllers/dingTalk.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from '@dtos/dingTlak';
import { ICreateReport } from '@interfaces/dingTalk';
import { NestRes } from '@interfaces/nestbase';
import { ITimeSheetData } from '@interfaces/timesheet';
import { ITimeSheet } from '@interfaces/timesheet';
import { InjectRedis, Redis } from '@nestjs-modules/ioredis';
import {
Body,
Expand Down Expand Up @@ -215,7 +215,7 @@ export class DingTalkController {
async getReportTemplateByName(@Request() req: NestRes) {
const { dingTalkUserId } = req.user;
const _timesheet = await this.redis.get('timesheets');
const datas = <ITimeSheetData[]>JSON.parse(_timesheet || '[]');
const datas = <ITimeSheet[]>JSON.parse(_timesheet || '[]');
const userTimeSheet = datas.find((x) => x.userid === dingTalkUserId);

const result = await this.dingTalkService.getReportTemplateByName({
Expand Down
13 changes: 8 additions & 5 deletions src/controllers/timesheet.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Body, Controller, Get, Param, Put, UseGuards } from '@nestjs/common';
import FileData from '@core/files.data';
import { ITimeSheetData } from '@interfaces/timesheet';
import { ITimeSheet } from '@interfaces/timesheet';
import { InjectRedis, Redis } from '@nestjs-modules/ioredis';
import { AuthGuard } from '@nestjs/passport';
import * as moment from 'moment';
Expand All @@ -16,25 +16,28 @@ export class TimeSheetController {
) {
const templateData = await FileData.readTimeSheetTemplate();
const users = await FileData.readUsers();
let datas = [];
let datas = <ITimeSheet[]>[];

if (date === moment().format('YYYY-MM-DD')) {
const _timesheet = await this.redis.get('timesheets');
datas = <ITimeSheetData[]>JSON.parse(_timesheet || '[]');
datas = <ITimeSheet[]>JSON.parse(_timesheet || '[]');
} else {
try {
const result = await FileData.readTimeSheet(date);
datas = <ITimeSheetData[]>JSON.parse(result).users;
datas = <ITimeSheet[]>JSON.parse(result).users;
} catch (err) {}
}
const timeSheetData = users
.filter((x) => x.dept_name === dept_name)
.map((x) => {
const _data = datas.find((d) => d.userid === x.id);
return {
userid: x.id,
name: x.english_name,
groupid: x.groupid,
value: datas.find((d) => d.userid === x.id)?.value || null,
value: _data?.value || '',
createTime: _data?.createTime || '',
updateTime: _data?.updateTime || '',
};
});

Expand Down
27 changes: 27 additions & 0 deletions src/entities/timesheet.enetity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Column, Entity } from 'typeorm';

@Entity({ name: 'user_timesheet' })
export class UserTimesheet {
@Column({ primary: true, generated: 'uuid' })
id: string;
@Column('jsonb', { array: false, default: () => "'[]'", nullable: true })
timesheet?: ITimeSheet[];
@Column('date')
createTime: string;
}

export interface ITimeSheet {
userid: string;
name: string;
value?: string;
groupid: number;
updateTime: string;
createTime: string;
}

export interface ISheetTemplate {
frontend: string;
backend: string;
test: string;
nodejs: string;
}
2 changes: 1 addition & 1 deletion src/interfaces/dingTalk/attendance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
AttendanceCheckType,
AttendanceState,
TimeResultType,
} from '../../constants';
} from '../../constants/dingTalk';
import { IDingTalkBaseResult } from './base';

export interface IUserAttendances {
Expand Down
4 changes: 3 additions & 1 deletion src/interfaces/timesheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ export interface ISheetTemplate {
test: string;
}

export interface ITimeSheetData {
export interface ITimeSheet {
userid: string;
name: string;
value?: string;
groupid: number;
updateTime: string;
createTime: string;
}
24 changes: 16 additions & 8 deletions src/schedules/timesheet.schedule.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import config from '@config/config';
import FileData from '@core/files.data';
import { ITimeSheetData } from '@interfaces/timesheet';
import { ITimeSheet } from '@interfaces/timesheet';
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import * as moment from 'moment';
import { InjectRedis, Redis } from '@nestjs-modules/ioredis';
import { InjectRepository } from '@nestjs/typeorm';
import { UserTimesheet } from 'src/entities/timesheet.enetity';
import { Repository } from 'typeorm';
import { now } from '@utils/utils';
@Injectable()
export class TimeSheetSchedule {
constructor(@InjectRedis() private readonly redis: Redis) {}
constructor(
@InjectRedis() private readonly redis: Redis,
@InjectRepository(UserTimesheet)
private readonly timesheetRepository: Repository<UserTimesheet>,
) {}

@Cron(config.job.saveTimeSheetRule, { name: 'SaveTimeSheetSchedule' })
async run() {
Expand All @@ -19,12 +27,12 @@ export class TimeSheetSchedule {
}
console.log('Saving TimeSheet...');
const _timesheet = await this.redis.get('timesheets');
const timesheets = <ITimeSheetData[]>JSON.parse(_timesheet || '[]');
const result = await FileData.writeTimeSheet(
currentDate.format('YYYY-MM-DD'),
JSON.stringify({ users: timesheets }),
);
if (result) {
const timesheets = <ITimeSheet[]>JSON.parse(_timesheet || '[]');
const result = await this.timesheetRepository.save({
timesheet: timesheets,
createTime: now(),
});
if (result.id) {
await this.redis.set('timesheets', '[]');
console.log('Save TimeSheet successful!');
} else {
Expand Down
5 changes: 4 additions & 1 deletion src/services/attendance.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
AttendanceCheckType,
AttendanceState,
TimeResultType,
} from '../constants';
} from '../constants/dingTalk';

interface ITimes {
start: string;
Expand Down Expand Up @@ -155,6 +155,9 @@ export class AttendanceService {
if (await this.whetherLeaveOneDay()) {
return;
}
if (this.user.groupid >= 1 && this.user.groupid <= 4) {
return;
}
const { date } = this.findNextNotHolodayDate(
moment(this.tiems.start).format('YYYY-MM-DD'),
);
Expand Down
4 changes: 2 additions & 2 deletions src/services/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AttendanceState } from '@constants/dingTalk';
import FileData from '@core/files.data';
import { IAttendances, IUserAttendances } from '@interfaces/dingTalk';
import { ITimeSheetData } from '@interfaces/timesheet';
import { ITimeSheet } from '@interfaces/timesheet';
import { Injectable } from '@nestjs/common';
import * as moment from 'moment';
import { InjectRedis, Redis } from '@nestjs-modules/ioredis';
Expand All @@ -12,7 +12,7 @@ export class UserService {

async getTodayTimeSheet(username: string) {
const data = await this.redis.get('timesheets');
const timesheet = <ITimeSheetData[]>JSON.parse(data || '[]');
const timesheet = <ITimeSheet[]>JSON.parse(data || '[]');
const users = await FileData.readUsers();
const user = users.find((x) => x.name === username);
const todayTimeSheet = timesheet.find(
Expand Down
11 changes: 8 additions & 3 deletions src/sockets/timesheet.socket.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import { ITimeSheetData } from '@interfaces/timesheet';
import { ITimeSheet } from '@interfaces/timesheet';
import { UseGuards } from '@nestjs/common';
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import { InjectRedis, Redis } from '@nestjs-modules/ioredis';
import { Socket } from 'socket.io';
import { WsGuard } from '../strategys';
import { now } from '@utils/utils';

@UseGuards(WsGuard)
@WebSocketGateway({ namespace: 'timesheet', cors: '*' })
export class TimeSheetSocket {
constructor(@InjectRedis() private readonly redis: Redis) {}
@SubscribeMessage('sendMessage')
async onEvent(client: Socket, data: ITimeSheetData) {
async onEvent(client: Socket, data: ITimeSheet) {
const _timesheet = await this.redis.get('timesheets');
const timesheets = <ITimeSheetData[]>JSON.parse(_timesheet || '[]');
const timesheets = <ITimeSheet[]>JSON.parse(_timesheet || '[]');
const _data = timesheets.find((x) => x.userid === data.userid);
data.createTime = _data?.createTime || now();
data.updateTime = now();
if (_data) {
// 使用token中的userid=>每用户都只能编辑自己的timesheet不能修改其他用户的
// _data.userid = client.data.dingTalkUserId;
_data.userid = data.userid;
_data.value = data.value;
_data.createTime = data.createTime || now();
_data.updateTime = now();
} else {
timesheets.push(data);
}
Expand Down
6 changes: 5 additions & 1 deletion src/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as moment from 'moment';
import { AttendanceState } from '../constants';
import { AttendanceState } from '../constants/dingTalk';

/**
* 简单数组去重 eg: [1,2,2]=>[1,2] / ["1","2","2"]=>["1","2"]
Expand Down Expand Up @@ -36,3 +36,7 @@ export function formatDate(
}
return date.format(format);
}

export function now(format = 'YYYY-MM-DD HH:mm:ss') {
return moment().format(format);
}
Loading

0 comments on commit e315257

Please sign in to comment.