Files
recipe-app/backend/dist/meal-plan/meal-plan.service.js
T
Nils-Johan Gynther 969dafdbc6
Test Suite / test (24.15.0) (push) Has been cancelled
Refactor code structure for improved readability and maintainability
2026-05-06 07:37:59 +02:00

162 lines
6.3 KiB
JavaScript

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MealPlanService = void 0;
const common_1 = require("@nestjs/common");
const prisma_service_1 = require("../prisma/prisma.service");
const recipeSelect = {
id: true,
name: true,
imageUrl: true,
servings: true,
ingredients: {
select: {
quantity: true,
unit: true,
note: true,
product: { select: { id: true, name: true, canonicalName: true } },
},
},
};
let MealPlanService = class MealPlanService {
constructor(prisma) {
this.prisma = prisma;
}
async findByRange(userId, from, to) {
return this.prisma.mealPlanEntry.findMany({
where: {
userId,
date: { gte: new Date(from), lte: new Date(to) },
},
include: { recipe: { select: recipeSelect } },
orderBy: { date: 'asc' },
});
}
async upsert(userId, dto) {
const date = new Date(dto.date);
return this.prisma.mealPlanEntry.upsert({
where: {
userId_date: {
userId,
date,
},
},
create: {
userId,
date,
recipeId: dto.recipeId,
servings: dto.servings ?? null,
},
update: { recipeId: dto.recipeId, servings: dto.servings ?? null },
include: { recipe: { select: recipeSelect } },
});
}
async removeByDate(userId, date) {
const entry = await this.prisma.mealPlanEntry.findUnique({
where: {
userId_date: {
userId,
date: new Date(date),
},
},
});
if (!entry)
throw new common_1.NotFoundException('Ingen matplanspost för detta datum');
return this.prisma.mealPlanEntry.delete({ where: { id: entry.id } });
}
aggregateIngredients(entries) {
const map = new Map();
for (const entry of entries) {
const recipeServings = entry.recipe.servings;
const entryServings = entry.servings;
const scale = recipeServings && entryServings ? entryServings / recipeServings : 1;
for (const ing of entry.recipe.ingredients) {
if (!ing.product || !ing.unit) {
continue;
}
const key = `${ing.product.id}-${ing.unit}`;
const qty = Number(ing.quantity ?? 0) * scale;
const existing = map.get(key);
if (existing) {
existing.quantity += qty;
}
else {
map.set(key, {
productId: ing.product.id,
name: ing.product.canonicalName || ing.product.name,
quantity: qty,
unit: ing.unit,
});
}
}
}
return Array.from(map.values());
}
async shoppingList(userId, from, to) {
const entries = await this.findByRange(userId, from, to);
return this.aggregateIngredients(entries).sort((a, b) => a.name.localeCompare(b.name, 'sv'));
}
async inventoryCompare(userId, from, to) {
const entries = await this.findByRange(userId, from, to);
const pantryItems = await this.prisma.pantryItem.findMany({
where: { userId },
select: { productId: true },
});
const pantryProductIds = new Set(pantryItems.map((p) => p.productId));
const aggregated = this.aggregateIngredients(entries).map((item) => ({
productId: item.productId,
name: item.name,
required: item.quantity,
unit: item.unit,
}));
const result = await Promise.all(aggregated.map(async (item) => {
if (pantryProductIds.has(item.productId)) {
return {
productId: item.productId,
name: item.name,
required: item.required,
unit: item.unit,
available: item.required,
missing: 0,
status: 'pantry',
};
}
const inventoryItems = await this.prisma.inventoryItem.findMany({
where: { productId: item.productId },
});
const available = inventoryItems
.filter((i) => i.unit.trim().toLowerCase() === item.unit.trim().toLowerCase())
.reduce((sum, i) => sum + Number(i.quantity), 0);
return {
productId: item.productId,
name: item.name,
required: item.required,
unit: item.unit,
available,
missing: Math.max(0, item.required - available),
status: (available >= item.required ? 'enough' : 'missing'),
};
}));
const statusOrder = { missing: 0, enough: 1, pantry: 2 };
return result.sort((a, b) => {
const diff = statusOrder[a.status] - statusOrder[b.status];
if (diff !== 0)
return diff;
return a.name.localeCompare(b.name, 'sv');
});
}
};
exports.MealPlanService = MealPlanService;
exports.MealPlanService = MealPlanService = __decorate([
(0, common_1.Injectable)(),
__metadata("design:paramtypes", [prisma_service_1.PrismaService])
], MealPlanService);
//# sourceMappingURL=meal-plan.service.js.map