Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update score on items change #1266

Merged
merged 3 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions server/src/drizzle/methods/Item.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import { DbClient } from '../../db/client';
import { and, count, eq, like, sql } from 'drizzle-orm';
import { type InsertItem, item as ItemTable } from '../../db/schema';
import { type InsertItem, itemPacks, item as ItemTable } from '../../db/schema';
import { scorePackService } from '../../services/pack/scorePackService';
import { ItemPacks } from './ItemPacks';

export class Item {
async create(data: InsertItem) {
async create(data: InsertItem, packId?: string) {
try {
const item = await DbClient.instance
.insert(ItemTable)
.values(data)
.returning()
.get();

if (packId) {
const itemPacksClass = new ItemPacks();
await itemPacksClass.create({ itemId: item.id, packId });
await this.updateScoreIfNeeded(packId);
}

return item;
} catch (error) {
throw new Error(`Failed to create item: ${error.message}`);
Expand Down Expand Up @@ -45,19 +54,32 @@ export class Item {
.where(filter)
.returning()
.get();
const packIds = await DbClient.instance
.select()
.from(itemPacks)
.where(eq(itemPacks.itemId, item.id))
.all();

for (const { packId } of packIds) {
await this.updateScoreIfNeeded(packId);
}

return item;
} catch (error) {
throw new Error(`Failed to update item: ${error.message}`);
}
}

async delete(id: string, filter = eq(ItemTable.id, id)) {
async delete(id: string, filter = eq(ItemTable.id, id), packId?: string) {
try {
const deletedItem = await DbClient.instance
.delete(ItemTable)
.where(filter)
.returning()
.get();

await this.updateScoreIfNeeded(packId);

return deletedItem;
} catch (error) {
throw new Error(`Failed to delete item: ${error.message}`);
Expand Down Expand Up @@ -171,4 +193,10 @@ export class Item {
throw new Error(`Failed to find count of items: ${error.message}`);
}
}

async updateScoreIfNeeded(packId?: string) {
if (!packId) return;

await scorePackService(packId);
}
}
15 changes: 9 additions & 6 deletions server/src/services/item/addGlobalItemToPackService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { Item } from '../../drizzle/methods/Item';
import { ItemPacks } from '../../drizzle/methods/ItemPacks';
import { ItemOwners } from '../../drizzle/methods/ItemOwners';
import { scorePackService } from '../pack/scorePackService';

/**
* Adds a global item to the pack service.
Expand All @@ -27,12 +28,14 @@ export const addGlobalItemToPackService = async (
throw new Error('Global Item does not exist!');
}
const { id, ...duplicatedItemValues } = item;
const newItem = await itemClass.create({
...duplicatedItemValues,
global: false,
ownerId,
});
await itemPacksClass.create({ itemId: newItem.id, packId });
const newItem = await itemClass.create(
{
...duplicatedItemValues,
global: false,
ownerId,
},
packId,
);

return newItem;
};
24 changes: 12 additions & 12 deletions server/src/services/item/addItemService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// import { prisma } from '../../prisma';
import { Item } from '../../drizzle/methods/Item';
import { ItemPacks } from '../../drizzle/methods/ItemPacks';
import { ItemCategory } from '../../drizzle/methods/itemcategory';
import { ItemOwners } from '../../drizzle/methods/ItemOwners';
import { ItemCategory as categories } from '../../utils/itemCategory';
Expand Down Expand Up @@ -35,24 +34,25 @@ export const addItemService = async (
}
const itemCategoryClass = new ItemCategory();
const itemClass = new Item();
const itemPacksClass = new ItemPacks();
const itemOwnersClass = new ItemOwners();
category = (await itemCategoryClass.findItemCategory({ name: type })) || null;
if (!category) {
category = await itemCategoryClass.create({ name: type });
}
const item = await itemClass.create({
name,
weight,
quantity,
unit,
// packs: [packId],
categoryId: category.id,
ownerId,
});
const item = await itemClass.create(
{
name,
weight,
quantity,
unit,
// packs: [packId],
categoryId: category.id,
ownerId,
},
packId,
);

// await Pack.updateOne({ _id: packId }, { $addToSet: { items: newItem._id } });
await itemPacksClass.create({ itemId: item.id, packId });
await itemOwnersClass.create({ itemId: item.id, ownerId });
// const pack = await packClass.update(
// {
Expand Down
2 changes: 1 addition & 1 deletion server/src/services/item/deleteItemService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const deleteItemService = async (
const itemClass = new Item();
const ItemPacksClass = new ItemPacks();

await itemClass.delete(itemId);
await itemClass.delete(itemId, undefined, packId);
if (packId) {
await ItemPacksClass.delete(itemId, packId);
}
Expand Down
4 changes: 2 additions & 2 deletions server/src/services/pack/scorePackService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ export async function scorePackService(packId: string) {

const updatedPack = await packClass.update({
id: pack.id,
scores: packScore.scores,
grades: packScore.grades,
scores: packScore?.scores || null,
grades: packScore?.grades || null,
});

return updatedPack;
Expand Down
5 changes: 5 additions & 0 deletions server/src/utils/scorePack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ export function calculatePackScore(packData: any) {
// console.log("weight: ", weight);
// console.log('items: ', items)

if (!itemDocuments || itemDocuments.length === 0) {
return null;
}

const totalWeight = itemDocuments.reduce((total: number, item: any) => {
if (item.unit === 'lb') {
return total + item.weight * 16 * item.quantity; // Considering 1 lb equals 16 oz
Expand Down Expand Up @@ -159,6 +163,7 @@ export function calculatePackScore(packData: any) {
redundancyAndVersatility: redundancyAndVersatilityGrade,
}),
scores: JSON.stringify({
totalScore,
weightScore,
essentialItemsScore,
redundancyAndVersatilityScore,
Expand Down
Loading