Revert "Merge pull request 'Complete Housekeeping migration and /ase cutover' (#52) from codex/housekeeping-complete into main"
CI / check (push) Successful in 27s
CI / release (push) Skipped
CI / deploy (push) Successful in 43s

This reverts commit 488b6e57c4, reversing
changes made to b506b4499a.
This commit is contained in:
Simo committed 2026-08-30 21:31:34 +02:00
1 parent 488b6e57c4
commit b1ddda66ff
802 files changed
+61370 -76659

No files matched your search

+226 -151
View File
@@ -1,100 +1,40 @@
"use server";
import { and, eq } from "drizzle-orm";
import {
createPeopleMutationInvocation,
peopleMutationService,
} from "@/features/housekeeping/domains/people/services/mutations";
import { createCorrelationId } from "@/features/housekeeping/foundation/contracts";
import { and, eq, inArray, max, sql } from "drizzle-orm";
import { requirePermission } from "@/lib/admin/guard";
import { db, User, UsersCurrency } from "@/lib/db";
import {
Ban,
db,
Sanctions,
User,
UsersBadges,
UsersCurrency,
UsersSettings,
} from "@/lib/db";
import { PERMS } from "@/lib/permissions";
import type { ActionResult } from "@/lib/safe-action-shared";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
async function executeLegacy(
staff: {
readonly id: number;
readonly username: string;
readonly rank: number;
},
operation:
| "users.bulk-ban"
| "users.bulk-unban"
| "users.bulk-currency"
| "users.bulk-badge"
| "user.trade-lock",
input: unknown,
) {
return peopleMutationService.execute(
createPeopleMutationInvocation(staff, createCorrelationId()),
operation,
input,
);
}
function numberValue(value: unknown): number {
return Number.isSafeInteger(Number(value)) ? Number(value) : 0;
}
function failedIds(value: unknown): Array<{ userId: number; reason: string }> {
return Array.isArray(value)
? value.flatMap((item) =>
typeof item === "object" && item !== null
? [
{
userId: numberValue(Reflect.get(item, "userId")),
reason: String(Reflect.get(item, "reason") ?? "Database error"),
},
]
: [],
)
: [];
}
function legacyBulkOutcome(
after: Readonly<Record<string, unknown>> | null,
userIds: readonly number[],
): {
readonly completed: number;
readonly total: number;
readonly failedIds: Array<{ userId: number; reason: string }>;
} {
const databaseFailures = failedIds(after?.failedIds);
const externalSyncFailures = failedIds(after?.externalSyncFailures).map(
({ userId }) => ({ userId, reason: "Database error" }),
);
const pendingFailures = [...databaseFailures, ...externalSyncFailures];
const orderedFailures = userIds.flatMap((userId) => {
const index = pendingFailures.findIndex(
(failure) => failure.userId === userId,
);
return index === -1 ? [] : pendingFailures.splice(index, 1);
});
return {
completed: Math.max(
0,
numberValue(after?.completed) - externalSyncFailures.length,
),
total: numberValue(after?.total),
failedIds: [...orderedFailures, ...pendingFailures],
};
}
export async function bulkUnban({
userIds,
}: {
userIds: number[];
}): Promise<ActionResult<{ unbanned: number; total: number }>> {
const staff = await requirePermission(PERMS.USERS_EDIT);
const result = await executeLegacy(staff, "users.bulk-unban", { userIds });
if (!result.ok) return { ok: false, error: "Bulk unban failed" };
const result = await db.delete(Ban).where(inArray(Ban.userId, userIds));
const unbanned = Number(
(result as unknown as [{ affectedRows: number }])[0]?.affectedRows ?? 0,
);
await logStaffActivity({
staffId: staff.id,
action: "bulk_unban",
description: `Unbanned ${unbanned} user(s)`,
targetType: "user",
});
return {
ok: true,
data: {
unbanned: numberValue(result.data.after?.completed),
total: numberValue(result.data.after?.total),
},
ok: true as const,
data: { unbanned, total: userIds.length },
};
}
@@ -108,16 +48,34 @@ export async function bulkBan({
duration: number;
}): Promise<ActionResult<{ banned: number }>> {
const staff = await requirePermission(PERMS.USERS_EDIT);
const result = await executeLegacy(staff, "users.bulk-ban", {
userIds,
reason,
duration,
const now = Math.floor(Date.now() / 1000);
let banned = 0;
for (const userId of userIds) {
try {
await db.insert(Ban).values({
userId,
ip: "",
machineId: "",
userStaffId: staff.id,
timestamp: now,
banExpire: duration > 0 ? now + duration : 0,
banReason: reason,
type: "account",
});
banned++;
} catch {
// skip duplicates
}
}
await logStaffActivity({
staffId: staff.id,
action: "bulk_ban",
description: `Banned ${banned} user(s)`,
targetType: "user",
});
if (!result.ok) return { ok: false, error: "Bulk ban failed" };
return {
ok: true,
data: { banned: numberValue(result.data.after?.completed) },
};
return { ok: true as const, data: { banned } };
}
export async function bulkGiveCurrency({
@@ -136,20 +94,49 @@ export async function bulkGiveCurrency({
}>
> {
const staff = await requirePermission(PERMS.USERS_EDIT);
const result = await executeLegacy(staff, "users.bulk-currency", {
userIds,
amount,
type,
let given = 0;
const failedIds: Array<{ userId: number; reason: string }> = [];
for (const userId of userIds) {
try {
if (type === "credits") {
await db
.update(User)
.set({ credits: sql`${User.credits} + ${amount}` })
.where(eq(User.id, userId));
await rcon.giveCredits(userId, amount);
} else if (type === "pixels") {
await db
.insert(UsersCurrency)
.values({ userId, type: 0, amount })
.onDuplicateKeyUpdate({
set: { amount: sql`${UsersCurrency.amount} + ${amount}` },
});
await rcon.giveDuckets(userId, amount);
} else if (type === "points") {
await db
.insert(UsersCurrency)
.values({ userId, type: 101, amount })
.onDuplicateKeyUpdate({
set: { amount: sql`${UsersCurrency.amount} + ${amount}` },
});
await rcon.givePointsGotw(userId, amount);
}
given++;
} catch {
failedIds.push({ userId, reason: "Database error" });
}
}
await logStaffActivity({
staffId: staff.id,
action: "bulk_give_currency",
description: `Gave ${amount} ${type} to ${given} user(s)`,
targetType: "user",
});
if (!result.ok) return { ok: false, error: "Bulk currency failed" };
const outcome = legacyBulkOutcome(result.data.after, userIds);
return {
ok: true,
data: {
given: outcome.completed,
total: outcome.total,
failedIds: outcome.failedIds,
},
ok: true as const,
data: { given, total: userIds.length, failedIds },
};
}
@@ -167,19 +154,45 @@ export async function bulkGiveBadge({
}>
> {
const staff = await requirePermission(PERMS.USERS_EDIT);
const result = await executeLegacy(staff, "users.bulk-badge", {
userIds,
badgeCode,
let given = 0;
const failedIds: Array<{ userId: number; reason: string }> = [];
for (const userId of userIds) {
try {
const [existing] = await db
.select({ id: UsersBadges.id })
.from(UsersBadges)
.where(
and(
eq(UsersBadges.userId, userId),
eq(UsersBadges.badgeCode, badgeCode),
),
)
.limit(1);
if (!existing) {
const [agg] = await db
.select({ maxSlot: max(UsersBadges.slotId) })
.from(UsersBadges)
.where(eq(UsersBadges.userId, userId));
const slotId = (agg?.maxSlot ?? 0) + 1;
await db.insert(UsersBadges).values({ userId, slotId, badgeCode });
await rcon.giveBadge(userId, badgeCode);
}
given++;
} catch {
failedIds.push({ userId, reason: "Database error" });
}
}
await logStaffActivity({
staffId: staff.id,
action: "bulk_give_badge",
description: `Gave badge "${badgeCode}" to ${given} user(s)`,
targetType: "user",
});
if (!result.ok) return { ok: false, error: "Bulk badge failed" };
const outcome = legacyBulkOutcome(result.data.after, userIds);
return {
ok: true,
data: {
given: outcome.completed,
total: outcome.total,
failedIds: outcome.failedIds,
},
ok: true as const,
data: { given, total: userIds.length, failedIds },
};
}
@@ -189,6 +202,7 @@ export async function bulkAdjustCurrency({
type,
}: {
userIds: number[];
/** Positive = give, negative = take. Balances clamped at 0. */
amount: number;
type: "credits" | "pixels" | "points";
}): Promise<
@@ -200,29 +214,29 @@ export async function bulkAdjustCurrency({
> {
const staff = await requirePermission(PERMS.USERS_EDIT);
if (!Number.isFinite(amount) || amount === 0) {
return { ok: false, error: "Amount must be a non-zero number" };
return { ok: false as const, error: "Amount must be a non-zero number" };
}
if (amount > 0) {
const result = await executeLegacy(staff, "users.bulk-currency", {
userIds,
amount,
type,
});
if (!result.ok) return { ok: false, error: "Currency adjustment failed" };
const outcome = legacyBulkOutcome(result.data.after, userIds);
const given = await bulkGiveCurrency({ userIds, amount, type });
if (!given.ok) return given;
if (!given.data) {
return { ok: false as const, error: "Currency adjustment failed" };
}
return {
ok: true,
ok: true as const,
data: {
adjusted: outcome.completed,
total: outcome.total,
failedIds: outcome.failedIds,
adjusted: given.data.given,
total: given.data.total,
failedIds: given.data.failedIds,
},
};
}
const take = Math.abs(Math.trunc(amount));
let adjusted = 0;
const failures: Array<{ userId: number; reason: string }> = [];
const failedIds: Array<{ userId: number; reason: string }> = [];
for (const userId of userIds) {
try {
if (type === "credits") {
@@ -232,13 +246,11 @@ export async function bulkAdjustCurrency({
.where(eq(User.id, userId))
.limit(1);
if (!user) {
failures.push({ userId, reason: "Not found" });
failedIds.push({ userId, reason: "Not found" });
continue;
}
await db
.update(User)
.set({ credits: Math.max(0, user.credits - take) })
.where(eq(User.id, userId));
const next = Math.max(0, user.credits - take);
await db.update(User).set({ credits: next }).where(eq(User.id, userId));
} else {
const currencyType = type === "pixels" ? 0 : 101;
const [row] = await db
@@ -251,17 +263,19 @@ export async function bulkAdjustCurrency({
),
)
.limit(1);
const next = Math.max(0, (row?.amount ?? 0) - take);
const current = row?.amount ?? 0;
const next = Math.max(0, current - take);
await db
.insert(UsersCurrency)
.values({ userId, type: currencyType, amount: next })
.onDuplicateKeyUpdate({ set: { amount: next } });
}
adjusted += 1;
adjusted++;
} catch {
failures.push({ userId, reason: "Database error" });
failedIds.push({ userId, reason: "Database error" });
}
}
await logStaffActivity({
staffId: staff.id,
action: "bulk_adjust_currency",
@@ -269,32 +283,93 @@ export async function bulkAdjustCurrency({
targetType: "user",
});
return {
ok: true,
data: { adjusted, total: userIds.length, failedIds: failures },
ok: true as const,
data: { adjusted, total: userIds.length, failedIds },
};
}
/**
* Persist trade lock on `sanctions.trade_locked_until` + `users_settings.can_trade`
* via Drizzle, then best-effort RCON sync (settradelock + alert + disconnect if online).
*/
export async function setTradeLock({
userId,
untilUnix,
}: {
userId: number;
/** Unix seconds; 0 clears the lock. */
untilUnix: number;
}): Promise<ActionResult<{ userId: number; untilUnix: number }>> {
const staff = await requirePermission(PERMS.USERS_EDIT);
const until = Math.max(0, Math.trunc(untilUnix));
const result = await executeLegacy(staff, "user.trade-lock", {
userId,
untilUnix: until,
});
if (!result.ok) {
return {
ok: false,
error:
result.error.code === "NOT_FOUND"
? "User not found"
: "Trade lock update failed",
};
const locked = until > 0;
const [user] = await db
.select({
id: User.id,
username: User.username,
online: User.online,
})
.from(User)
.where(eq(User.id, userId))
.limit(1);
if (!user) {
return { ok: false as const, error: "User not found" };
}
return { ok: true, data: { userId, untilUnix: until } };
await db.transaction(async (tx) => {
const [existing] = await tx
.select({ id: Sanctions.id })
.from(Sanctions)
.where(eq(Sanctions.habboId, userId))
.limit(1);
if (existing) {
await tx
.update(Sanctions)
.set({
tradeLockedUntil: until,
...(locked ? { reason: "Trade lock (CMS)" } : {}),
})
.where(eq(Sanctions.id, existing.id));
} else {
await tx.insert(Sanctions).values({
habboId: userId,
tradeLockedUntil: until,
reason: locked ? "Trade lock (CMS)" : "",
});
}
await tx
.update(UsersSettings)
.set({
canTrade: locked ? "0" : "1",
...(locked
? { tradelockAmount: sql`${UsersSettings.tradelockAmount} + 1` }
: {}),
})
.where(eq(UsersSettings.userId, userId));
});
await rcon.setTradeLock(userId, locked);
await rcon.alertUser(
userId,
locked
? "Trading has been disabled by staff."
: "Trading has been re-enabled by staff.",
);
if (user.online === "1") {
await rcon.disconnectUser(userId, user.username);
}
await logStaffActivity({
staffId: staff.id,
action: locked ? "trade_lock" : "trade_unlock",
description: locked
? `Trade-locked ${user.username} (#${userId}) until ${until}`
: `Cleared trade lock for ${user.username} (#${userId})`,
targetType: "user",
targetId: userId,
});
return { ok: true as const, data: { userId, untilUnix: until } };
}