Skip to content

Commit

Permalink
Merge pull request #429 from TeamSparker/feature/#428
Browse files Browse the repository at this point in the history
[FEAT] 생명 타임라인 생성 및 감소 내용 추가
  • Loading branch information
youngkwon02 authored Sep 26, 2022
2 parents 65d129b + d99f7c0 commit 9d0c815
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 32 deletions.
9 changes: 9 additions & 0 deletions functions/constants/lifeTimelineMessage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const LIFE_DECREASE = (count) => {
const title = `생명 ${count}개 감소💧`;
const body = `인증하지 않은 스파커가 있었네요. 응원이 더 필요해요!`;
return { title, body };
};

module.exports = {
LIFE_DECREASE,
};
21 changes: 3 additions & 18 deletions functions/db/dialog.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,6 @@ const getUserDialogs = async (client, userId, types) => {
return convertSnakeToCamel.keysToCamel(rows);
};

const insertLifeDeductionDialogs = async (client, dialogs) => {
const { rows } = await client.query(
`
INSERT INTO spark.dialog
(user_id, room_id, life_deduction_count, type, date)
VALUES
${dialogs.join()}
RETURNING *
`,
);

return convertSnakeToCamel.keysToCamel(rows);
};

const setDialogRead = async (client, dialogId) => {
const now = dayjs().add(9, 'h');
const { rows } = await client.query(
Expand Down Expand Up @@ -73,10 +59,10 @@ const setLifeDeductionDialogsRead = async (client, userId, roomId) => {
AND type = 'LIFE_DEDUCTION'
RETURNING *
`,
[userId, roomId, now]
)
[userId, roomId, now],
);
return convertSnakeToCamel.keysToCamel(rows);
}
};

const getUnReadDialogByRoomAndUser = async (client, roomId, userId) => {
const { rows } = await client.query(
Expand All @@ -94,7 +80,6 @@ const getUnReadDialogByRoomAndUser = async (client, roomId, userId) => {
};

module.exports = {
insertLifeDeductionDialogs,
insertDialogs,
getUserDialogs,
setDialogRead,
Expand Down
1 change: 1 addition & 0 deletions functions/db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ module.exports = {
remindDB: require('./remind'),
ownershipDB: require('./ownership'),
versionDB: require('./version'),
lifeTimelineDB: require('./lifeTimeline'),
};
20 changes: 20 additions & 0 deletions functions/db/lifeTimeline.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const dayjs = require('dayjs');
const _ = require('lodash');
const convertSnakeToCamel = require('../lib/convertSnakeToCamel');

const addLifeTimeline = async (client, timelines) => {
const { rows } = await client.query(
`
INSERT INTO spark.life_timeline
(receiver_id, room_id, is_decrease, thumbnail1, thumbnail2)
VALUES
${timelines.join()}
RETURNING *
`,
);
return convertSnakeToCamel.keysToCamel(rows[0]);
};

module.exports = {
addLifeTimeline,
};
28 changes: 28 additions & 0 deletions functions/db/room.js
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,33 @@ const getFailRecords = async (client, roomIds) => {
return convertSnakeToCamel.keysToCamel(rows);
};

const getFailProfiles = async (client, roomId) => {
const now = dayjs().add(9, 'hour');
const yesterday = dayjs(now.subtract(1, 'day').format('YYYY-MM-DD'));
const { rows } = await client.query(
`
SELECT u.profile_img AS profile
FROM spark.entry e
LEFT JOIN spark.user u
ON e.user_id = u.user_id
LEFT JOIN spark.record r
ON e.entry_id = r.entry_id
LEFT JOIN spark.room room
ON e.room_id = room.room_id
WHERE room.status = 'ONGOING'
AND e.is_out = FALSE
AND e.is_kicked = FALSE
AND e.is_deleted = FALSE
AND r.day != 0
AND r.status IN ('NONE', 'CONSIDER')
AND r.date = $1
AND e.room_id = ${roomId}
`,
[yesterday],
);
return convertSnakeToCamel.keysToCamel(rows);
};

const updateLife = async (client, failCount, roomIds) => {
const now = dayjs().add(9, 'hour');
const yesterday = dayjs(now.subtract(1, 'day').format('YYYY-MM-DD'));
Expand Down Expand Up @@ -732,6 +759,7 @@ module.exports = {
getCardsByUserId,
updateLife,
getFailRecords,
getFailProfiles,
getEntriesByRoomIds,
updateThumbnail,
getOngoingRoomIds,
Expand Down
42 changes: 28 additions & 14 deletions functions/scheduler/funcs.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const db = require('../db/db');
const admin = require('firebase-admin');
const { userDB, roomDB, recordDB, scheduleDB, remindDB, dialogDB } = require('../db');
const { roomDB, recordDB, scheduleDB, remindDB, dialogDB, lifeTimelineDB } = require('../db');
const _ = require('lodash');
const dayjs = require('dayjs');
const slackAPI = require('../middlewares/slackAPI');
Expand Down Expand Up @@ -70,34 +69,49 @@ const checkLife = async () => {
const dialogRoomIds = completeRoomIds.concat(failRoomIds).concat(lifeDeductionRoomIds);
let dialogUsers = [];
if (dialogRoomIds.length) {
dialogUsers = await roomDB.getAllUsersByIds(client, completeRoomIds.concat(failRoomIds).concat(lifeDeductionRoomIds));
dialogUsers = await roomDB.getAllUsersByIds(client, completeRoomIds.concat(failRoomIds));
}
let insertDialogs = [];
let insertLifeDeductionDialogs = [];
dialogUsers.map((o) => {
if (o.status === 'FAIL' || o.status === 'COMPLETE') {
insertDialogs.push(`(${o.userId}, ${o.roomId}, '${o.status}', '${today}')`);
} else {
insertLifeDeductionDialogs.push(`(${o.userId}, ${o.roomId}, ${lifeDeductionMap.get(o.roomId)}, 'LIFE_DEDUCTION', '${today}')`);
}
insertDialogs.push(`(${o.userId}, ${o.roomId}, '${o.status}', '${today}')`);
});

if (insertDialogs.length) {
await dialogDB.insertDialogs(client, insertDialogs);
}
if (insertLifeDeductionDialogs.length) {
await dialogDB.insertLifeDeductionDialogs(client, insertLifeDeductionDialogs);

let failProfiles = {}; // 인증 안한 사용자 프로필 사진, key: roomId, value: profile 배열
let decreaseMessageUsers = await roomDB.getAllUsersByIds(client, completeRoomIds.concat(failRoomIds));
let decreaseMessage = [];
for (let i = 0; i < decreaseMessageUsers.length; i++) {
const { userId, roomId } = decreaseMessageUsers[i];

if (!Object.keys(failProfiles).includes(roomId)) {
let profiles = await roomDB.getFailProfiles(client, roomId);
profiles = profiles.sort(() => Math.random() - 0.5);
while (profiles.length < 2) {
profiles.push(null);
}
failProfiles[roomId] = profiles;
}

decreaseMessage.push(`('${userId}', '${roomId}', true, '${failProfiles[roomId][0]}', '${failProfiles[roomId][1]}')`);
}

// 생명 감소시 Time Line Insert
if (decreaseMessage.length) {
await lifeTimelineDB.addLifeTimeline(client, decreaseMessage);
}

// 살아남은 방 없으면 return
if (!successRoomIds.length) {
// 살아남은 방 없으면 return
return;
}

const survivedRoomIds = _.difference(successRoomIds, completeRoomIds);
const ongoingEntries = await roomDB.getEntriesByRoomIds(client, survivedRoomIds); // 성공한 방들의 entry 불러오기

// 추가해줄 record들의 속성들 빚어주기
const insertEntries = ongoingEntries.map((o) => {
// 추가해줄 record들의 속성들 빚어주기
const startDate = dayjs(o.startAt);
const day = dayjs(today).diff(startDate, 'day') + 1;
const queryParameter = '(' + o.entryId + ",'" + now.format('YYYY-MM-DD') + "'," + day + ')';
Expand Down

0 comments on commit 9d0c815

Please sign in to comment.