Skip to content

Commit

Permalink
feat: 식사 상세 페이지 완성, 메인 대시보드 페이지 완성
Browse files Browse the repository at this point in the history
  • Loading branch information
ArpaAP committed Aug 6, 2024
1 parent 06a4f27 commit ee84526
Show file tree
Hide file tree
Showing 19 changed files with 875 additions and 321 deletions.
Binary file modified .yarn/install-state.gz
Binary file not shown.
13 changes: 11 additions & 2 deletions apps/web/src/app/analyze/page.layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'

import dayjs from 'dayjs'
import 'dayjs/locale/ko'

dayjs.locale('ko')

interface AnalyzePageLayoutProps {
mealId: string
meal: Meal
Expand All @@ -29,14 +34,18 @@ export default function AnalyzePageLayout({
for (let mealItem of mealItems) {
try {
await axios.post(`/api/analyze?mealItemId=${mealItem.mealItemId}`)
setSuccessCount((count) => count + 1)
} catch (error) {
console.error(error)
} finally {
setSuccessCount((count) => count + 1)
}
}

toast.success('분석이 완료되었습니다!')
setTimeout(() => router.push(`/meal/${mealId}`), 2000)
setTimeout(
() => router.push(`/meals/${dayjs(meal.date).format('YYYY-MM-DD')}`),
2000
)
})()
}, [mealItems])

Expand Down
110 changes: 93 additions & 17 deletions apps/web/src/app/api/analyze/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,19 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const user = await prisma.user.findUnique({
where: { email: session.user.email ?? undefined },
})

if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}

const mealItem = await prisma.mealItem.findUnique({
where: {
mealItemId,
meal: {
user: {
email: session.user.email,
},
userId: user.userId,
},
},
include: {
Expand Down Expand Up @@ -83,27 +89,97 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ message: 'No analysis result' }, { status: 400 })
}

const nutrientData = {
kcal: analysisResult.nut.food_kcal,
carbohydrate: analysisResult.nut.food_carbohydrate,
sugar: analysisResult.nut.food_sugar,
fat: analysisResult.nut.food_fat,
protein: analysisResult.nut.food_protein,
calcium: analysisResult.nut.food_calcium,
phosphorus: analysisResult.nut.food_phosphorus,
natrium: analysisResult.nut.food_natrium,
kalium: analysisResult.nut.food_kalium,
magnesium: analysisResult.nut.food_magnesium,
iron: analysisResult.nut.food_iron,
zinc: analysisResult.nut.food_zinc,
cholesterol: analysisResult.nut.food_cholesterol,
transfat: analysisResult.nut.food_transfat,
}

// try {
// var r = await axios.post(
// `${process.env.AI_API_URL}/score`,
// {
// user_info: {
// gender: user.gender === 'male' ? 1 : 0,
// age:
// new Date().getFullYear() - new Date(user.birthDate).getFullYear(),
// height: user.height,
// weight: user.weight,
// activity: 2,
// },
// daily_nutrient: nutrientData,
// },
// {}
// )
// } catch (_e) {
// const e = _e as AxiosError

// return NextResponse.json(
// { message: 'Failed to score', error: e.response?.data },
// { status: 500 }
// )
// }

// const scoreData =
// typeof r.data === 'string'
// ? JSON.parse(r.data.replace(/NaN/g, '0.0'))
// : r.data

const mealItemAnalysis = await prisma.mealItemAnalysis.create({
data: {
mealItemId: mealItem.mealItemId,
classId: analysisResult.cls,
className: analysisResult.class,
confidence: analysisResult.confidence,
amount: analysisResult.nut.food_amount,
kcal: analysisResult.nut.food_kcal,
carbohydrate: analysisResult.nut.food_carbohydrate,
sugar: analysisResult.nut.food_sugar,
fat: analysisResult.nut.food_fat,
protein: analysisResult.nut.food_protein,
calcium: analysisResult.nut.food_calcium,
phosphorus: analysisResult.nut.food_phosphorus,
natrium: analysisResult.nut.food_natrium,
kalium: analysisResult.nut.food_kalium,
magnesium: analysisResult.nut.food_magnesium,
iron: analysisResult.nut.food_iron,
zinc: analysisResult.nut.food_zinc,
cholesterol: analysisResult.nut.food_cholesterol,
transfat: analysisResult.nut.food_transfat,
...nutrientData,

// totalScore: scoreData.daily_score,
// energyScore: scoreData.detail.energy_score.total,
// eer: scoreData.detail.energy_score.EER,

// totalRatioScore: scoreData.detail.ratio_score.energy_ratio_score,
// ratioCarbohydrateScore:
// scoreData.detail.ratio_score.detail.ratio_carb_score,
// ratioProteinScore:
// scoreData.detail.ratio_score.detail.ratio_protein_score,
// ratioFatScore: scoreData.detail.ratio_score.detail.ratio_fat_score,
// ratioTransfatScore:
// scoreData.detail.ratio_score.detail.ratio_transfat_score,

// totalNutritionScore: scoreData.detail.nutrition_score.total,
// nutritionCarbohydrateScore:
// scoreData.detail.nutrition_score.detail.nut_carbohydrate_score,
// nutritionProteinScore:
// scoreData.detail.nutrition_score.detail.nut_protein_score,
// nutritionCalciumScore:
// scoreData.detail.nutrition_score.detail.nut_calcium_score,
// nutritionPhosphorusScore:
// scoreData.detail.nutrition_score.detail.nut_phosphorus_score,
// nutritionMagnesiumScore:
// scoreData.detail.nutrition_score.detail.nut_magnesium_score,
// nutritionIronScore:
// scoreData.detail.nutrition_score.detail.nut_iron_score,
// nutritionZincScore:
// scoreData.detail.nutrition_score.detail.nut_zinc_score,

// totalPenalty: scoreData.detail.penalty.total,
// phosphorusPenalty: scoreData.detail.penalty.detail.phosphorus_penalty,
// natriumPenalty: scoreData.detail.penalty.detail.natrium_penalty,
// ironPenalty: scoreData.detail.penalty.detail.iron_penalty,
// zincPenalty: scoreData.detail.penalty.detail.zinc_penalty,
// cholesterolPenalty: scoreData.detail.penalty.detail.cholesterol_penalty,
},
})

Expand Down
43 changes: 43 additions & 0 deletions apps/web/src/app/api/articles/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { getServerSession } from 'next-auth'
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@repo/database'
import { articlePostSchema } from './schema'

const prisma = new PrismaClient()

export async function POST(request: NextRequest) {
const session = await getServerSession()

if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

let user = await prisma.user.findUnique({
where: {
email: session.user.email!,
},
})

if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}

const body = await request.json()

const parse = articlePostSchema.safeParse(body)

if (!parse.success) {
return NextResponse.json({ error: parse.error }, { status: 400 })
}

await prisma.meal.update({
where: {
mealId: parse.data.mealId,
},
data: {
isPublic: true,
},
})

return NextResponse.json({ message: 'OK' })
}
5 changes: 5 additions & 0 deletions apps/web/src/app/api/articles/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { z } from 'zod'

export const articlePostSchema = z.object({
mealId: z.string(),
})
Loading

0 comments on commit ee84526

Please sign in to comment.