Files

83 lines
3.0 KiB
TypeScript

import { enhance } from "@zenstackhq/runtime";
import { db } from "~/utils/db.server";
import { DrinkType, Manufacturer } from "@prisma/client";
import { ContainerWithSection, DrinkComposite } from "./types";
import { shuffleArray } from "~/utils/arrays";
export async function findIdFromSlug(slug:string | undefined) : Promise<number | undefined> {
if(slug){
const id = Number(slug);
if(id) return id;
const drink = await db.drink.findUnique({where: {slug: slug}, select: {id: true}});
return drink?.id;
}
return undefined;
}
export async function findManufacturersFromSearch(searchParams: URLSearchParams) : Promise<Manufacturer[]> {
const dbe = enhance(db);
var result : Manufacturer[] = [];
if(searchParams.has("drink")){
result = result.concat(await dbe.manufacturer.findMany({
orderBy: {drinks: {_count: "desc"}},
where: {drinks: { some: { type: { in: searchParams.getAll("drink").map((str) => {return DrinkType[str as keyof typeof DrinkType]})}}}}
}));
}
else {
result = result.concat(await dbe.manufacturer.findMany({
orderBy: {drinks: {_count: "desc"}},
where: {NOT: {drinks: {none: {}}}}
}));
}
return result;
}
export async function getMostCommonSection(containers : ContainerWithSection[]) : Promise<number> {
if(containers.length <= 0) return -1;
const container : ContainerWithSection = containers.reduce((previousValue: ContainerWithSection, currentValue: ContainerWithSection, currentIndex: number, array: ContainerWithSection[]) : ContainerWithSection => {
if(previousValue.inventory > currentValue.inventory) return previousValue;
return currentValue;
})
return container.section_id;
}
export async function findRecommendations(sectionId: number, numRecommendations: number, notId: number) : Promise<DrinkComposite[]> {
const dbe = enhance(db);
// Drinks with the same section
const drinksWithSameSection = await dbe.drink.findMany({include: {manufacturer: true, containers: true}, where: {id: {not: notId}, containers: {some: {section_id: sectionId}, every: {inventory: {gt: 0}}}}});
var result : DrinkComposite[] = [];
// Shuffle first recommendations array
shuffleArray(drinksWithSameSection);
var loopLength : number = Math.min(numRecommendations, drinksWithSameSection.length);
for(var i = 0; i < loopLength; i++){
result.push(drinksWithSameSection[i])
}
if(result.length < numRecommendations){
const completelyRandomDrinks = await dbe.drink.findMany({include: {manufacturer: true, containers: true}, where: {id: {not: notId}, containers: {every: {inventory: {gt: 0}}}}});
// Shuffle second recommendations array
shuffleArray(completelyRandomDrinks);
loopLength = Math.min(numRecommendations, completelyRandomDrinks.length) - result.length;
for(var i = 0; i < loopLength; i++){
result.push(completelyRandomDrinks[i])
}
}
return result;
}