Skip to content

Commit

Permalink
feat: update
Browse files Browse the repository at this point in the history
  • Loading branch information
Bensigo committed Oct 12, 2023
1 parent 5a759f5 commit 9bed6fa
Show file tree
Hide file tree
Showing 6 changed files with 262 additions and 233 deletions.
2 changes: 2 additions & 0 deletions src/pages/api/trpc/[trpc].ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { env } from "@/env.mjs";
import { appRouter } from "@/server/api/root";
import { createTRPCContext } from "@/server/api/trpc";

export const maxDuration = 150;

// export API handler
export default createNextApiHandler({
router: appRouter,
Expand Down
210 changes: 104 additions & 106 deletions src/server/api/routers/activities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,67 +25,65 @@ export const activityRouter = createTRPCRouter({
getActivites: protectedProcedure
.input(z.object({ mood: z.number(), questId: z.string() }))
.query(async ({ ctx, input }) => {
try {
const prisma = ctx.prisma;

// check for cache
const cacheKey = `${ctx.session.user.id}_affirmation_v2`
const cacheData = await kv.get<Activity[]>(cacheKey);

console.log({ cacheData }) // log for texting
try {
const prisma = ctx.prisma;
const cacheKey = `${ctx.session.user.id}_activity`;
if (process.env.VERCEL_ENV === "production") {
// check for cache
const cacheData = await kv.get<Activity[]>(cacheKey);

if (cacheData) {
return cacheData;
}
}

if(cacheData) {
return cacheData
}
// const quest = await ctx.prisma.quest.findUnique({ where: { id: input.questId }, include: { goal: true }})
const quest = await prisma.quest.findFirst({
where: { id: input.questId },
include: { goal: true },
});

// const quest = await ctx.prisma.quest.findUnique({ where: { id: input.questId }, include: { goal: true }})
const quest = await prisma.quest.findFirst({
where: { id : input.questId },
include: { goal: true }
});

if(!quest){
throw new Error('invlaid quest')
}
if (!quest.goal)return [];
const goal = (quest.goal).name;
const prompt = `
if (!quest) {
throw new Error("invlaid quest");
}
if (!quest.goal) return [];
const goal = quest.goal.name;
const prompt = `
Imagine yourself as a specialist, someone with a mood of ${input.mood} in a scale of 1-10
Can you recommend three activities for the day that can empower him/her to reach thier goal?
Can you recommend 5 activities for the day that can empower him/her to reach thier goal?
These activities should contribute to thier pursuit of ${goal}. Please provide your response in the form of a JavaScript array of objects, with each object containing a title, duration, and a concise description (maximum 150 characters).
`.trim();


const rawActivitiyResponse = await queryOpenAi(prompt).catch((err: unknown) => {
console.log({ err })
})


console.log({ rawActivitiyResponse })
if (!rawActivitiyResponse) {
throw new Error("Oops something went wrong");

const rawActivitiyResponse = await queryOpenAi(prompt).catch(
(err: unknown) => {
console.log({ err });
}
const activities = parseActivities(rawActivitiyResponse);
console.log({ activities })
);

// set cache data

await kv.set(cacheKey, activities, {
ex: 86400
})

return activities;
console.log({ rawActivitiyResponse });
if (!rawActivitiyResponse) {
throw new Error("Oops something went wrong");
}
catch (err: unknown){
console.log(err)
throw err;
const activities = parseActivities(rawActivitiyResponse);
console.log({ activities });

// set cache data
if (process.env.VERCEL_ENV === "production") {
await kv.set(cacheKey, activities, {
ex: 86400,
});
}
return activities;
} catch (err: unknown) {
console.log(err);
throw err;
}
}),
startQuestActivity: protectedProcedure
.input(
z.object({
type: z.enum(dailyActivityEnum),
id: z.string()
id: z.string(),
})
)
.mutation(async ({ input, ctx }) => {
Expand All @@ -97,24 +95,24 @@ export const activityRouter = createTRPCRouter({

const { type, id } = input;
const quest = await prisma.quest.findFirst({
where: { userId, id },
include: { goal: true }
where: { userId, id },
include: { goal: true },
});

if (!quest) {
throw new Error("Quest not found");
}
if (!quest.goal){
throw new Error('Invalid quest')

if (!quest.goal) {
throw new Error("Invalid quest");
}

const isChat = type.toLowerCase() === DailyQuestActivity.Chat.toString().toLowerCase();
if (isChat){
const isChat =
type.toLowerCase() === DailyQuestActivity.Chat.toString().toLowerCase();
if (isChat) {
// create a new chat ;
const goal = (quest.goal).name;
await createChat(prisma, goal, userId, quest.id)

const goal = quest.goal.name;
await createChat(prisma, goal, userId, quest.id);
}

const currentDay = new Date(); // Current date
Expand Down Expand Up @@ -154,16 +152,13 @@ export const activityRouter = createTRPCRouter({

const currentProfileScore = profile.score + score;



const level = getLevel(currentProfileScore);

console.log({ level })
console.log({ level });

if (!level) {
throw new Error("Oops try again");
}


// update user score and create activity
await prisma.profile.update({
Expand All @@ -190,27 +185,31 @@ export const activityRouter = createTRPCRouter({
.input(
z.object({
id: z.string(),
chatSessionId: z.string().optional()
chatSessionId: z.string().optional(),
})
)
.mutation(async ({ ctx, input }) => {
const prisma = ctx.prisma;
const userId = ctx.session.user.id
const userId = ctx.session.user.id;

const profile = await prisma.profile.findFirst({ where: { userId }});
const profile = await prisma.profile.findFirst({ where: { userId } });

if(!profile){
throw new Error('user not found')
if (!profile) {
throw new Error("user not found");
}
const chatId = input.chatSessionId
const chatId = input.chatSessionId;

if (chatId){

const session = await prisma.dailyTherapySession.findUnique({ where: { id: chatId }});
if (!session){
throw new Error('Invalid chat session')
}
await prisma.dailyTherapySession.update({ where: { id: chatId }, data: { isActive: false }})
if (chatId) {
const session = await prisma.dailyTherapySession.findUnique({
where: { id: chatId },
});
if (!session) {
throw new Error("Invalid chat session");
}
await prisma.dailyTherapySession.update({
where: { id: chatId },
data: { isActive: false },
});
}

const activity = await prisma.dailyActivity.findFirst({
Expand All @@ -228,61 +227,61 @@ export const activityRouter = createTRPCRouter({
throw new Error("Activiy does not exit");
}


const currentScore = 50 + profile.score;
const currentLevel = getLevel(currentScore);

await prisma.profile.update({
where: {
userId
userId,
},
data: {
score: currentScore,
level: currentLevel,
}
})


},
});

const currentActivity = await prisma.dailyActivity.update({
where: {
id: input.id
id: input.id,
},
data: {
isCompleted: true,

},
include: {
quest: true
}
})
quest: true,
},
});
return currentActivity;
}),
getActiveDailyActivity: protectedProcedure.input(z.object({
type: z.enum(dailyActivityEnum)
})).query(async ({ ctx, input }) => {



const activity = ctx.prisma.dailyActivity.findFirst({
getActiveDailyActivity: protectedProcedure
.input(
z.object({
type: z.enum(dailyActivityEnum),
})
)
.query(async ({ ctx, input }) => {
const activity = ctx.prisma.dailyActivity.findFirst({
where: {
type: input.type as DailyQuestActivity,
isCompleted: false,
quest: {
userId: ctx.session.user.id,
}
},
},
include: {
quest: true
}
})

return activity;
quest: true,
},
});

return activity;
}),
getActiveStep: protectedProcedure.input(z.object({
id: z.string()
})).query(async ({ ctx , input}) => {
getActiveStep: protectedProcedure
.input(
z.object({
id: z.string(),
})
)
.query(async ({ ctx, input }) => {
const questId = input.id;

const currentDay = new Date(); // Current date
Expand All @@ -299,12 +298,12 @@ export const activityRouter = createTRPCRouter({
createdAt: {
gte: currentDayStart,
lt: new Date(currentDayStart.getTime() + 24 * 60 * 60 * 1000),
}
},
},
})
});

return { count }
})
return { count };
}),
});

/**
Expand All @@ -316,4 +315,3 @@ Zenith: 15001 - 40000
GodMode: 400001 - INFINITY
*
*/

4 changes: 2 additions & 2 deletions src/ui/quest/QuestAffrimationWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export const QuestAffrimationWrapper = () => {
onClick={goBack}
></IconButton>
</Box>
<Skeleton isLoaded={isFetched}>
{/* <Skeleton isLoaded={isFetched}>
{!hideInfo && <InfoNote>
<Box my={1} display={'flex'}width={'100%'} justifyContent={'end'}>
<Button colorScheme="sage" variant={'ghost'} onClick={() => {
Expand All @@ -64,7 +64,7 @@ export const QuestAffrimationWrapper = () => {
your journey to a more fulfilling and positive life.
</Text>
</InfoNote>}
</Skeleton>
</Skeleton> */}

<Skeleton isLoaded={isAffirmationFetched} mt={2}>
<AffirmationCard isQuest={true} data={affirmations || []} title={'Daily Quest Affrimation'}/>
Expand Down
Loading

0 comments on commit 9bed6fa

Please sign in to comment.