Skip to content

Commit

Permalink
commit
Browse files Browse the repository at this point in the history
  • Loading branch information
gc committed Nov 9, 2024
1 parent 734c315 commit f2424c5
Show file tree
Hide file tree
Showing 12 changed files with 340 additions and 208 deletions.
11 changes: 11 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -1135,6 +1135,17 @@ model UserEvent {
@@map("user_event")
}

model DroppedClueScroll {
id String @id @default(uuid()) @db.Uuid
user_id String @db.Text
date_received DateTime @db.Timestamp(6)
used Boolean @default(false)
item_id Int
@@map("dropped_clue_scroll")
}

enum command_name_enum {
testpotato
achievementdiary
Expand Down
8 changes: 6 additions & 2 deletions src/lib/MUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { Gear, defaultGear } from './structures/Gear';
import { GearBank } from './structures/GearBank';
import type { XPBank } from './structures/XPBank';
import type { ItemBank, Skills } from './types';
import type { ActivityTaskOptions } from './types/minions';
import { addItemToBank, convertXPtoLVL, fullGearToBank, hasSkillReqsRaw, itemNameFromID } from './util';
import { determineRunes } from './util/determineRunes';
import { getKCByName } from './util/getKCByName';
Expand Down Expand Up @@ -340,21 +341,24 @@ GROUP BY data->>'ci';`);
collectionLog = false,
filterLoot = true,
dontAddToTempCL = false,
neverUpdateHistory = false
neverUpdateHistory = false,
tripOptions
}: {
items: ItemBank | Bank;
collectionLog?: boolean;
filterLoot?: boolean;
dontAddToTempCL?: boolean;
neverUpdateHistory?: boolean;
tripOptions?: ActivityTaskOptions;
}) {
const res = await transactItems({
collectionLog,
itemsToAdd: new Bank(items),
filterLoot,
dontAddToTempCL,
userID: this.id,
neverUpdateHistory
neverUpdateHistory,
tripOptions
});
this.user = res.newUser;
this.updateProperties();
Expand Down
16 changes: 0 additions & 16 deletions src/lib/clues/clueUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,6 @@ export function getClueScoresFromOpenables(openableScores: Bank) {
return openableScores.filter(item => Boolean(ClueTiers.find(ct => ct.id === item.id)));
}

/**
* Removes extra clue scrolls from loot, if they got more than 1 or if they already own 1.
*/
export function deduplicateClueScrolls({ loot, currentBank }: { loot: Bank; currentBank: Bank }) {
const newLoot = loot.clone();
for (const { scrollID } of ClueTiers) {
if (!newLoot.has(scrollID)) continue;
if (currentBank.has(scrollID)) {
newLoot.remove(scrollID, newLoot.amount(scrollID));
} else {
newLoot.set(scrollID, 1);
}
}
return newLoot;
}

export function buildClueButtons(loot: Bank | null, perkTier: number, user: MUser) {
const components: ButtonBuilder[] = [];
if (loot && perkTier > 1 && !user.bitfield.includes(BitField.DisableClueButtons)) {
Expand Down
3 changes: 3 additions & 0 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as dotenv from 'dotenv';
import { getItemOrThrow, resolveItems } from 'oldschooljs';
import { z } from 'zod';

import { Time } from 'e';
import { DISCORD_SETTINGS, production } from '../config';
import type { AbstractCommand } from '../mahoji/lib/inhibitors';
import { SkillsEnum } from './skilling/types';
Expand Down Expand Up @@ -582,3 +583,5 @@ if (!process.env.TEST && isMainThread) {
`Starting... Git[${gitHash}] ClientID[${globalConfig.clientID}] Production[${globalConfig.isProduction}]`
);
}

export const CLUE_DROP_DESPAWN_TIME = Time.Minute * 61;
15 changes: 13 additions & 2 deletions src/lib/structures/UpdateBank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { MUserClass } from '../MUser';
import { degradeChargeBank } from '../degradeableItems';
import type { GearSetup } from '../gear/types';
import type { ItemBank } from '../types';
import type { ActivityTaskOptions } from '../types/minions';
import { type JsonKeys, objHasAnyPropInCommon } from '../util';
import { ChargeBank, XPBank } from './Bank';
import { KCBank } from './KCBank';
Expand Down Expand Up @@ -54,7 +55,12 @@ export class UpdateBank {
this.userUpdates = mergeDeep(this.userUpdates, other.userUpdates);
}

async transact(user: MUser, { isInWilderness }: { isInWilderness?: boolean } = { isInWilderness: false }) {
async transact(
user: MUser,
{ isInWilderness, tripOptions }: { isInWilderness?: boolean; tripOptions?: ActivityTaskOptions } = {
isInWilderness: false
}
) {
// Check everything first
if (this.chargeBank.length() > 0) {
const charges = user.hasCharges(this.chargeBank);
Expand Down Expand Up @@ -86,7 +92,12 @@ export class UpdateBank {
}
let itemTransactionResult: Awaited<ReturnType<MUserClass['addItemsToBank']>> | null = null;
if (this.itemLootBank.length > 0) {
itemTransactionResult = await user.addItemsToBank({ items: this.itemLootBank, collectionLog: true });
itemTransactionResult = await user.addItemsToBank({
items: this.itemLootBank,
collectionLog: true,
tripOptions
});
results.push(...itemTransactionResult.messages);
}

// XP
Expand Down
9 changes: 9 additions & 0 deletions src/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -435,3 +435,12 @@ export function joinStrings(itemList: any[], end?: string) {
return itemList.join(', ');
}
}

export function fetchUsersDroppedClues() {
return prisma.droppedClueScroll.findMany({
select: {
user_id: true,
item_id: true
}
});
}
3 changes: 3 additions & 0 deletions src/lib/util/migrateUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ export async function migrateUser(_source: string | MUser, _dest: string | MUser
transactions.push(
prisma.reclaimableItem.updateMany({ where: { user_id: sourceUser.id }, data: { user_id: destUser.id } })
);
transactions.push(
prisma.droppedClueScroll.updateMany({ where: { user_id: sourceUser.id }, data: { user_id: destUser.id } })
);

transactions.push(
prisma.activity.updateMany({
Expand Down
12 changes: 11 additions & 1 deletion src/lib/util/smallUtils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { type CommandResponse, deepMerge, miniID, stripEmojis, toTitleCase } from '@oldschoolgg/toolkit/util';
import type { Prisma } from '@prisma/client';
import type { DroppedClueScroll, Prisma } from '@prisma/client';
import { AlignmentEnum, AsciiTable3 } from 'ascii-table3';
import { ButtonBuilder, ButtonStyle, type InteractionReplyOptions } from 'discord.js';
import { clamp, objectEntries } from 'e';
import { type ArrayItemsResolved, Bank, type ItemBank, Items, getItemOrThrow } from 'oldschooljs';
import { MersenneTwister19937, shuffle } from 'random-js';
import z from 'zod';

import { CLUE_DROP_DESPAWN_TIME } from '../constants';
import { skillEmoji } from '../data/emojis';
import type { UserFullGearSetup } from '../gear/types';
import type { Skills } from '../types';
Expand Down Expand Up @@ -255,3 +256,12 @@ export function isValidNickname(str?: string) {
stripEmojis(str).length === str.length
);
}

export function convertDroppedCluesToBank(droppedClues: Pick<DroppedClueScroll, 'item_id' | 'date_received'>[]) {
const bank = new Bank();
for (const clue of droppedClues) {
if (clue.date_received.getTime() < Date.now() - CLUE_DROP_DESPAWN_TIME) continue;
bank.add(clue.item_id, 1);
}
return bank;
}
61 changes: 57 additions & 4 deletions src/lib/util/transactItemsFromBank.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,60 @@
import type { Prisma } from '@prisma/client';
import { Bank } from 'oldschooljs';

import { randomInteger } from 'remeda';
import { findBingosWithUserParticipating } from '../../mahoji/lib/bingo/BingoManager';
import { mahojiUserSettingsUpdate } from '../MUser';
import { deduplicateClueScrolls } from '../clues/clueUtils';
import { ClueTiers } from '../clues/clueTiers';
import { handleNewCLItems } from '../handleNewCLItems';
import { filterLootReplace } from '../slayer/slayerUtil';
import type { ItemBank } from '../types';
import type { ActivityTaskOptions } from '../types/minions';
import { logError } from './logError';
import { userQueueFn } from './userQueues';

async function deduplicateClueScrolls({
userID,
loot,
currentBank,
tripOptions
}: { userID: string; loot: Bank; currentBank: Bank; tripOptions: ActivityTaskOptions | undefined }): Promise<{
newLoot: Bank;
droppedClues: Prisma.DroppedClueScrollCreateInput[];
}> {
const droppedClues: Prisma.DroppedClueScrollCreateInput[] = [];
const newLoot = loot.clone();
for (const { scrollID } of ClueTiers) {
if (!newLoot.has(scrollID)) continue;
const amountOwned = currentBank.amount(scrollID);
const amountInLoot = newLoot.amount(scrollID);

newLoot.set(scrollID, amountOwned > 0 ? 0 : 1);

const leftOvers = amountInLoot - amountOwned;
if (tripOptions) {
for (let i = 0; i < leftOvers; i++) {
const dateReceived = new Date(
randomInteger(tripOptions.finishDate - tripOptions.duration, tripOptions.finishDate)
);
droppedClues.push({
user_id: userID,
item_id: scrollID,
date_received: dateReceived
});
}
}
}
if (droppedClues.length > 0) {
await prisma.droppedClueScroll.createMany({
data: droppedClues
});
}
return {
newLoot,
droppedClues
};
}

export interface TransactItemsArgs {
userID: string;
itemsToAdd?: Bank;
Expand All @@ -19,6 +64,7 @@ export interface TransactItemsArgs {
dontAddToTempCL?: boolean;
neverUpdateHistory?: boolean;
otherUpdates?: Prisma.UserUpdateArgs['data'];
tripOptions?: ActivityTaskOptions;
}

declare global {
Expand All @@ -31,13 +77,15 @@ async function transactItemsFromBank({
collectionLog = false,
filterLoot = true,
dontAddToTempCL = false,
tripOptions,
...options
}: TransactItemsArgs) {
let itemsToAdd = options.itemsToAdd ? options.itemsToAdd.clone() : undefined;
const itemsToRemove = options.itemsToRemove ? options.itemsToRemove.clone() : undefined;

return userQueueFn(userID, async function transactItemsInner() {
const settings = await mUserFetch(userID);
const messages: string[] = [];

const gpToRemove = (itemsToRemove?.amount('Coins') ?? 0) - (itemsToAdd?.amount('Coins') ?? 0);
if (itemsToRemove && settings.GP < gpToRemove) {
Expand All @@ -58,10 +106,14 @@ async function transactItemsFromBank({

let clUpdates: Prisma.UserUpdateArgs['data'] = {};
if (itemsToAdd) {
itemsToAdd = deduplicateClueScrolls({
const dedupeResult = await deduplicateClueScrolls({
loot: itemsToAdd.clone(),
currentBank: currentBank.clone().remove(itemsToRemove ?? {})
currentBank: currentBank.clone().remove(itemsToRemove ?? {}),
userID,
tripOptions
});
itemsToAdd = dedupeResult.newLoot;
messages.push(`Dropped ${dedupeResult.droppedClues.length} clue scrolls`);
const { bankLoot, clLoot } = filterLoot
? filterLootReplace(settings.allItemsOwned, itemsToAdd)
: { bankLoot: itemsToAdd, clLoot: itemsToAdd };
Expand Down Expand Up @@ -151,7 +203,8 @@ async function transactItemsFromBank({
itemsRemoved: itemsToRemove,
newBank: new Bank(newUser.bank as ItemBank),
newCL,
newUser
newUser,
messages
};
});
}
Loading

0 comments on commit f2424c5

Please sign in to comment.