Skip to content

Commit

Permalink
fix(menus): adapt for new top chef api
Browse files Browse the repository at this point in the history
  • Loading branch information
Lutonite committed Dec 16, 2023
1 parent b166d63 commit ef253b5
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 57 deletions.
1 change: 0 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,3 @@ REDIS_URL=redis://127.0.0.1:6379
FIREBASE_CREDENTIALS_PATH=
TWITCH_CLIENT_ID=
TWITCH_CLIENT_SECRET=
TOP_CHEF_API_KEY=
4 changes: 2 additions & 2 deletions src/scheduled-tasks/canteen-menu.task.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
APIDayMenuModel,
ApiMenu,
buildDayMenuEmbed,
queryDayMenu,
} from '../services/heig-canteen-menu.service';
Expand Down Expand Up @@ -36,7 +36,7 @@ export default class CanteenMenuTask extends ScheduledTask {

private async handleGuildMenu(
guild: Guild,
menu: APIDayMenuModel,
menu: ApiMenu[],
): Promise<void> {
const { logger } = this.container;

Expand Down
91 changes: 40 additions & 51 deletions src/services/heig-canteen-menu.service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { groupBy } from '../utils/array-utils';
import { fieldValueOrEmpty } from '../utils/embed-utils';
import { capitalize } from '../utils/string-utils';
import { fetch, FetchResultTypes } from '@sapphire/fetch';
Expand All @@ -7,31 +8,34 @@ import { EmbedBuilder } from 'discord.js';

const DAY_FORMAT = 'DD MMMM YYYY';

const WEEK_API_URL = 'https://top-chef-intra-api.blacktree.io/weeks/current';
const DAY_API_URL = 'https://apix.blacktree.io/top-chef/today';
const API_URL = 'https://top-chef-2023.vercel.app/menus';

const apiHeaders = new Headers();
apiHeaders.append('x-api-key', process.env.TOP_CHEF_API_KEY ?? '');

export const queryWeekMenu = async (): Promise<APIWeekMenuModel> =>
fetch<APIWeekMenuModel>(
WEEK_API_URL,
{ headers: apiHeaders },
export const queryWeekMenu = async (): Promise<ApiMenu[]> =>
fetch<ApiMenu[]>(
oneLineTrim`
${API_URL}
?from=${dayjs().startOf('week').format('YYYY-MM-DD')}
&to=${dayjs().endOf('week').format('YYYY-MM-DD')}
`,
FetchResultTypes.JSON,
);

export const queryDayMenu = async (): Promise<APIDayMenuModel> =>
fetch<APIDayMenuModel>(DAY_API_URL, FetchResultTypes.JSON);
export const queryDayMenu = async (): Promise<ApiMenu[]> =>
fetch<ApiMenu[]>(
oneLineTrim`
${API_URL}
?from=${dayjs().format('YYYY-MM-DD')}
&to=${dayjs().format('YYYY-MM-DD')}
`,
FetchResultTypes.JSON,
);

export const isMenuIncomplete = (menu: APIMenuModel) =>
!menu.mainCourse || menu.mainCourse.length === 0 || !menu.mainCourse[0];
export const isMenuIncomplete = (menu: ApiMenu) =>
!menu.main || menu.main.length === 0 || !menu.main[0];

export const addMenusToFields = (
embed: EmbedBuilder,
menus: APIMenuModel[],
) => {
export const addMenusToFields = (embed: EmbedBuilder, menus: ApiMenu[]) => {
let counter = 0;
Object.values(menus).forEach((m) => {
menus.forEach((m) => {
if (isMenuIncomplete(m)) {
return;
}
Expand All @@ -40,69 +44,54 @@ export const addMenusToFields = (
embed.addFields({
name: title,
value: fieldValueOrEmpty(stripIndent`
${m.starter}
${m.mainCourse.join('\n')}
${m.dessert}
`),
${m.starter}
${m.main.join('\n')}
${m.dessert}
`),
inline: true,
});
});
};

export const buildWeekMenuEmbed = (menu: APIWeekMenuModel): EmbedBuilder => {
export const buildWeekMenuEmbed = (menu: ApiMenu[]): EmbedBuilder => {
const embed = new EmbedBuilder()
.setColor('#EA580C')
.setTitle(`:fork_and_knife: Menus de la semaine ${menu.week}`)
.setTitle(`:fork_and_knife: Menus de la semaine ${dayjs().week()}`)
.setFooter({
text: oneLine`
Semaine
du ${dayjs(menu.monday).format(DAY_FORMAT)}
au ${dayjs(menu.friday).format(DAY_FORMAT)}
du ${dayjs(menu[0]?.date).format(DAY_FORMAT)}
au ${dayjs(menu[menu.length]?.date).format(DAY_FORMAT)}
`,
});

Object.values(menu.days).forEach((dayMenu: APIDayMenuModel) => {
Object.entries(groupBy(menu, (m) => m.date)).forEach(([date, menus]) => {
embed.addFields({
name: '-'.repeat(80),
value: oneLineTrim`
**${capitalize(dayjs(dayMenu.day).format('dddd'))}**
`,
**${capitalize(dayjs(date).format('dddd'))}**
`,
inline: false,
});
addMenusToFields(embed, dayMenu.menus);
addMenusToFields(embed, menus);
});

return embed;
};

export const buildDayMenuEmbed = (menu: APIDayMenuModel): EmbedBuilder => {
export const buildDayMenuEmbed = (menu: ApiMenu[]): EmbedBuilder => {
const embed = new EmbedBuilder().setColor('#EA580C').setTitle(
oneLine`:fork_and_knife: Menus du
${dayjs(menu.day).format('dddd LL')}`,
${dayjs(menu[0]?.date).format('dddd LL')}`,
);
addMenusToFields(embed, menu.menus);
addMenusToFields(embed, menu);
return embed;
};

export interface APIWeekMenuModel {
export interface ApiMenu {
_id: string;
week: number;
year: number;
monday: string;
friday: string;
lastSave: string;
lastPublish: string;
days: APIDayMenuModel[];
}

export interface APIDayMenuModel {
day: string;
menus: APIMenuModel[];
}

export interface APIMenuModel {
date: string;
starter: string;
mainCourse: string[];
main: string[];
dessert: string;
containsPork: boolean;
}
14 changes: 14 additions & 0 deletions src/utils/array-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,17 @@ export function shuffleArray(array: unknown[]) {
[array[i], array[j]] = [array[j], array[i]];
}
}

export function groupBy<T, K extends string>(arr: T[], key: (item: T) => K) {
return arr.reduce(
(acc, curr) => {
const group = key(curr);
if (!acc[group]) {
acc[group] = [];
}
acc[group].push(curr);
return acc;
},
{} as Record<K, T[]>,
);
}
7 changes: 4 additions & 3 deletions src/utils/dayjs-parser.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import * as parser from 'any-date-parser';
import 'any-date-parser';
import type { PluginFunc } from 'dayjs';
import dayjs from 'dayjs';

const plugin: PluginFunc<unknown> = (_option: unknown, dayjsClass) => {
const defParse = dayjsClass.prototype.parse;
dayjs.prototype.parse = function parse(config: { date: unknown }) {
const fromString = parser.exportAsFunction(this.$locale().name);
if (typeof config.date === 'string') {
const parsed = fromString(config.date);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const parsed = Date.fromString(config.date, this.$locale().name);
if (parsed instanceof Date) {
// eslint-disable-next-line no-param-reassign
config.date = parsed;
Expand Down
3 changes: 3 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
"baseUrl": "./src",
"rootDir": "src",
"outDir": "dist",
"lib": [
"ESNext"
],
"noUncheckedIndexedAccess": true,
"skipLibCheck": true,
"tsBuildInfoFile": "dist/.tsbuildinfo"
Expand Down

0 comments on commit ef253b5

Please sign in to comment.