Skip to content

Commit

Permalink
Merge pull request #19 from Suke-H/#10-1st-milestone-finish
Browse files Browse the repository at this point in the history
#10 仕上げ:DBへ所望の形式で渡す
  • Loading branch information
Suke-H authored Sep 7, 2024
2 parents fbd504c + a357f4c commit 7242ee9
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 73 deletions.
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"start": "npm run docker:build && npm run docker:run",
"stop": "npm run docker:stop && npm run docker:remove-image",
"docker:build": "docker build --build-arg NODE_ENV=development -t yuru-sprint:dev .",
"docker:run": "docker run --name yuru-sprint --env-file .env.development -d -p 8080:8080 yuru-sprint:dev",
"docker:stop": "docker stop yuru-sprint && docker rm yuru-sprint",
"docker:remove-image": "docker rmi yuru-sprint:dev"
},
"keywords": [],
"author": "",
Expand Down
25 changes: 7 additions & 18 deletions src/messages/weeklyReportMessage.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
function weeklyReportMessage(formattedGoals, achievementRate) {
function weeklyReportMessage(goals, achievementRate, period) {
const formattedGoals = goals.map((goal, index) =>
`${index + 1}. :${goal.emoji}: ${goal.text} ${goal.isCompleted ? "✅" : "⬜"}`
).join('\n');

return {
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: "*今週の目標の振り返り*"
text: `*今週の目標の振り返り (${period})*`
}
},
{
Expand All @@ -22,13 +26,6 @@ function weeklyReportMessage(formattedGoals, achievementRate) {
text: `全体の達成率: ${achievementRate}%`
}
},
{
type: "section",
text: {
type: "mrkdwn",
text: "今週の振り返りをしましょう!\n今週の目標達成状況を確認し、感想を入力してください。"
}
},
{
type: "input",
block_id: "reflection_input",
Expand All @@ -53,18 +50,10 @@ function weeklyReportMessage(formattedGoals, achievementRate) {
text: "送信",
emoji: true
},
value: JSON.stringify({ goals, period }),
action_id: "submit_reflection"
}
]
},
{
type: "context",
elements: [
{
type: "plain_text",
text: JSON.stringify({ formattedGoals, achievementRate })
}
]
}
]
};
Expand Down
4 changes: 1 addition & 3 deletions src/modules/sendToNotionDB.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ const cleanDatabaseId = config.NOTION_DATABASE_ID.trim().replace(/"/g, '');

const notion = new Client({ auth: config.NOTION_INTEGRATION_TOKEN });

async function sendWeeklyDataToNotion(completedTasks, incompleteTasks, achievementRate, feedback) {
async function sendWeeklyDataToNotion(completedTasks, incompleteTasks, feedback, period) {
try {
const today = new Date();
const period = "8/19-8/25";

console.log('Preparing data for Notion API');
const notionData = {
Expand Down
47 changes: 26 additions & 21 deletions src/modules/statusDetector.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
async function detectStatuses(slack, channelId) {
try {
const weeklyGoals = await getWeeklyGoals(slack, channelId);

if (!weeklyGoals || weeklyGoals.length === 0) {
console.log("No goals found for the week");
return [];
}

const goalStatuses = await Promise.all(weeklyGoals.map(async (goal) => {
const reactions = await getReactions(slack, channelId, goal.messageTs, goal.emoji);
const isCompleted = reactions.count >= 2;
return { ...goal, isCompleted };
}));

return goalStatuses;
} catch (error) {
console.error('Error detecting task statuses:', error);
return [];
try {
const { weeklyGoals, startDate } = await getWeeklyGoals(slack, channelId);

if (!weeklyGoals || weeklyGoals.length === 0) {
console.log("No goals found for the week");
return { goalStatuses: [], period: null };
}

const goalStatuses = await Promise.all(weeklyGoals.map(async (goal) => {
const reactions = await getReactions(slack, channelId, goal.messageTs, goal.emoji);
const isCompleted = reactions.count >= 2;
return { ...goal, isCompleted };
}));

const endDate = new Date().toISOString().split('T')[0]; // 今日の日付
const period = `${startDate} - ${endDate}`;

return { goalStatuses, period };
} catch (error) {
console.error('Error detecting task statuses:', error);
return { goalStatuses: [], period: null };
}
}

async function getWeeklyGoals(slack, channelId) {
try {
Expand All @@ -43,7 +46,7 @@ async function detectStatuses(slack, channelId) {

if (!goalMessage) {
console.log("No valid goal message found");
return [];
return { weeklyGoals: [], startDate: null };
}

console.log("Found goal message:", goalMessage.text);
Expand All @@ -60,11 +63,13 @@ async function detectStatuses(slack, channelId) {
return null;
}).filter(Boolean);

const startDate = new Date(parseInt(goalMessage.ts.split('.')[0]) * 1000).toISOString().split('T')[0];

console.log("Extracted goals:", goals);
return goals;
return { weeklyGoals: goals, startDate };
} catch (error) {
console.error('Error retrieving weekly goals:', error);
return [];
return { weeklyGoals: [], startDate: null };
}
}

Expand Down
38 changes: 13 additions & 25 deletions src/modules/weeklyReport.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ async function generateWeeklyReport(slack, channelId) {
try {
console.log('Generating weekly report...');

const goalStatuses = await detectStatuses(slack, channelId);
const { goalStatuses, period } = await detectStatuses(slack, channelId);
console.log('Goal statuses:', JSON.stringify(goalStatuses, null, 2));
console.log('Period:', period);

if (goalStatuses.length === 0) {
await slack.chat.postMessage({
Expand All @@ -16,10 +18,9 @@ async function generateWeeklyReport(slack, channelId) {
return;
}

const formattedGoals = formatGoalStatuses(goalStatuses);
const achievementRate = calculateAchievementRate(goalStatuses);

const message = weeklyReportMessage(formattedGoals, achievementRate);
const message = weeklyReportMessage(goalStatuses, achievementRate, period);

await slack.chat.postMessage({
channel: channelId,
Expand All @@ -33,46 +34,33 @@ async function generateWeeklyReport(slack, channelId) {
}
}

function formatGoalStatuses(goalStatuses) {
return goalStatuses.map((goal, index) => {
const statusEmoji = goal.isCompleted ? "✅" : "⬜";
return `${index + 1}. :${goal.emoji}: ${goal.text} ${statusEmoji}`;
}).join('\n');
}

function calculateAchievementRate(goalStatuses) {
const completedGoals = goalStatuses.filter(goal => goal.isCompleted);
return Math.round((completedGoals.length / goalStatuses.length) * 100);
}

async function handleUserFeedback(feedback, hiddenGoalsData, slack, channelId) {
async function handleUserFeedback(payload, slack, channelId) {
try {
const feedback = payload.state.values.reflection_input.reflection_input.value;
if (!feedback) {
throw new Error('Feedback is empty');
}

const { formattedGoals, achievementRate } = hiddenGoalsData;
const { goals, period } = JSON.parse(payload.actions[0].value);
console.log('Parsed data:', { goals, period });

// 完了タスクと未完了タスクを分離
const completedTasks = [];
const incompleteTasks = [];
formattedGoals.split('\n').forEach(goal => {
if (goal.includes('✅')) {
completedTasks.push(goal.replace('✅', '').trim());
} else {
incompleteTasks.push(goal.replace('⬜', '').trim());
}
});
const completedTasks = goals.filter(goal => goal.isCompleted).map(goal => `${goal.emoji} ${goal.text}`);
const incompleteTasks = goals.filter(goal => !goal.isCompleted).map(goal => `${goal.emoji} ${goal.text}`);

await sendWeeklyDataToNotion(
completedTasks.join('\n') || 'なし',
incompleteTasks.join('\n') || 'なし',
achievementRate,
feedback
feedback,
period
);

console.log('Data sent to Notion successfully');

// フィードバックを受け取ったことを確認するメッセージをチャンネルに送信
await slack.chat.postMessage({
channel: channelId,
text: "Notionへ送信しました。1週間お疲れ様!"
Expand Down
6 changes: 1 addition & 5 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,16 +73,12 @@ function createApp(testMode = false) {
// 週終わりに送信した週間レポートのフィードバックを受け取る -> Notionに送信
} else if (action.action_id === 'submit_reflection') {
const userFeedback = payload.state.values.reflection_input.reflection_input.value;
const hiddenGoalsData = JSON.parse(payload.message.blocks[payload.message.blocks.length - 1].elements[0].text);

console.log('User feedback:', userFeedback);
console.log('Hidden goals data:', hiddenGoalsData);

if (!userFeedback) {
throw new Error('User feedback is empty');
}

await weeklyReport.handleUserFeedback(userFeedback, hiddenGoalsData, slack, payload.channel.id);
await weeklyReport.handleUserFeedback(payload, slack, payload.channel.id);
}
} catch (error) {
console.error('Error handling action:', error);
Expand Down

0 comments on commit 7242ee9

Please sign in to comment.