@stacksjs/defaults 0.75.489 → 0.75.490
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +20 -2
- package/ai/skills/stacks-native/CATALOG.md +9 -9
- package/ai/skills/stacks-search-engine/SKILL.md +14 -0
- package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
- package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
- package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
- package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
- package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
- package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
- package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
- package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
- package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
- package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
- package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
- package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
- package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
- package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
- package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
- package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
- package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
- package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
- package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
- package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
- package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
- package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
- package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
- package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
- package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
- package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
- package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
- package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
- package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
- package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
- package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
- package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
- package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
- package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
- package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
- package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
- package/app/Actions/Dashboard/Content/content-list.ts +10 -0
- package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
- package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
- package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
- package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
- package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
- package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
- package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
- package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
- package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
- package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
- package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
- package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
- package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
- package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +5 -3
- package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
- package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
- package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
- package/app/Actions/Dashboard/named-search.test.ts +36 -0
- package/app/Actions/Dashboard/named-search.ts +80 -0
- package/app/Models/Request.ts +4 -2
- package/functions/commerce/shippings/dashboard-resource.ts +12 -1
- package/functions/commerce/shippings/delivery-routes.ts +1 -0
- package/functions/commerce/shippings/license-keys.ts +1 -0
- package/functions/dashboard-list.test.ts +132 -1
- package/functions/dashboard-list.ts +198 -1
- package/functions/queue.ts +2 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +2 -2
- package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
- package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
- package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
- package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
- package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
- package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
- package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
- package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
- package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
- package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
- package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
- package/resources/components/Dashboard/Queue/QueueDashboard.stx +7 -1
- package/routes/dashboard-api.ts +11 -0
- package/views/dashboard/stores/kanban.ts +38 -6
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
|
|
3
|
+
import type { QueryReader } from '../Content/content-list'
|
|
4
|
+
import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
|
|
5
|
+
import { referencedIds } from './commerce-record'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
import { binder, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
|
|
8
|
+
import type { ReviewProductOption, ReviewRecord, ReviewSummary } from './review-records'
|
|
9
|
+
import { normalizeReviewCustomerContext, normalizeReviewProductOption, normalizeReviewRecord } from './review-records'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of reviews, searched, filtered, sorted and counted by the database,
|
|
13
|
+
* with the summary of every review (stacksjs/stacks#3218).
|
|
14
|
+
*
|
|
15
|
+
* The Reviews page used to read the newest 500 reviews and do all of that in
|
|
16
|
+
* the browser, so a review past the 500th could not be found or moderated,
|
|
17
|
+
* and the summary counted those 500. It also read the first 500 products and
|
|
18
|
+
* customers by name, so one review of any later product or by any later
|
|
19
|
+
* customer failed the whole page.
|
|
20
|
+
*/
|
|
21
|
+
export const REVIEW_SORTS = ['created', 'id', 'customer', 'product', 'rating', 'helpful', 'approved'] as const
|
|
22
|
+
export type ReviewSort = typeof REVIEW_SORTS[number]
|
|
23
|
+
|
|
24
|
+
export const REVIEW_RATINGS = ['1', '2', '3', '4', '5', 'none'] as const
|
|
25
|
+
export const REVIEW_MODERATION = ['approved', 'pending', 'featured', 'verified'] as const
|
|
26
|
+
|
|
27
|
+
export interface ReviewListQuery {
|
|
28
|
+
search: string
|
|
29
|
+
/** A product id, or '' for any. */
|
|
30
|
+
product: string
|
|
31
|
+
/** '' for any. */
|
|
32
|
+
rating: '' | typeof REVIEW_RATINGS[number]
|
|
33
|
+
/** '' for any. */
|
|
34
|
+
moderation: '' | typeof REVIEW_MODERATION[number]
|
|
35
|
+
sort: ReviewSort
|
|
36
|
+
direction: 'asc' | 'desc'
|
|
37
|
+
page: number
|
|
38
|
+
perPage: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function parseReviewListQuery(read: QueryReader): ReviewListQuery | { error: string } {
|
|
42
|
+
const pageText = queryText(read, 'page')
|
|
43
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
44
|
+
if (!Number.isInteger(page) || page < 1)
|
|
45
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
46
|
+
|
|
47
|
+
const sizeText = queryText(read, 'per_page')
|
|
48
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
49
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
50
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
51
|
+
|
|
52
|
+
const sort = queryText(read, 'sort') || 'created'
|
|
53
|
+
if (!(REVIEW_SORTS as readonly string[]).includes(sort))
|
|
54
|
+
return { error: `sort must be one of ${REVIEW_SORTS.join(', ')}.` }
|
|
55
|
+
|
|
56
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
57
|
+
const direction = directionText === '' ? (['created', 'rating', 'helpful'].includes(sort) ? 'desc' : 'asc') : directionText
|
|
58
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
59
|
+
return { error: 'direction must be asc or desc.' }
|
|
60
|
+
|
|
61
|
+
const search = queryText(read, 'q')
|
|
62
|
+
if (search.length > 200)
|
|
63
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
64
|
+
|
|
65
|
+
const product = queryText(read, 'product')
|
|
66
|
+
if (product && !/^\d+$/.test(product))
|
|
67
|
+
return { error: 'product must be a product id.' }
|
|
68
|
+
|
|
69
|
+
const rating = queryText(read, 'rating')
|
|
70
|
+
if (rating && !(REVIEW_RATINGS as readonly string[]).includes(rating))
|
|
71
|
+
return { error: `rating must be one of ${REVIEW_RATINGS.join(', ')}.` }
|
|
72
|
+
|
|
73
|
+
const moderation = queryText(read, 'moderation')
|
|
74
|
+
if (moderation && !(REVIEW_MODERATION as readonly string[]).includes(moderation))
|
|
75
|
+
return { error: `moderation must be one of ${REVIEW_MODERATION.join(', ')}.` }
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
search,
|
|
79
|
+
product,
|
|
80
|
+
rating: rating as ReviewListQuery['rating'],
|
|
81
|
+
moderation: moderation as ReviewListQuery['moderation'],
|
|
82
|
+
sort: sort as ReviewSort,
|
|
83
|
+
direction,
|
|
84
|
+
page,
|
|
85
|
+
perPage,
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const FROM = ' FROM reviews r LEFT JOIN products p ON p.id = r.product_id LEFT JOIN customers c ON c.id = r.customer_id'
|
|
90
|
+
|
|
91
|
+
function sortExpression(sort: ReviewSort, dialect: QueryBuilderDialect): string {
|
|
92
|
+
switch (sort) {
|
|
93
|
+
case 'id': return 'r.id'
|
|
94
|
+
case 'customer': return `LOWER(COALESCE(c.name, ''))`
|
|
95
|
+
case 'product': return `LOWER(COALESCE(p.name, ''))`
|
|
96
|
+
case 'rating': return 'r.rating'
|
|
97
|
+
case 'helpful': return 'r.helpful_votes'
|
|
98
|
+
case 'approved': return `CASE WHEN ${isTrue('r.is_approved', dialect)} THEN 1 ELSE 0 END`
|
|
99
|
+
default: return 'r.created_at'
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function reviewFilter(query: Pick<ReviewListQuery, 'search' | 'product' | 'rating' | 'moderation'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
104
|
+
const { bind, values } = binder(dialect)
|
|
105
|
+
const clauses: string[] = []
|
|
106
|
+
if (query.product)
|
|
107
|
+
clauses.push(`r.product_id = ${bind(Number(query.product))}`)
|
|
108
|
+
if (query.rating === 'none')
|
|
109
|
+
clauses.push('r.rating IS NULL')
|
|
110
|
+
else if (query.rating)
|
|
111
|
+
clauses.push(`r.rating = ${bind(Number(query.rating))}`)
|
|
112
|
+
if (query.moderation === 'approved')
|
|
113
|
+
clauses.push(isTrue('r.is_approved', dialect))
|
|
114
|
+
if (query.moderation === 'pending')
|
|
115
|
+
clauses.push(`NOT (${isTrue('r.is_approved', dialect)})`)
|
|
116
|
+
if (query.moderation === 'featured')
|
|
117
|
+
clauses.push(isTrue('r.is_featured', dialect))
|
|
118
|
+
if (query.moderation === 'verified')
|
|
119
|
+
clauses.push(isTrue('r.is_verified_purchase', dialect))
|
|
120
|
+
if (query.search) {
|
|
121
|
+
const pattern = containsPattern(query.search)
|
|
122
|
+
const columns = [
|
|
123
|
+
`COALESCE(c.name, '')`,
|
|
124
|
+
`COALESCE(c.email, '')`,
|
|
125
|
+
`COALESCE(p.name, '')`,
|
|
126
|
+
`COALESCE(r.title, '')`,
|
|
127
|
+
`COALESCE(r.content, '')`,
|
|
128
|
+
]
|
|
129
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
130
|
+
}
|
|
131
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function orderBy(query: Pick<ReviewListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
135
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
136
|
+
// Unrated reviews come last in both directions, as the page sorted them:
|
|
137
|
+
// each dialect would put NULL at a different end.
|
|
138
|
+
const unrated = query.sort === 'rating' ? 'CASE WHEN r.rating IS NULL THEN 1 ELSE 0 END ASC, ' : ''
|
|
139
|
+
// Ties read newest first, as the page broke them; the id breaks every
|
|
140
|
+
// remaining tie, so pages never repeat or skip a review.
|
|
141
|
+
if (query.sort === 'created' || query.sort === 'id')
|
|
142
|
+
return ` ORDER BY ${sortExpression(query.sort, dialect)} ${direction}, r.id ${direction}`
|
|
143
|
+
return ` ORDER BY ${unrated}${sortExpression(query.sort, dialect)} ${direction}, r.created_at DESC, r.id DESC`
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Reviews turned into records, against exactly the products and customers they reference. */
|
|
147
|
+
async function recordsFor(reviews: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ReviewRecord[]> {
|
|
148
|
+
if (reviews.length === 0)
|
|
149
|
+
return []
|
|
150
|
+
const productIds = referencedIds(reviews, 'product_id')
|
|
151
|
+
const customerIds = referencedIds(reviews, 'customer_id')
|
|
152
|
+
const [products, customers] = await Promise.all([
|
|
153
|
+
productIds.length > 0 ? run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(productIds, dialect)})`, productIds).execute() : [],
|
|
154
|
+
customerIds.length > 0 ? run.unsafe(`SELECT id, name, email FROM customers WHERE id IN (${idPlaceholders(customerIds, dialect)})`, customerIds).execute() : [],
|
|
155
|
+
])
|
|
156
|
+
const productMap = new Map(sqlRows(products).map(normalizeReviewProductOption).map(option => [option.id, { name: option.label }]))
|
|
157
|
+
const customerMap = new Map(sqlRows(customers).map(normalizeReviewCustomerContext).map(customer => [customer.id, customer.context]))
|
|
158
|
+
return reviews.map(review => normalizeReviewRecord(review, productMap, customerMap))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The summary cards, over every review as before. */
|
|
162
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<ReviewSummary> {
|
|
163
|
+
const count = (condition: string) => `SUM(CASE WHEN ${condition} THEN 1 ELSE 0 END)`
|
|
164
|
+
const row = sqlRows(await run.unsafe(
|
|
165
|
+
`SELECT COUNT(*) AS total_count, ${count(isTrue('is_approved', dialect))} AS approved_count, ${count(isTrue('is_featured', dialect))} AS featured_count, ${count(isTrue('is_verified_purchase', dialect))} AS verified_count, COUNT(rating) AS rated_count, SUM(rating) AS rating_total FROM reviews`,
|
|
166
|
+
).execute())[0] ?? {}
|
|
167
|
+
const total = countOf(row.total_count)
|
|
168
|
+
const approved = countOf(row.approved_count)
|
|
169
|
+
const rated = countOf(row.rated_count)
|
|
170
|
+
return {
|
|
171
|
+
total,
|
|
172
|
+
approved,
|
|
173
|
+
pending: total - approved,
|
|
174
|
+
featured: countOf(row.featured_count),
|
|
175
|
+
verified: countOf(row.verified_count),
|
|
176
|
+
// An unrated review is a review, not a 0-star one, so the average is
|
|
177
|
+
// taken over the rated reviews only, as summarizeReviews does.
|
|
178
|
+
averageRating: rated > 0 ? Math.round(countOf(row.rating_total) / rated * 10) / 10 : 0,
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The product filter's choices: every product that has a review, read whole.
|
|
184
|
+
* The page listed the first 500 products by name, reviewed or not.
|
|
185
|
+
*/
|
|
186
|
+
async function reviewedProducts(run: CommerceSqlRunner): Promise<ReviewProductOption[]> {
|
|
187
|
+
const rows = sqlRows(await run.unsafe(
|
|
188
|
+
// LOWER, so the order is the same on every dialect: each collates case its own way.
|
|
189
|
+
'SELECT p.id, p.name FROM products p WHERE EXISTS (SELECT 1 FROM reviews r WHERE r.product_id = p.id) ORDER BY LOWER(p.name) ASC, p.id ASC',
|
|
190
|
+
).execute())
|
|
191
|
+
return rows.map(normalizeReviewProductOption)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export interface ReviewPage {
|
|
195
|
+
records: ReviewRecord[]
|
|
196
|
+
total: number
|
|
197
|
+
page: number
|
|
198
|
+
summary: ReviewSummary
|
|
199
|
+
products: ReviewProductOption[]
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export async function readReviewPage(
|
|
203
|
+
query: ReviewListQuery,
|
|
204
|
+
run: CommerceSqlRunner = db,
|
|
205
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
206
|
+
): Promise<ReviewPage> {
|
|
207
|
+
const { where, values } = reviewFilter(query, dialect)
|
|
208
|
+
const [counted, summary, products] = await Promise.all([
|
|
209
|
+
run.unsafe(`SELECT COUNT(*) AS total_count${FROM}${where}`, values).execute(),
|
|
210
|
+
summarize(run, dialect),
|
|
211
|
+
reviewedProducts(run),
|
|
212
|
+
])
|
|
213
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
214
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
215
|
+
const reviews = await run.unsafe(
|
|
216
|
+
`SELECT r.*${FROM}${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
217
|
+
values,
|
|
218
|
+
).execute()
|
|
219
|
+
return { records: await recordsFor(sqlRows(reviews), run, dialect), total, page, summary, products }
|
|
220
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { sqlHelpers } from '@stacksjs/database/runtime'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The SQL plumbing the commerce lists share (stacksjs/stacks#3218): Orders and
|
|
6
|
+
* Payments read their pages with plain SQL so one test can run them against
|
|
7
|
+
* SQLite, PostgreSQL and MySQL alike.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** What runs the queries: the configured `db`, or a test's own connection. */
|
|
11
|
+
export interface CommerceSqlRunner {
|
|
12
|
+
unsafe: (sql: string, values?: unknown[]) => { execute: () => Promise<unknown> }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A result as rows, whatever the driver returned for an empty one. */
|
|
16
|
+
export function sqlRows(result: unknown): Array<Record<string, unknown>> {
|
|
17
|
+
return Array.isArray(result) ? result as Array<Record<string, unknown>> : []
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The placeholders for an `IN (...)` over `ids`, numbered from 1. */
|
|
21
|
+
export function idPlaceholders(ids: unknown[], dialect: QueryBuilderDialect): string {
|
|
22
|
+
const sql = sqlHelpers(dialect)
|
|
23
|
+
return ids.map((_, index) => sql.param(index + 1)).join(', ')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A column as text, for `LOWER`, `LIKE` and comparisons. PostgreSQL enums
|
|
28
|
+
* (payments.status and payments.method) and numbers need it, and comparing an
|
|
29
|
+
* enum to a value it does not list is an error there rather than no match.
|
|
30
|
+
*/
|
|
31
|
+
export function asText(column: string, dialect: QueryBuilderDialect): string {
|
|
32
|
+
const type = dialect === 'mysql' || dialect === 'singlestore' || dialect === 'vitess' ? 'CHAR' : 'TEXT'
|
|
33
|
+
return `CAST(${column} AS ${type})`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Binds values in order and returns each placeholder, for building a WHERE. */
|
|
37
|
+
export function binder(dialect: QueryBuilderDialect): { bind: (value: unknown) => string, values: unknown[] } {
|
|
38
|
+
const sql = sqlHelpers(dialect)
|
|
39
|
+
const values: unknown[] = []
|
|
40
|
+
return {
|
|
41
|
+
values,
|
|
42
|
+
bind: (value: unknown) => {
|
|
43
|
+
values.push(value)
|
|
44
|
+
return sql.param(values.length)
|
|
45
|
+
},
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* "This flag is set", the same on every dialect: SQLite and MySQL store 0 and
|
|
51
|
+
* 1, and PostgreSQL a boolean, or an integer in an older schema, which the
|
|
52
|
+
* cast reads either way. A bare `column = 1` is an error on a PostgreSQL
|
|
53
|
+
* boolean.
|
|
54
|
+
*/
|
|
55
|
+
export function isTrue(column: string, dialect: QueryBuilderDialect): string {
|
|
56
|
+
return dialect === 'postgres' ? `CAST(${column} AS INTEGER) = 1` : `${column} = 1`
|
|
57
|
+
}
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
paymentsToCsv,
|
|
6
6
|
summarizePayments,
|
|
7
7
|
} from './payment-records'
|
|
8
|
+
import { referencedIds } from './commerce-record'
|
|
8
9
|
|
|
9
10
|
function payment(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
|
10
11
|
return {
|
|
@@ -103,3 +104,18 @@ describe('dashboard payment records', () => {
|
|
|
103
104
|
expect(csv).toContain('1,2026-07-29T10:00:00.000Z,completed,creditCard,1000')
|
|
104
105
|
})
|
|
105
106
|
})
|
|
107
|
+
|
|
108
|
+
describe('the orders and customers a payments page reads', () => {
|
|
109
|
+
test('a payment for an order past the 500 oldest normalizes from the referenced read', () => {
|
|
110
|
+
// A store's 704th order is outside a read of its 500 oldest. The ids the
|
|
111
|
+
// payments reference still name it, so the payment is accepted.
|
|
112
|
+
const payments = [payment({ id: 1, order_id: 704, customer_id: 9 }), payment({ id: 2, order_id: 12 })]
|
|
113
|
+
const orderIds = new Set(referencedIds(payments, 'order_id').map(String))
|
|
114
|
+
const customerIds = new Set(referencedIds(payments, 'customer_id').map(String))
|
|
115
|
+
expect(normalizePaymentRecord(payments[0], { orderIds, customerIds }).orderId).toBe('704')
|
|
116
|
+
|
|
117
|
+
// The refusal this prevents is real: without order 704 the payment is rejected.
|
|
118
|
+
const oldest = new Set(Array.from({ length: 500 }, (_, index) => String(index + 1)))
|
|
119
|
+
expect(() => normalizePaymentRecord(payments[0], { orderIds: oldest, customerIds })).toThrow('references missing Order 704')
|
|
120
|
+
})
|
|
121
|
+
})
|
|
@@ -28,13 +28,14 @@ describe('dashboard product waitlist records', () => {
|
|
|
28
28
|
it('normalizes database and model attribute names', () => {
|
|
29
29
|
expect(normalizeProductWaitlistRecord(
|
|
30
30
|
entry({ quantity: '3', customer_id: 9 }),
|
|
31
|
-
new
|
|
31
|
+
new Map([['8', 'Native Mug']]),
|
|
32
32
|
new Set(['9']),
|
|
33
33
|
)).toMatchObject({
|
|
34
34
|
id: '4',
|
|
35
35
|
quantity: 3,
|
|
36
36
|
notificationPreference: 'email',
|
|
37
37
|
productId: '8',
|
|
38
|
+
productName: 'Native Mug',
|
|
38
39
|
customerId: '9',
|
|
39
40
|
status: 'waiting',
|
|
40
41
|
createdAt: '2026-07-28T12:00:00.000Z',
|
|
@@ -44,21 +45,21 @@ describe('dashboard product waitlist records', () => {
|
|
|
44
45
|
it('rejects corrupt fields and missing relationships', () => {
|
|
45
46
|
expect(() => normalizeProductWaitlistRecord(
|
|
46
47
|
entry({ quantity: 0 }),
|
|
47
|
-
new
|
|
48
|
+
new Map([['8', 'Native Mug']]),
|
|
48
49
|
)).toThrow('WaitlistProduct 4.quantity must be at least 1')
|
|
49
50
|
expect(() => normalizeProductWaitlistRecord(
|
|
50
51
|
entry({ product_id: 99 }),
|
|
51
|
-
new
|
|
52
|
+
new Map(),
|
|
52
53
|
)).toThrow('WaitlistProduct 4.product_id references missing Product 99')
|
|
53
54
|
expect(() => normalizeProductWaitlistRecord(
|
|
54
55
|
entry({ customer_id: 99 }),
|
|
55
|
-
new
|
|
56
|
+
new Map([['8', 'Native Mug']]),
|
|
56
57
|
new Set(),
|
|
57
58
|
)).toThrow('WaitlistProduct 4.customer_id references missing Customer 99')
|
|
58
59
|
})
|
|
59
60
|
|
|
60
61
|
it('summarizes only native record states', () => {
|
|
61
|
-
const productIds = new
|
|
62
|
+
const productIds = new Map([['8', 'Native Mug']])
|
|
62
63
|
const records = [
|
|
63
64
|
normalizeProductWaitlistRecord(entry({ id: 1, status: 'waiting' }), productIds),
|
|
64
65
|
normalizeProductWaitlistRecord(entry({ id: 2, status: 'notified' }), productIds),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CustomerChoice, ProductChoice } from './commerce-choice-records'
|
|
1
2
|
import {
|
|
2
3
|
commerceEmail,
|
|
3
4
|
commerceEnum,
|
|
@@ -21,6 +22,8 @@ export interface ProductWaitlistRecord {
|
|
|
21
22
|
notes: string
|
|
22
23
|
status: string
|
|
23
24
|
productId: string
|
|
25
|
+
/** The waitlisted product's name, read with the entry. */
|
|
26
|
+
productName: string
|
|
24
27
|
customerId: string
|
|
25
28
|
createdAt: string
|
|
26
29
|
}
|
|
@@ -33,21 +36,11 @@ export interface ProductWaitlistSummary {
|
|
|
33
36
|
conversionRate: number
|
|
34
37
|
}
|
|
35
38
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
label: string
|
|
39
|
-
detail: string
|
|
40
|
-
}
|
|
39
|
+
/** A product the entry dialog offers (commerce-choice-records.ts). */
|
|
40
|
+
export type ProductWaitlistOption = ProductChoice
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
phone: string
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export interface ProductWaitlistOptions {
|
|
48
|
-
products: ProductWaitlistOption[]
|
|
49
|
-
customers: ProductWaitlistCustomerOption[]
|
|
50
|
-
}
|
|
42
|
+
/** A customer the entry dialog offers (commerce-choice-records.ts). */
|
|
43
|
+
export type ProductWaitlistCustomerOption = CustomerChoice
|
|
51
44
|
|
|
52
45
|
export interface ProductWaitlistWritePayload {
|
|
53
46
|
productId: number
|
|
@@ -62,9 +55,14 @@ export interface ProductWaitlistWritePayload {
|
|
|
62
55
|
status: 'waiting' | 'notified' | 'purchased' | 'cancelled'
|
|
63
56
|
}
|
|
64
57
|
|
|
58
|
+
/**
|
|
59
|
+
* An entry as the dashboard shows it. `products` maps each product the entry
|
|
60
|
+
* may reference to its name; an entry for any other product is refused, as is
|
|
61
|
+
* one for a customer outside `customerIds`.
|
|
62
|
+
*/
|
|
65
63
|
export function normalizeProductWaitlistRecord(
|
|
66
64
|
record: any,
|
|
67
|
-
|
|
65
|
+
products?: Map<string, string>,
|
|
68
66
|
customerIds?: Set<string>,
|
|
69
67
|
): ProductWaitlistRecord {
|
|
70
68
|
const id = commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'WaitlistProduct')
|
|
@@ -74,7 +72,7 @@ export function normalizeProductWaitlistRecord(
|
|
|
74
72
|
source,
|
|
75
73
|
'product_id',
|
|
76
74
|
)
|
|
77
|
-
if (
|
|
75
|
+
if (products && !products.has(productId))
|
|
78
76
|
throw new TypeError(`${source}.product_id references missing Product ${productId}.`)
|
|
79
77
|
const customerId = commerceOptionalIdentifier(
|
|
80
78
|
commerceValue(record, 'customer_id', 'customerId'),
|
|
@@ -107,40 +105,13 @@ export function normalizeProductWaitlistRecord(
|
|
|
107
105
|
'cancelled',
|
|
108
106
|
]),
|
|
109
107
|
productId,
|
|
108
|
+
productName: products?.get(productId) ?? '',
|
|
110
109
|
customerId,
|
|
111
110
|
createdAt: commerceTimestamp(commerceValue(record, 'created_at', 'createdAt'), source),
|
|
112
111
|
}
|
|
113
112
|
}
|
|
114
113
|
|
|
115
|
-
export
|
|
116
|
-
const id = commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'Product')
|
|
117
|
-
const source = `Product ${id}`
|
|
118
|
-
const inventory = commerceNumber(
|
|
119
|
-
commerceValue(record, 'inventory_count', 'inventoryCount'),
|
|
120
|
-
source,
|
|
121
|
-
'inventory_count',
|
|
122
|
-
{ min: 0, integer: true },
|
|
123
|
-
)
|
|
124
|
-
return {
|
|
125
|
-
id,
|
|
126
|
-
label: commerceRequiredString(commerceValue(record, 'name'), source, 'name'),
|
|
127
|
-
detail: `${inventory} in inventory`,
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export function normalizeProductWaitlistCustomerOption(record: any): ProductWaitlistCustomerOption {
|
|
132
|
-
const id = commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'Customer')
|
|
133
|
-
const source = `Customer ${id}`
|
|
134
|
-
const email = commerceEmail(commerceValue(record, 'email'), source)
|
|
135
|
-
const phone = commerceOptionalString(commerceValue(record, 'phone'), source, 'phone')
|
|
136
|
-
return {
|
|
137
|
-
id,
|
|
138
|
-
label: commerceRequiredString(commerceValue(record, 'name'), source, 'name'),
|
|
139
|
-
detail: email || phone,
|
|
140
|
-
email,
|
|
141
|
-
phone,
|
|
142
|
-
}
|
|
143
|
-
}
|
|
114
|
+
export { normalizeCustomerChoice as normalizeProductWaitlistCustomerOption, normalizeProductChoice as normalizeProductWaitlistOption } from './commerce-choice-records'
|
|
144
115
|
|
|
145
116
|
export function summarizeProductWaitlist(records: ProductWaitlistRecord[]): ProductWaitlistSummary {
|
|
146
117
|
const waiting = records.filter(record => record.status === 'waiting').length
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CustomerChoice } from './commerce-choice-records'
|
|
1
2
|
import {
|
|
2
3
|
commerceEmail,
|
|
3
4
|
commerceEnum,
|
|
@@ -37,17 +38,8 @@ export interface RestaurantWaitlistSummary {
|
|
|
37
38
|
seatingRate: number
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
label: string
|
|
43
|
-
detail: string
|
|
44
|
-
email: string
|
|
45
|
-
phone: string
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export interface RestaurantWaitlistOptions {
|
|
49
|
-
customers: RestaurantWaitlistCustomerOption[]
|
|
50
|
-
}
|
|
41
|
+
/** A customer the entry dialog offers (commerce-choice-records.ts). */
|
|
42
|
+
export type RestaurantWaitlistCustomerOption = CustomerChoice
|
|
51
43
|
|
|
52
44
|
export interface RestaurantWaitlistWritePayload {
|
|
53
45
|
customerId: number | null
|
|
@@ -151,19 +143,7 @@ export function normalizeRestaurantWaitlistRecord(
|
|
|
151
143
|
}
|
|
152
144
|
}
|
|
153
145
|
|
|
154
|
-
export
|
|
155
|
-
const id = commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'Customer')
|
|
156
|
-
const source = `Customer ${id}`
|
|
157
|
-
const email = commerceEmail(commerceValue(record, 'email'), source)
|
|
158
|
-
const phone = commerceOptionalString(commerceValue(record, 'phone'), source, 'phone')
|
|
159
|
-
return {
|
|
160
|
-
id,
|
|
161
|
-
label: commerceRequiredString(commerceValue(record, 'name'), source, 'name'),
|
|
162
|
-
detail: email || phone,
|
|
163
|
-
email,
|
|
164
|
-
phone,
|
|
165
|
-
}
|
|
166
|
-
}
|
|
146
|
+
export { normalizeCustomerChoice as normalizeRestaurantWaitlistCustomerOption } from './commerce-choice-records'
|
|
167
147
|
|
|
168
148
|
export function summarizeRestaurantWaitlist(records: RestaurantWaitlistRecord[]): RestaurantWaitlistSummary {
|
|
169
149
|
const waitingRecords = records.filter(record => record.status === 'waiting')
|
|
@@ -67,3 +67,13 @@ export function pageWithin(page: number, total: number, perPage: number): number
|
|
|
67
67
|
export function countOf(value: unknown): number {
|
|
68
68
|
return Number(value ?? 0) || 0
|
|
69
69
|
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* A `LIKE` pattern that matches `term` anywhere, ignoring case, with its own
|
|
73
|
+
* `%` and `_` taken literally. Use it with `ESCAPE '!'`: `!` means the same in
|
|
74
|
+
* every dialect, where SQLite has no default escape and MySQL reads a
|
|
75
|
+
* backslash in a string literal as an escape of its own.
|
|
76
|
+
*/
|
|
77
|
+
export function containsPattern(term: string): string {
|
|
78
|
+
return `%${term.toLowerCase().replace(/[!%_]/g, character => `!${character}`)}%`
|
|
79
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import type { StorageMetadataStore } from './file-metadata'
|
|
3
|
+
import { createMemoryMetadataStore } from './file-metadata'
|
|
4
|
+
import { readListingMetadata } from './file-manager'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The file listing reads the advisory metadata rows (stars, tags, tasks)
|
|
8
|
+
* before building the tree. A missing table must give an empty answer, not a
|
|
9
|
+
* failed listing (stacksjs/stacks#3211); anything else must still fail.
|
|
10
|
+
*/
|
|
11
|
+
function failingStore(error: Error): StorageMetadataStore {
|
|
12
|
+
const store = createMemoryMetadataStore()
|
|
13
|
+
return { ...store, under: async () => { throw error }, tasksUnder: async () => { throw error } }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('readListingMetadata', () => {
|
|
17
|
+
test('reads the rows when the tables exist', async () => {
|
|
18
|
+
const store = createMemoryMetadataStore()
|
|
19
|
+
await store.write('public', 'a.txt', { favorite: true, tags: [] })
|
|
20
|
+
const read = await readListingMetadata(store, 'public', async () => { throw new Error('the catalog must not be asked') })
|
|
21
|
+
|
|
22
|
+
expect(read.migrated).toBeTrue()
|
|
23
|
+
expect(read.records.get('a.txt')?.favorite).toBeTrue()
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test('a missing table lists with no stars, tags or tasks', async () => {
|
|
27
|
+
const asked: string[] = []
|
|
28
|
+
const read = await readListingMetadata(failingStore(new Error('relation "storage_items" does not exist')), 'public', async (table) => {
|
|
29
|
+
asked.push(table)
|
|
30
|
+
return table === 'storage_items'
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
expect(read).toEqual({ records: new Map(), tasks: new Map(), migrated: false })
|
|
34
|
+
expect(asked).toEqual(['storage_items'])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
test('the tasks table missing on its own counts too', async () => {
|
|
38
|
+
const read = await readListingMetadata(failingStore(new Error('no such table: storage_item_tasks')), 'public', async table => table === 'storage_item_tasks')
|
|
39
|
+
expect(read.migrated).toBeFalse()
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test('any other failure still fails the listing', async () => {
|
|
43
|
+
const outage = new Error('connection refused')
|
|
44
|
+
await expect(readListingMetadata(failingStore(outage), 'public', async () => false)).rejects.toBe(outage)
|
|
45
|
+
})
|
|
46
|
+
})
|
|
@@ -4,7 +4,7 @@ import { posix } from 'node:path'
|
|
|
4
4
|
import type { JobName } from '@stacksjs/queue'
|
|
5
5
|
import type { StorageAdapter, StorageManager, UploadedFileLike, Visibility } from '@stacksjs/storage'
|
|
6
6
|
import { Storage } from '@stacksjs/storage'
|
|
7
|
-
import type { StorageItemTask, StorageMetadataStore, StorageTaskKind, StorageTaskState } from './file-metadata'
|
|
7
|
+
import type { StorageItemMetadata, StorageItemTask, StorageMetadataStore, StorageTaskKind, StorageTaskState } from './file-metadata'
|
|
8
8
|
import {
|
|
9
9
|
aggregateTaskState,
|
|
10
10
|
dispatchTasks,
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
variantsPathFor,
|
|
23
23
|
} from './file-metadata'
|
|
24
24
|
import { databaseMetadataStore } from './file-metadata-store'
|
|
25
|
+
import { isUnmigratedTable } from '../Models/model-migration'
|
|
25
26
|
import { claimedContentType, hasPreview, previewPathFor, previewPlanFor, previewUrlFor } from './file-preview'
|
|
26
27
|
|
|
27
28
|
const DEFAULT_DISK = 'public'
|
|
@@ -330,6 +331,44 @@ export function normalizeDashboardFileLimit(value: unknown): number {
|
|
|
330
331
|
return normalized
|
|
331
332
|
}
|
|
332
333
|
|
|
334
|
+
/** The tables the advisory file metadata lives in (`app/Models/StorageItem.ts`). */
|
|
335
|
+
const METADATA_TABLES = ['storage_items', 'storage_item_tasks'] as const
|
|
336
|
+
|
|
337
|
+
export const METADATA_NOT_MIGRATED = 'Stars, tags and processing status are off until the storage_items tables exist. Run ./buddy migrate to create them.'
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* The stars, tags and tasks recorded for a disk, for a listing.
|
|
341
|
+
*
|
|
342
|
+
* The disk is authoritative and these rows are advisory: a path with no row
|
|
343
|
+
* is a file with no stars, the normal case. So an app that has not migrated
|
|
344
|
+
* the metadata tables still gets its files, without stars, tags or tasks, and
|
|
345
|
+
* a warning that names the command. The listing used to fail outright with
|
|
346
|
+
* "Files could not be loaded" (stacksjs/stacks#3211).
|
|
347
|
+
*
|
|
348
|
+
* Only a missing table is treated that way, and the catalog decides it: any
|
|
349
|
+
* other failure is rethrown, so a database outage still fails the listing.
|
|
350
|
+
*/
|
|
351
|
+
export async function readListingMetadata(
|
|
352
|
+
store: StorageMetadataStore,
|
|
353
|
+
disk: string,
|
|
354
|
+
isMissing: (table: string) => Promise<boolean> = isUnmigratedTable,
|
|
355
|
+
): Promise<{ records: Map<string, StorageItemMetadata>, tasks: Map<string, StorageItemTask[]>, migrated: boolean }> {
|
|
356
|
+
try {
|
|
357
|
+
return {
|
|
358
|
+
records: await metadataUnder(store, disk),
|
|
359
|
+
tasks: await store.tasksUnder(disk, ''),
|
|
360
|
+
migrated: true,
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
catch (error) {
|
|
364
|
+
for (const table of METADATA_TABLES) {
|
|
365
|
+
if (await isMissing(table))
|
|
366
|
+
return { records: new Map(), tasks: new Map(), migrated: false }
|
|
367
|
+
}
|
|
368
|
+
throw error
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
333
372
|
export async function getDashboardFileSnapshot(
|
|
334
373
|
options: { disk?: string, maxEntries?: number } = {},
|
|
335
374
|
manager: Manager = Storage,
|
|
@@ -354,8 +393,7 @@ export async function getDashboardFileSnapshot(
|
|
|
354
393
|
// One query for the whole subtree, not one per file: a folder of a thousand
|
|
355
394
|
// files would otherwise be a thousand round trips to answer a question about
|
|
356
395
|
// the handful of them anybody starred (stacksjs/stacks#2577).
|
|
357
|
-
const records = await
|
|
358
|
-
const tasks = await store.tasksUnder(selected.name, '')
|
|
396
|
+
const { records, tasks, migrated: metadataMigrated } = await readListingMetadata(store, selected.name)
|
|
359
397
|
|
|
360
398
|
const stated = await mapInBatches(
|
|
361
399
|
entries,
|
|
@@ -509,13 +547,15 @@ export async function getDashboardFileSnapshot(
|
|
|
509
547
|
// this takes the flag: a truncated walk has not shown that a path is absent,
|
|
510
548
|
// only that it stopped before reaching it, and sweeping on that would delete
|
|
511
549
|
// the metadata of every file past the limit (stacksjs/stacks#2577).
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
550
|
+
if (metadataMigrated) {
|
|
551
|
+
await sweepMetadata(
|
|
552
|
+
store,
|
|
553
|
+
selected.name,
|
|
554
|
+
'',
|
|
555
|
+
new Set(stated.map(entry => entry.path)),
|
|
556
|
+
{ truncated },
|
|
557
|
+
)
|
|
558
|
+
}
|
|
519
559
|
|
|
520
560
|
return {
|
|
521
561
|
disk: selected.name,
|
|
@@ -528,6 +568,7 @@ export async function getDashboardFileSnapshot(
|
|
|
528
568
|
truncated,
|
|
529
569
|
warnings: [
|
|
530
570
|
...(capacity.warning ? [capacity.warning] : []),
|
|
571
|
+
...(metadataMigrated ? [] : [METADATA_NOT_MIGRATED]),
|
|
531
572
|
...stated.flatMap(entry => entry.warnings),
|
|
532
573
|
],
|
|
533
574
|
}
|