enh
This commit is contained in:
parent
c9e6095cc1
commit
1bc511abe5
4 changed files with 93 additions and 31 deletions
|
|
@ -4370,3 +4370,54 @@ user-ui
|
|||
is retried WITHOUT it — so token registration still works on a DB where the region column
|
||||
is not migrated yet. Same for the unauthenticated branch.
|
||||
No dependency added. No migration run. No tests run.
|
||||
|
||||
2026-10-14 22:38:15 Scratch SQL at repo root: 0006_phase5_user_regions.sql (NEW).
|
||||
The additive-only part of migration 0006 (Phase 5) so it can be applied to a DB where the
|
||||
rest of 0006 already ran, without re-running the whole file:
|
||||
- CREATE TABLE IF NOT EXISTS user_regions + unique index
|
||||
- ALTER TABLE notif_creds / unlogged_user_tokens ADD COLUMN region_id (nullable)
|
||||
- backfill INSERT OR IGNORE ... SELECT DISTINCT user_id, region_id FROM addresses
|
||||
Temporary helper for the manual `wrangler d1 execute --file=...` run; delete after applying.
|
||||
One-shot (SQLite has no ADD COLUMN IF NOT EXISTS). Dry-run applied to a copy of the dev DB:
|
||||
created the table, 757 rows backfilled, both columns + index present. No migration run.
|
||||
|
||||
2026-10-14 22:39:32 Delete the scratch SQL at the repo root (0006_phase5_user_regions.sql).
|
||||
The user applied the change, so the helper file is no longer needed. The SQL itself stays in
|
||||
packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (Phase 5) for other
|
||||
environments. Dev DB verified after the apply: user_regions (757 rows), notif_creds.region_id
|
||||
and unlogged_user_tokens.region_id present. No dependency added. No migration run by me.
|
||||
|
||||
2026-10-15 17:03:10 Fix admin.coupon.getUsersMiniInfo (500): the orders subquery was rewritten to the
|
||||
users table.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/coupon.ts (getUsersForCoupon)
|
||||
- The raw `where` fragment interpolated ANOTHER table's columns
|
||||
(`${orders.userId}` / `${orders.regionId}`) and was handed to the RELATIONAL builder
|
||||
(db.query.users.findMany). The relational builder re-points every column reference in a
|
||||
raw fragment at the aliased main table, so the subquery came out as
|
||||
`EXISTS (SELECT 1 FROM "orders" WHERE "users"."user_id" = "users"."id" AND
|
||||
"users"."region_id" = ?)` — users has neither column -> "Failed query" 500.
|
||||
- Switched to a plain `.select().from(users)` (same shape as the sibling
|
||||
getAllUsersWithFilters / searchUsers in admin-apis/user.ts, which render the subquery
|
||||
correctly). Behaviour is unchanged: users who have an order in the region, optional
|
||||
name/mobile search, ordered by name, same limit/offset.
|
||||
No dependency added. No migration run. No tests run.
|
||||
|
||||
2026-10-15 17:18:51 Fix push-token upserts colliding on the token unique index (500 on
|
||||
admin.staffUser.savePushToken; same latent bug in user.user.savePushToken).
|
||||
|
||||
A push token identifies a DEVICE and both staff_notif_creds.token and notif_creds.token are
|
||||
UNIQUE — but both upserts looked the row up by (owner, token). Re-registering the same device
|
||||
under a different account (log out / log in as someone else) missed the existing row, so the
|
||||
INSERT hit "UNIQUE constraint failed: <table>.token".
|
||||
Live evidence: token ExponentPushToken[VcoSOK...] already had a row for staff 7; a login as
|
||||
staff 10 tried to insert a second row for the same token.
|
||||
|
||||
packages/db_helper_sqlite/src/admin-apis/staff-user.ts
|
||||
- upsertStaffNotifCred: look up by TOKEN; when the row exists, UPDATE staff_user_id (the
|
||||
device now belongs to the newly logged-in staff) + last_verified instead of inserting.
|
||||
packages/db_helper_sqlite/src/user-apis/user.ts
|
||||
- upsertNotifCred: same token-keyed lookup (getNotifCred -> getNotifCredByToken); the update
|
||||
also reassigns user_id, keeping the "does not erase a known region" rule.
|
||||
One row per token, owned by whoever registered it last, so the previous account stops
|
||||
receiving on that device. No schema/migration change. No dependency added. No tests run.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { coupons, reservedCoupons, users, orders, orderStatus, couponApplicableUsers, couponApplicableProducts, productSkus } from '../db/schema'
|
||||
import { eq, and, like, or, inArray, lt, desc, asc, sql, SQL, isNull } from 'drizzle-orm'
|
||||
import { eq, and, like, or, inArray, lt, desc, asc, sql, isNull } from 'drizzle-orm'
|
||||
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
|
||||
|
||||
const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null): Promise<void> => {
|
||||
|
|
@ -444,28 +444,28 @@ export async function getUsersForCoupon(
|
|||
limit: number = 20,
|
||||
offset: number = 0
|
||||
): Promise<{ users: UserMiniInfo[] }> {
|
||||
let whereCondition: SQL<unknown> | undefined = sql`EXISTS (SELECT 1 FROM ${orders} WHERE ${orders.userId} = ${users.id} AND ${orders.regionId} = ${regionId})`
|
||||
if (search && search.trim()) {
|
||||
whereCondition = and(
|
||||
whereCondition,
|
||||
or(
|
||||
like(users.name, `%${search}%`),
|
||||
like(users.mobile, `%${search}%`)
|
||||
)
|
||||
)
|
||||
}
|
||||
// Plain select, NOT db.query.users: the relational builder re-points every
|
||||
// column reference inside a raw `where` fragment at the aliased main table,
|
||||
// which turned this subquery into `users.user_id` / `users.region_id` — neither
|
||||
// exists on users. A plain select renders the orders columns correctly.
|
||||
const inRegion = sql`EXISTS (SELECT 1 FROM ${orders} WHERE ${orders.userId} = ${users.id} AND ${orders.regionId} = ${regionId})`
|
||||
|
||||
const userList = await db.query.users.findMany({
|
||||
where: whereCondition,
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
mobile: true,
|
||||
},
|
||||
limit: limit,
|
||||
offset: offset,
|
||||
orderBy: asc(users.name),
|
||||
})
|
||||
const term = search?.trim()
|
||||
const whereCondition = term
|
||||
? and(inRegion, or(like(users.name, `%${term}%`), like(users.mobile, `%${term}%`)))
|
||||
: inRegion
|
||||
|
||||
const userList = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
mobile: users.mobile,
|
||||
})
|
||||
.from(users)
|
||||
.where(whereCondition)
|
||||
.orderBy(asc(users.name))
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
|
||||
return {
|
||||
users: userList.map((user) => ({
|
||||
|
|
|
|||
|
|
@ -119,10 +119,16 @@ export async function getStaffNotifCred(staffUserId: number, token: string) {
|
|||
}
|
||||
|
||||
export async function upsertStaffNotifCred(staffUserId: number, token: string): Promise<void> {
|
||||
const existing = await getStaffNotifCred(staffUserId, token)
|
||||
// `token` is UNIQUE (one row per device), so look the row up by token alone:
|
||||
// a device that logs in as a different staff member must move to that staff,
|
||||
// not insert a second row for the same token.
|
||||
const existing = await db.query.staffNotifCreds.findFirst({
|
||||
where: eq(staffNotifCreds.token, token),
|
||||
columns: { id: true },
|
||||
})
|
||||
if (existing) {
|
||||
await db.update(staffNotifCreds)
|
||||
.set({ lastVerified: new Date() })
|
||||
.set({ staffUserId, lastVerified: new Date() })
|
||||
.where(eq(staffNotifCreds.id, existing.id))
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { db } from '../db/db_index'
|
||||
import { notifCreds, unloggedUserTokens, userCreds, userDetails, users } from '../db/schema'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import { eq } from 'drizzle-orm'
|
||||
|
||||
export async function getUserById(userId: number) {
|
||||
const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1)
|
||||
|
|
@ -27,12 +27,15 @@ export async function getUserWithCreds(userId: number) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function getNotifCred(userId: number, token: string) {
|
||||
// Only the id is needed by the upsert below. Selecting just it keeps the
|
||||
// lookup working even if a newly added column (`region_id`) has not been
|
||||
// migrated yet, so a region failure can never stop a token from being saved.
|
||||
/**
|
||||
* The notif_creds row for a device token. `token` is UNIQUE (one row per
|
||||
* device), so the lookup is by token alone — a device that signs in as another
|
||||
* account must move to that account, not insert a second row.
|
||||
* Only the id is selected, so an unmigrated `region_id` cannot break the write.
|
||||
*/
|
||||
async function getNotifCredByToken(token: string) {
|
||||
return db.query.notifCreds.findFirst({
|
||||
where: and(eq(notifCreds.userId, userId), eq(notifCreds.token, token)),
|
||||
where: eq(notifCreds.token, token),
|
||||
columns: { id: true },
|
||||
})
|
||||
}
|
||||
|
|
@ -42,10 +45,12 @@ export async function upsertNotifCred(
|
|||
token: string,
|
||||
regionId: number | null = null
|
||||
): Promise<void> {
|
||||
const existing = await getNotifCred(userId, token)
|
||||
const existing = await getNotifCredByToken(token)
|
||||
if (existing) {
|
||||
await db.update(notifCreds)
|
||||
.set({
|
||||
// The device belongs to this account now.
|
||||
userId,
|
||||
lastVerified: new Date(),
|
||||
// A call that doesn't carry a region must not erase a known one.
|
||||
...(regionId != null ? { regionId } : {}),
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue