Skip to content

Commit

Permalink
Merge pull request #102 from GzhiYi/feat/6.0.2
Browse files Browse the repository at this point in the history
Feat/6.0.2
  • Loading branch information
GzhiYi authored Dec 24, 2021
2 parents 70f84ed + f10f6f7 commit a74b5c6
Show file tree
Hide file tree
Showing 11 changed files with 987 additions and 68 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules/
cloudfunctions/backup/wxInfo.js
cloudfunctions/**/package-lock.json
cloudfunctions/**/package-lock.json
cloudfunctions/**/token.js
26 changes: 25 additions & 1 deletion cloudfunctions/account/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// 云函数入口文件
const cloud = require('wx-server-sdk')
const dayjs = require('dayjs')

cloud.init()

Expand Down Expand Up @@ -41,13 +42,32 @@ exports.main = async (event) => {
message: '操作成功'
}
}

let oldNote = null
if (event.mode === 'deleteById' || event.mode === 'updateById') {
const noteRes = await db.collection('DANDAN_NOTE').doc(id).get()
// eslint-disable-next-line prefer-destructuring
oldNote = noteRes.data[0]
}
const updateStat = async (nd) => {
try {
await cloud.callFunction({
name: 'stat',
data: {
openId: wxContext.OPENID,
noteDate: dayjs(nd).format('YYYY-MM-DD')
}
})
} catch (error) {
console.log(error)
}
}
if (event.mode === 'deleteById') {
const res = await db.collection('DANDAN_NOTE').doc(id).update({
data: {
isDel: true
}
})
await updateStat(oldNote.noteDate)
return {
code: 1,
data: res,
Expand All @@ -66,6 +86,10 @@ exports.main = async (event) => {
updateTime: db.serverDate()
}
})
// 更新旧的统计数据
await updateStat(oldNote.noteDate)
// 更新最新的统计数据
await updateStat(noteDate)
return {
code: 1,
data: res,
Expand Down
1 change: 1 addition & 0 deletions cloudfunctions/account/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"dayjs": "^1.10.7",
"wx-server-sdk": "^0.8.1"
}
}
6 changes: 6 additions & 0 deletions cloudfunctions/account/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cloudfunctions/sendMessage/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"triggers": [{
"name": "timeToSendMessage",
"type": "timer",
"config": "0 0 21 * * * *"
"config": "0 0 22 * * * *"
}],
"permissions": {
"openapi": [
Expand Down
27 changes: 24 additions & 3 deletions cloudfunctions/sendMessage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ const cloud = require('wx-server-sdk')
const dayjs = require('dayjs')

cloud.init()

function notify(title, content) {
// eslint-disable-next-line global-require
const { bark } = require('./token')
if (bark) {
request(`https://api.day.app/${bark}/${encodeURI(title)}/${encodeURI(content)}`)
}
}
// 云函数入口函数
exports.main = async () => {
const wxContext = cloud.getWXContext()
Expand All @@ -28,10 +34,12 @@ exports.main = async () => {
const checkAccountTodayRes = await db.collection('DANDAN_NOTE')
.where({
openId: _.in(sendList.map((user) => user.openId)),
isDel: false,
noteDate: _.gte(new Date(startTime)).and(_.lte(new Date(endTime)))
})
.get()
const canSendList = Array.from(new Set(checkAccountTodayRes.data.map((item) => item.openId)))
const hasNoteOpenIdList = Array.from(new Set(checkAccountTodayRes.data.map((item) => item.openId)))
const canSendList = sendList.filter(u => !hasNoteOpenIdList.includes(u.openId)).map(item => item.openId)
const sendTask = []
canSendList.forEach((item) => {
const reqTask = cloud.openapi.subscribeMessage.send({
Expand All @@ -49,7 +57,20 @@ exports.main = async () => {
})
sendTask.push(reqTask)
})
await Promise.all(sendTask)
const limit = 30
if (sendTask.length > limit) {
const divide = sendTask.length / limit
for(let i = 0; i < divide; i++) {
await Promise.all(sendTask.slice(i * limit, (i + 1) * limit))
}
notify(
'模板发送提醒',
`
发送时间:${dayjs().format('YYYY-MM-DD HH:mm:ss')}
分批次数:${Math.floor(divide)}
发送人数: ${sendTask.length}
`)
}
}
} catch (err) {
// eslint-disable-next-line no-console
Expand Down
172 changes: 112 additions & 60 deletions cloudfunctions/stat/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,58 @@
1. 日期
2. 支出
3. 收入
4. 净资产
4. 净收入
5. 记账次数
6. 用户openId
*/
const cloud = require('wx-server-sdk')
const dayjs = require('dayjs')
const request = require('request')

cloud.init()
const MAX_LIMIT = 100

function strip(num, precision = 12) {
return +parseFloat(num.toPrecision(precision))
}
function notify(title, content) {
// eslint-disable-next-line global-require
const { bark } = require('./token')
if (bark) {
request(`https://api.day.app/${bark}/${encodeURI(title)}/${encodeURI(content)}`)
}
}
// 云函数入口函数
exports.main = async () => {
exports.main = async (event) => {
const wxContext = cloud.getWXContext()
cloud.updateConfig({
env: wxContext.ENV === 'local' ? 'release-wifo3' : wxContext.ENV
})
const env = wxContext.ENV === 'local' ? 'dandan-zdm86' : wxContext.ENV
cloud.updateConfig({ env })
// 初始化数据库
const db = cloud.database({
env: wxContext.ENV === 'local' ? 'release-wifo3' : wxContext.ENV
})
const db = cloud.database({ env })
const _ = db.command
// 有openId则表示只更新某个人的统计记录
let { noteDate } = event
const { openId } = event
// 定时任务不具有参数
if (!noteDate) {
noteDate = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
}
// 传入日期的开始和结束时间
// 由于是定时任务,所以需要减少一天
const statDate = openId ? dayjs(noteDate).format('YYYY-MM-DD') : noteDate
const startTime = `${statDate} 00:00:00`
const endTime = `${statDate} 23:59:59`
const isToday = dayjs().format('YYYY-MM-DD') === statDate
// 如果是更新某个人的统计数据,并且日期等于今天,则不更新
if (openId && isToday) {
return {
code: 0,
msg: '今天等定时任务统计',
data: null
}
}
// 由于性能有限,现在默认只统计自然日的数据,后面再把其他数据跑回来
const queryAll = async (collectName, queryParams) => {
const resultNum = await db.collection(collectName).count()
const resultNum = await db.collection(collectName).where(queryParams).count()
const { total } = resultNum
const batchTimes = Math.ceil(total / MAX_LIMIT)
const tasks = []
Expand All @@ -40,60 +70,82 @@ exports.main = async () => {
errMsg: acc.errMsg
}))
}
const calNote = (noteList) => {
if (!noteList) {
return {
pay: 0,
income: 0,
netIncome: 0,
noteLength: 0
}
}
let pay = 0
let income = 0
noteList.forEach((note) => {
if (note.flow === 0) {
pay += note.money
}
if (note.flow === 1) {
income += note.money
}
})
return {
pay,
income,
netIncome: income - pay,
noteTime: noteList.length
const calNote = (noteList, openIdList) => {
let index = -1
const addData = []
while (++index < openIdList.length) {
const oneOpenId = openIdList[index]
const noteListByOpenId = noteList.filter((note) => note.openId === oneOpenId)
let pay = 0
let income = 0
let netAsset = 0
let payCount = 0
let incomeCount = 0
noteListByOpenId.forEach((note) => {
// 支出
if (note.flow === 0) {
pay += note.money
payCount += 1
} else {
income += note.money
incomeCount += 1
}
})
netAsset = income - pay
addData.push({
openId: oneOpenId,
noteDate: new Date(noteDate),
pay: strip(pay),
income: strip(income),
netAsset: strip(netAsset),
payCount,
incomeCount,
createTime: new Date(), // 写入时间
updateTime: new Date(), // 更新时间
type: 'day'
})
}
return addData
}
const userData = await queryAll('USERS')
const userList = userData.data
const endDate = new Date()
const startDate = new Date().setDate(new Date().getDate() - 1)
if (userList instanceof Array) {
for (let i = 0; i < userList.length; i++) {
// eslint-disable-next-line no-await-in-loop
const noteData = await queryAll('DANDAN_NOTE', {
openId: userList[i].openId,
noteDate: _.gt(new Date(startDate)).and(_.lte(endDate)),
isDel: false
})
if (noteData.data && noteData.data.length) {
const {
pay, income, netIncome, noteTime
} = calNote(noteData.data)
// eslint-disable-next-line no-await-in-loop
await db.collection('STAT').add({
data: {
date: new Date(),
pay,
income,
netIncome,
noteTime,
openId: wxContext.OPENID
}
const params = {
noteDate: _.gte(new Date(startTime)).and(_.lte(new Date(endTime))),
isDel: false
}
if (openId) {
params.openId = openId
}
const noteListRes = await queryAll('DANDAN_NOTE', params)
const noteList = noteListRes.data
// get openId from noteList
const openIdList = Array.from(new Set(noteList.map((note) => note.openId)))
const addData = calNote(noteList, openIdList)
// 有openId,则只更新该用户该天的统计数据
if (openId) {
const oldRes = await db.collection('STAT').where({
openId,
noteDate: _.eq(statDate)
}).get()
// 更新该条记录
const updateData = addData[0]
delete updateData.createTime
try {
if (oldRes.data.length) {
await db.collection('STAT').doc(oldRes.data[0]._id).update({
data: updateData
})
}
} catch (error) {
notify('更新统计数据失败', error.toString.slice(0, 100))
}
} else {
// 插入今日统计数据
try {
await db.collection('STAT').add({
data: addData
})
notify('写入统计数据成功', `写入${statDate}统计数据共${addData.length}条,完成时间:${dayjs().format('YYYY-MM-DD HH:mm:ss')}`)
} catch (error) {
notify('写入统计数据失败', error.toString.slice(0, 100))
}
}
return {
Expand Down
1 change: 1 addition & 0 deletions cloudfunctions/stat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"dayjs": "^1.10.7",
"wx-server-sdk": "~2.4.0"
}
}
Loading

0 comments on commit a74b5c6

Please sign in to comment.