pgkiln 0.55.0 → 0.57.0

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.
Files changed (53) hide show
  1. package/SECURITY.md +2 -0
  2. package/docs/apex-feature-parity.md +4 -4
  3. package/docs/guide/03-builder.md +11 -4
  4. package/docs/guide/04-pages-and-regions.md +26 -0
  5. package/docs/guide/12-development.md +14 -0
  6. package/examples/gallery/README.md +4 -0
  7. package/examples/gallery/gallery.json +8 -0
  8. package/examples/gallery/samples/sample-approvals.sql +153 -0
  9. package/examples/gallery/samples/sample-data-loading.sql +142 -0
  10. package/examples/gallery/samples/sample-files.sql +160 -0
  11. package/examples/gallery/samples/sample-maps.sql +175 -0
  12. package/examples/gallery/samples/sample-reporting.sql +4 -3
  13. package/package.json +1 -1
  14. package/public/builder.css +1 -1
  15. package/public/worksheet.js +31 -26
  16. package/src/builder/i18n/de.ts +371 -0
  17. package/src/builder/i18n/en.ts +371 -0
  18. package/src/builder/i18n/es.ts +371 -0
  19. package/src/builder/i18n/fr.ts +371 -0
  20. package/src/builder/i18n/nl.ts +371 -0
  21. package/src/builder/i18n/pt.ts +371 -0
  22. package/src/builder/i18n.ts +10 -0
  23. package/src/builder/object-browser.ts +71 -67
  24. package/src/builder/region-help.ts +1 -1
  25. package/src/builder/region-settings.ts +3 -1
  26. package/src/builder/table-editor.ts +51 -48
  27. package/src/builder/ui.ts +3 -2
  28. package/src/builder/worksheet.ts +160 -154
  29. package/src/i18n/ar.ts +1 -0
  30. package/src/i18n/cs.ts +1 -0
  31. package/src/i18n/da.ts +1 -0
  32. package/src/i18n/de.ts +1 -0
  33. package/src/i18n/el.ts +1 -0
  34. package/src/i18n/es.ts +1 -0
  35. package/src/i18n/fi.ts +1 -0
  36. package/src/i18n/fr.ts +1 -0
  37. package/src/i18n/he.ts +1 -0
  38. package/src/i18n/it.ts +1 -0
  39. package/src/i18n/ja.ts +1 -0
  40. package/src/i18n/ko.ts +1 -0
  41. package/src/i18n/nb.ts +1 -0
  42. package/src/i18n/pl.ts +1 -0
  43. package/src/i18n/pt.ts +1 -0
  44. package/src/i18n/ru.ts +1 -0
  45. package/src/i18n/sv.ts +1 -0
  46. package/src/i18n/tr.ts +1 -0
  47. package/src/i18n/uk.ts +1 -0
  48. package/src/i18n/zh.ts +1 -0
  49. package/src/i18n.ts +2 -0
  50. package/src/runtime/ai-filter.ts +22 -6
  51. package/src/runtime/ask-facets.ts +72 -0
  52. package/src/runtime/ir-plan.ts +17 -3
  53. package/src/runtime/smart-filters.ts +36 -2
package/src/i18n/ar.ts CHANGED
@@ -406,6 +406,7 @@ export const ar: Record<MessageKey, string> = {
406
406
  'smart.suggested': "عوامل تصفية مقترحة:",
407
407
  'smart.matching': "التصفية حسب:",
408
408
  'smart.no_match': "لا يطابق أي عامل تصفية البحث؛ يُبحث عن النص في كل الأعمدة.",
409
+ 'smart.understood': "فُهم على أنه:",
409
410
  'rds.label': "المناطق",
410
411
  'rds.region': "المنطقة",
411
412
  'rds.show_all': "إظهار الكل",
package/src/i18n/cs.ts CHANGED
@@ -406,6 +406,7 @@ export const cs: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Navrhované filtry:",
407
407
  'smart.matching': "Filtrovat podle:",
408
408
  'smart.no_match': "Hledání neodpovídá žádný filtr; text se hledá ve všech sloupcích.",
409
+ 'smart.understood': "Pochopeno jako:",
409
410
  'rds.label': "Oblasti",
410
411
  'rds.region': "Oblast",
411
412
  'rds.show_all': "Zobrazit vše",
package/src/i18n/da.ts CHANGED
@@ -406,6 +406,7 @@ export const da: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Foreslåede filtre:",
407
407
  'smart.matching': "Filtrér på:",
408
408
  'smart.no_match': "Intet filter passer til søgningen; teksten søges i alle kolonner.",
409
+ 'smart.understood': "Forstået som:",
409
410
  'rds.label': "Regioner",
410
411
  'rds.region': "Region",
411
412
  'rds.show_all': "Vis alle",
package/src/i18n/de.ts CHANGED
@@ -406,6 +406,7 @@ export const de: Record<MessageKey, string> = {
406
406
  'smart.suggested': 'Vorgeschlagene Filter:',
407
407
  'smart.matching': 'Filtern nach:',
408
408
  'smart.no_match': 'Kein Filter passt zur Suche; der Text wird in allen Spalten gesucht.',
409
+ 'smart.understood': 'Verstanden als:',
409
410
  'rds.label': 'Regionen',
410
411
  'rds.region': 'Region',
411
412
  'rds.show_all': 'Alle anzeigen',
package/src/i18n/el.ts CHANGED
@@ -406,6 +406,7 @@ export const el: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Προτεινόμενα φίλτρα:",
407
407
  'smart.matching': "Φιλτράρισμα κατά:",
408
408
  'smart.no_match': "Κανένα φίλτρο δεν ταιριάζει· το κείμενο αναζητείται σε όλες τις στήλες.",
409
+ 'smart.understood': "Κατανοήθηκε ως:",
409
410
  'rds.label': "Περιοχές",
410
411
  'rds.region': "Περιοχή",
411
412
  'rds.show_all': "Εμφάνιση όλων",
package/src/i18n/es.ts CHANGED
@@ -406,6 +406,7 @@ export const es: Record<MessageKey, string> = {
406
406
  'smart.suggested': 'Filtros sugeridos:',
407
407
  'smart.matching': 'Filtrar por:',
408
408
  'smart.no_match': 'Ningún filtro coincide con la búsqueda; el texto se busca en todas las columnas.',
409
+ 'smart.understood': 'Entendido como:',
409
410
  'rds.label': 'Regiones',
410
411
  'rds.region': 'Región',
411
412
  'rds.show_all': 'Mostrar todo',
package/src/i18n/fi.ts CHANGED
@@ -406,6 +406,7 @@ export const fi: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Ehdotetut suodattimet:",
407
407
  'smart.matching': "Suodata:",
408
408
  'smart.no_match': "Mikään suodatin ei vastaa hakua; tekstiä haetaan kaikista sarakkeista.",
409
+ 'smart.understood': "Tulkittu näin:",
409
410
  'rds.label': "Alueet",
410
411
  'rds.region': "Alue",
411
412
  'rds.show_all': "Näytä kaikki",
package/src/i18n/fr.ts CHANGED
@@ -406,6 +406,7 @@ export const fr: Record<MessageKey, string> = {
406
406
  'smart.suggested': 'Filtres suggérés :',
407
407
  'smart.matching': 'Filtrer sur :',
408
408
  'smart.no_match': 'Aucun filtre ne correspond à la recherche ; le texte est recherché dans toutes les colonnes.',
409
+ 'smart.understood': 'Compris comme :',
409
410
  'rds.label': 'Régions',
410
411
  'rds.region': 'Région',
411
412
  'rds.show_all': 'Tout afficher',
package/src/i18n/he.ts CHANGED
@@ -406,6 +406,7 @@ export const he: Record<MessageKey, string> = {
406
406
  'smart.suggested': "מסננים מוצעים:",
407
407
  'smart.matching': "סינון לפי:",
408
408
  'smart.no_match': "אין מסנן שמתאים לחיפוש; הטקסט מחופש בכל העמודות.",
409
+ 'smart.understood': "הובן כ:",
409
410
  'rds.label': "אזורים",
410
411
  'rds.region': "אזור",
411
412
  'rds.show_all': "הצגת הכול",
package/src/i18n/it.ts CHANGED
@@ -406,6 +406,7 @@ export const it: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Filtri suggeriti:",
407
407
  'smart.matching': "Filtra per:",
408
408
  'smart.no_match': "Nessun filtro corrisponde alla ricerca; il testo viene cercato in tutte le colonne.",
409
+ 'smart.understood': "Interpretato come:",
409
410
  'rds.label': "Regioni",
410
411
  'rds.region': "Regione",
411
412
  'rds.show_all': "Mostra tutto",
package/src/i18n/ja.ts CHANGED
@@ -406,6 +406,7 @@ export const ja: Record<MessageKey, string> = {
406
406
  'smart.suggested': "おすすめのフィルター:",
407
407
  'smart.matching': "絞り込み:",
408
408
  'smart.no_match': "検索に一致するフィルターはありません。テキストはすべての列で検索されます。",
409
+ 'smart.understood': "次のように解釈:",
409
410
  'rds.label': "リージョン",
410
411
  'rds.region': "リージョン",
411
412
  'rds.show_all': "すべて表示",
package/src/i18n/ko.ts CHANGED
@@ -406,6 +406,7 @@ export const ko: Record<MessageKey, string> = {
406
406
  'smart.suggested': "추천 필터:",
407
407
  'smart.matching': "필터 조건:",
408
408
  'smart.no_match': "검색과 일치하는 필터가 없어 모든 열에서 텍스트를 검색합니다.",
409
+ 'smart.understood': "이렇게 이해함:",
409
410
  'rds.label': "영역",
410
411
  'rds.region': "영역",
411
412
  'rds.show_all': "모두 표시",
package/src/i18n/nb.ts CHANGED
@@ -406,6 +406,7 @@ export const nb: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Foreslåtte filtre:",
407
407
  'smart.matching': "Filtrer på:",
408
408
  'smart.no_match': "Ingen filtre passer til søket; teksten søkes i alle kolonner.",
409
+ 'smart.understood': "Forstått som:",
409
410
  'rds.label': "Regioner",
410
411
  'rds.region': "Region",
411
412
  'rds.show_all': "Vis alle",
package/src/i18n/pl.ts CHANGED
@@ -406,6 +406,7 @@ export const pl: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Sugerowane filtry:",
407
407
  'smart.matching': "Filtruj według:",
408
408
  'smart.no_match': "Żaden filtr nie pasuje do wyszukiwania; tekst jest szukany we wszystkich kolumnach.",
409
+ 'smart.understood': "Zrozumiano jako:",
409
410
  'rds.label': "Regiony",
410
411
  'rds.region': "Region",
411
412
  'rds.show_all': "Pokaż wszystkie",
package/src/i18n/pt.ts CHANGED
@@ -406,6 +406,7 @@ export const pt: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Filtros sugeridos:",
407
407
  'smart.matching': "Filtrar por:",
408
408
  'smart.no_match': "Nenhum filtro corresponde à pesquisa; o texto é procurado em todas as colunas.",
409
+ 'smart.understood': "Entendido como:",
409
410
  'rds.label': "Regiões",
410
411
  'rds.region': "Região",
411
412
  'rds.show_all': "Mostrar tudo",
package/src/i18n/ru.ts CHANGED
@@ -406,6 +406,7 @@ export const ru: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Предлагаемые фильтры:",
407
407
  'smart.matching': "Фильтровать по:",
408
408
  'smart.no_match': "Ни один фильтр не подходит; текст ищется во всех столбцах.",
409
+ 'smart.understood': "Понято как:",
409
410
  'rds.label': "Области",
410
411
  'rds.region': "Область",
411
412
  'rds.show_all': "Показать все",
package/src/i18n/sv.ts CHANGED
@@ -406,6 +406,7 @@ export const sv: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Föreslagna filter:",
407
407
  'smart.matching': "Filtrera på:",
408
408
  'smart.no_match': "Inget filter matchar sökningen; texten söks i alla kolumner.",
409
+ 'smart.understood': "Tolkat som:",
409
410
  'rds.label': "Regioner",
410
411
  'rds.region': "Region",
411
412
  'rds.show_all': "Visa alla",
package/src/i18n/tr.ts CHANGED
@@ -406,6 +406,7 @@ export const tr: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Önerilen süzgeçler:",
407
407
  'smart.matching': "Şuna göre süz:",
408
408
  'smart.no_match': "Aramayla eşleşen süzgeç yok; metin tüm sütunlarda aranır.",
409
+ 'smart.understood': "Şöyle anlaşıldı:",
409
410
  'rds.label': "Bölgeler",
410
411
  'rds.region': "Bölge",
411
412
  'rds.show_all': "Tümünü göster",
package/src/i18n/uk.ts CHANGED
@@ -406,6 +406,7 @@ export const uk: Record<MessageKey, string> = {
406
406
  'smart.suggested': "Запропоновані фільтри:",
407
407
  'smart.matching': "Фільтрувати за:",
408
408
  'smart.no_match': "Жоден фільтр не підходить; текст шукається в усіх стовпцях.",
409
+ 'smart.understood': "Зрозуміло як:",
409
410
  'rds.label': "Області",
410
411
  'rds.region': "Область",
411
412
  'rds.show_all': "Показати всі",
package/src/i18n/zh.ts CHANGED
@@ -406,6 +406,7 @@ export const zh: Record<MessageKey, string> = {
406
406
  'smart.suggested': "建议的筛选器:",
407
407
  'smart.matching': "筛选条件:",
408
408
  'smart.no_match': "没有与搜索匹配的筛选器;将在所有列中搜索该文本。",
409
+ 'smart.understood': "理解为:",
409
410
  'rds.label': "区域",
410
411
  'rds.region': "区域",
411
412
  'rds.show_all': "全部显示",
package/src/i18n.ts CHANGED
@@ -433,6 +433,7 @@ const en = {
433
433
  'smart.suggested': 'Suggested filters:',
434
434
  'smart.matching': 'Filter on:',
435
435
  'smart.no_match': 'No filter matches the search; the text is searched in all columns.',
436
+ 'smart.understood': 'Understood as:',
436
437
  'rds.label': 'Regions',
437
438
  'rds.region': 'Region',
438
439
  'rds.show_all': 'Show all',
@@ -1234,6 +1235,7 @@ const nl: Record<MessageKey, string> = {
1234
1235
  'smart.suggested': 'Voorgestelde filters:',
1235
1236
  'smart.matching': 'Filteren op:',
1236
1237
  'smart.no_match': 'Geen filter past bij de zoektekst; de tekst wordt in alle kolommen gezocht.',
1238
+ 'smart.understood': 'Begrepen als:',
1237
1239
  'rds.label': 'Regio\'s',
1238
1240
  'rds.region': 'Regio',
1239
1241
  'rds.show_all': 'Alles tonen',
@@ -11,6 +11,8 @@ import { REPORT_CHART_KINDS } from './charts.ts';
11
11
  import { bindValues, dbg, publicError, stripSemicolon, type PageContext } from './context.ts';
12
12
  import { applyPlan, checkPlan, chipsOf, ChipRefused, editChip, planIsEmpty, removeChip, type Chip, type Column, type Kind, type Plan } from './ir-plan.ts';
13
13
  import { parseQuestion, type Lookup } from './ir-phrases.ts';
14
+ import { applyFacetSettings, clearFacets, facetSettings } from './ask-facets.ts';
15
+ import { describeFacetFilter, reportFacetDefs, type FacetFilter } from './facet-state.ts';
14
16
  import { AGGREGATES, fieldsOf, headingOf, HIGHLIGHT_COLORS, isNumeric, opLabel, OPERATORS, q, reportState, visibleColumns, withComputations } from './report.ts';
15
17
  import { resolveRestRegion } from './rest-sources.ts';
16
18
  import { loadContext, simplePage, txContext, type Req } from './routes.ts';
@@ -37,6 +39,10 @@ import { loadContext, simplePage, txContext, type Req } from './routes.ts';
37
39
  // small form) and Remove; Undo returns to the settings before the last
38
40
  // change. All are buttons of one POST form (CSRF-checked), so they work
39
41
  // without JavaScript; the undo history is kept in the session.
42
+ //
43
+ // (sprint 122) With a faceted search or smart filters region on the same
44
+ // report, a condition one of its facets can hold sets that facet instead of
45
+ // a report filter (ask-facets.ts); the facets' selections are chips too.
40
46
 
41
47
  export { type Column } from './ir-plan.ts';
42
48
 
@@ -108,7 +114,7 @@ async function askColumns(ctx: PageContext, r: Region, params: URLSearchParams)
108
114
  }
109
115
 
110
116
  /** Stored values of the report's text columns matching the candidates (a query parameter): for "only clerks". */
111
- function valueLookup(ctx: PageContext, columns: Column[], src: string): Lookup {
117
+ export function valueLookup(ctx: PageContext, columns: Column[], src: string): Lookup {
112
118
  return async (column, candidates) => {
113
119
  const cols = columns.filter((c) => c.kind === 'text' && !c.computed && (column === null || c.name === column)).slice(0, MAX_LOOKUP_COLUMNS);
114
120
  const cands = [...new Set(candidates.map((x) => x.slice(0, 200).replace(/\0/g, '')).filter(Boolean))].slice(0, MAX_CANDIDATES);
@@ -234,10 +240,14 @@ export const checkAnswer = (json: unknown, columns: Column[]) => checkPlan(json,
234
240
 
235
241
  type T = PageContext['locale']['t'];
236
242
 
237
- function describePlan(p: Plan, t: T, label: (n: string) => string) {
243
+ /** The page's facets on the report (their selections are chips and Ask may set them). */
244
+ const pageFacets = (ctx: PageContext, rid: number) => reportFacetDefs(ctx.page.regions, rid);
245
+
246
+ function describePlan(p: Plan, t: T, label: (n: string) => string, facets: FacetFilter[] = []) {
238
247
  return [
239
248
  ...(p.reset ? [t('report.reset')] : []),
240
249
  ...p.filters.map((f) => `${label(f.column)} ${opLabel(t, f.operator)}${f.value ? ` ${f.value}` : ''}`),
250
+ ...facets.map((f) => describeFacetFilter(f, label(f.column), t)),
241
251
  ...(p.search ? [`"${p.search}"`] : []),
242
252
  ...(p.sort ? [t('ai_filter.sort', { column: `${p.sort.label}${p.desc ? ' ↓' : ''}` })] : []),
243
253
  ...p.highlights.map((h) => `${t('report.highlight')}: ${label(h.column)} ${opLabel(t, h.operator)}${h.value ? ` ${h.value}` : ''}`),
@@ -268,6 +278,8 @@ function chipText(chip: Chip, t: T, label: (n: string) => string, byPos: (pos: n
268
278
  case 'chart': return `${t('report.chart')}: ${t(`chart.${chip.type}`)}, ${label(chip.label)}, ${t(`agg.${chip.fn}`)}: ${label(chip.value)}`;
269
279
  case 'hide': return `${t('report.hidden_column')}: ${label(chip.column)}`;
270
280
  case 'area': case 'near': return t('report.map_area');
281
+ case 'facet': return describeFacetFilter({ kind: 'values', column: chip.column, values: [chip.value], exclude: chip.exclude }, label(chip.column), t);
282
+ case 'facetrange': return describeFacetFilter({ kind: 'range', column: chip.column, from: chip.from, to: chip.to, custom: chip.custom }, label(chip.column), t, chip.def);
271
283
  }
272
284
  }
273
285
 
@@ -287,7 +299,7 @@ export async function renderAiFilter(ctx: PageContext, r: Region): Promise<Raw |
287
299
  <input type="hidden" name="__csrf" value="${ctx.session.csrf_token}"><input type="hidden" name="params" value="${params}"></form>`);
288
300
 
289
301
  // the chips: the report's settings in the URL, each with Edit and Remove
290
- const chips = chipsOf(ctx.params, r.id);
302
+ const chips = chipsOf(ctx.params, r.id, pageFacets(ctx, r.id));
291
303
  let columns: Column[] = [];
292
304
  let computeErrors: Awaited<ReturnType<typeof askColumns>>['errors'] = [];
293
305
  if (chips.length && ctx.client)
@@ -444,7 +456,7 @@ export async function aiFilterRoutes(app: FastifyInstance) {
444
456
  dbg(ctx, 6, 'ai', () => `report settings from the phrases: ${JSON.stringify(plan)}; not understood: ${JSON.stringify(parsed.left)}`);
445
457
  if (planIsEmpty(plan)) throw new AiError('output', [t('ai_filter.no_match'), ...(parsed.left.length ? [t('ai_filter.not_understood', { what: parsed.left.join('; ') })] : [])].join(' '));
446
458
  } else {
447
- const current = chipsOf(params, r.id).map((ch) => chipText(ch, t, label, (pos) => columns.find((c) => c.pos === pos)?.label ?? `#${pos}`)).join('; ');
459
+ const current = chipsOf(params, r.id, pageFacets(ctx, r.id)).map((ch) => chipText(ch, t, label, (pos) => columns.find((c) => c.pos === pos)?.label ?? `#${pos}`)).join('; ');
448
460
  const res = await generate(conf.service!, { system: planSystem(columns, new Date().toISOString().slice(0, 10), current), prompt: question, schema: planSchema(columns), maxTokens: 3000 }, {
449
461
  appId: ctx.app.id, pageNo: ctx.page.page_no, user: ctx.user, source: 'nl2ir', debug: (l, x) => dbg(ctx, l, 'ai', x),
450
462
  });
@@ -452,9 +464,13 @@ export async function aiFilterRoutes(app: FastifyInstance) {
452
464
  dbg(ctx, 6, 'ai', () => `report settings from the question: ${JSON.stringify(plan)}`);
453
465
  if (planIsEmpty(plan)) throw new AiError('output', t('ai_filter.nothing'));
454
466
  }
467
+ // conditions a facet on the page can hold set that facet (the facets of regions the user sees)
468
+ const facets = facetSettings(plan, reportFacetDefs(ctx.page.regions, r.id, ctx.vis?.regions), columns);
469
+ if (plan.reset) clearFacets(params, r.id);
455
470
  applyPlan(params, r.id, plan);
471
+ applyFacetSettings(params, r.id, facets);
456
472
  if (params.toString() !== before) pushUndo(ctx, r.id, before);
457
- ctx.session.state.__FLASH = [t('ai_filter.applied', { what: describePlan(plan, t, label) }), ...(parsed?.left.length ? [t('ai_filter.not_understood', { what: parsed.left.join('; ') })] : [])].join(' ');
473
+ ctx.session.state.__FLASH = [t('ai_filter.applied', { what: describePlan(plan, t, label, facets) }), ...(parsed?.left.length ? [t('ai_filter.not_understood', { what: parsed.left.join('; ') })] : [])].join(' ');
458
474
  } catch (e) {
459
475
  if (e instanceof Forbidden) return refuse(`ai filter: region ${r.id} on page ${ctx.page.page_no}`);
460
476
  ctx.session.state.__FLASH_ERROR = e instanceof AiError ? e.message : await publicError(ctx, e, 'AI report filter');
@@ -476,7 +492,7 @@ export async function aiFilterRoutes(app: FastifyInstance) {
476
492
  await saveState(ctx.session);
477
493
  return back(reply, ctx, r.id, prev === null ? params : new URLSearchParams(prev));
478
494
  }
479
- const chips = chipsOf(params, r.id);
495
+ const chips = chipsOf(params, r.id, pageFacets(ctx, r.id));
480
496
  const which = typeof body.edit === 'string' ? body.edit : typeof body.remove === 'string' ? body.remove : '';
481
497
  const i = /^\d{1,3}$/.test(which) ? Number(which) : -1;
482
498
  const chip = chips[i];
@@ -0,0 +1,72 @@
1
+ import type { Column, Plan } from './ir-plan.ts';
2
+ import { CUSTOM_RANGE, facetKeys, facetParamNames, isFacetParam, rangeValue, validBound, type FacetDef, type FacetFilter } from './facet-state.ts';
3
+
4
+ // (sprint 122, WS-5) "Ask in your own words" on faceted search and smart
5
+ // filters (APEX 26.2: natural language for faceted search and smart filters).
6
+ // A condition that a facet on the page can hold is set on that facet instead
7
+ // of becoming a report filter, so the facet shows it (checked values, a chosen
8
+ // range, a smart filter chip) and its counts follow:
9
+ //
10
+ // job is clerk, job is analyst a checkbox facet: its values (one or more)
11
+ // job is not clerk ... excluded, when the facet allows exclude
12
+ // salary between 1000 and 3000 a range facet with custom ranges: from / to (at least, at most)
13
+ // rating at least 4 a star facet: "4 stars & up"
14
+ //
15
+ // Anything else (greater than, contains, a facet without custom ranges, a
16
+ // column without a facet) stays a report filter. The facets are those of the
17
+ // page's faceted search and smart filters regions on the report (columns
18
+ // checked there); values and bounds become the facets' own URL parameters,
19
+ // which facet-state.ts reads as query parameters, never SQL text.
20
+
21
+ /** Take the conditions the report's facets can hold out of the plan (plan.filters keeps the rest). */
22
+ export function facetSettings(plan: Plan, defs: Map<string, FacetDef>, columns: Column[]): FacetFilter[] {
23
+ const out: FacetFilter[] = [];
24
+ const taken = new Set<string>();
25
+ const byColumn = new Map<string, Plan['filters']>();
26
+ for (const f of plan.filters) if (defs.has(f.column)) byColumn.set(f.column, [...(byColumn.get(f.column) ?? []), f]);
27
+ for (const [column, list] of byColumn) {
28
+ const def = defs.get(column)!;
29
+ const ops = new Set(list.map((f) => f.operator));
30
+ let s: FacetFilter | null = null;
31
+ if (def.type === 'checkbox') {
32
+ const values = [...new Set(list.map((f) => f.value))].filter((v) => v !== '');
33
+ if (values.length === list.length && ops.size === 1 && (ops.has('eq') || (ops.has('ne') && def.exclude)))
34
+ s = { column, kind: 'values', values, exclude: ops.has('ne') };
35
+ } else if (def.type === 'star') {
36
+ const n = Number(list[0].value);
37
+ if (list.length === 1 && ops.has('ge') && Number.isInteger(n) && n >= 1 && n <= def.max) s = { column, kind: 'range', from: String(n), to: '', custom: false };
38
+ } else if (def.custom) {
39
+ const kind = columns.find((c) => c.name === column)?.kind;
40
+ const from = list.find((f) => f.operator === 'ge')?.value ?? '';
41
+ const to = list.find((f) => f.operator === 'le')?.value ?? '';
42
+ if ((kind === 'number' || kind === 'date') && list.length <= 2 && [...ops].every((o) => o === 'ge' || o === 'le') && ops.size === list.length && validBound(from, kind) && validBound(to, kind))
43
+ s = { column, kind: 'range', from, to, custom: true };
44
+ }
45
+ if (s) (out.push(s), taken.add(column));
46
+ }
47
+ plan.filters = plan.filters.filter((f) => !taken.has(f.column));
48
+ return out;
49
+ }
50
+
51
+ /** Set each facet as given (replacing what that facet had). */
52
+ export function applyFacetSettings(params: URLSearchParams, rid: number, settings: FacetFilter[]) {
53
+ const k = facetKeys(rid);
54
+ for (const s of settings) {
55
+ for (const n of facetParamNames(rid, s.column)) params.delete(n);
56
+ if (s.kind === 'values') {
57
+ for (const v of s.values) params.append(k.values + s.column, v);
58
+ if (s.exclude) params.set(k.exclude + s.column, '1');
59
+ } else if (!s.custom) params.set(k.range + s.column, rangeValue(s));
60
+ else {
61
+ params.set(k.range + s.column, CUSTOM_RANGE);
62
+ if (s.from) params.set(k.from + s.column, s.from);
63
+ if (s.to) params.set(k.to + s.column, s.to);
64
+ }
65
+ }
66
+ if (settings.length) params.delete(`r${rid}_p`);
67
+ }
68
+
69
+ /** "Start over" clears the report's facets too. */
70
+ export function clearFacets(params: URLSearchParams, rid: number) {
71
+ for (const n of [...new Set(params.keys())]) if (isFacetParam(rid, n)) params.delete(n);
72
+ }
@@ -1,5 +1,6 @@
1
1
  import { REPORT_CHART_KINDS } from './charts.ts';
2
2
  import { ComputeError, computeNameOk, computeSql } from './compute.ts';
3
+ import { facetFilters, facetKeys, facetParamNames, type FacetDef } from './facet-state.ts';
3
4
  import { AGGREGATES, HIGHLIGHT_COLORS, MAX_COMPUTATIONS, OPERATORS } from './report.ts';
4
5
 
5
6
  // (sprint 112) What "Ask in your own words" may do to an interactive report
@@ -15,7 +16,8 @@ import { AGGREGATES, HIGHLIGHT_COLORS, MAX_COMPUTATIONS, OPERATORS } from './rep
15
16
  //
16
17
  // The settings in force are shown as chips (chipsOf): each one is a URL
17
18
  // parameter value of the report, so a chip can be edited or removed
18
- // (editChip, removeChip) and nothing else is stored.
19
+ // (editChip, removeChip) and nothing else is stored. (sprint 122) The page's
20
+ // facets on the report are chips too (Remove only: the facet region edits them).
19
21
 
20
22
  export type Kind = 'number' | 'date' | 'text' | 'boolean';
21
23
 
@@ -243,12 +245,14 @@ export type Chip =
243
245
  | { kind: 'chart'; key: string; type: string; label: string; fn: string; value: string }
244
246
  | { kind: 'hide'; key: string; column: string }
245
247
  | { kind: 'area'; key: string }
246
- | { kind: 'near'; key: string };
248
+ | { kind: 'near'; key: string }
249
+ | { kind: 'facet'; key: string; column: string; value: string; exclude: boolean }
250
+ | { kind: 'facetrange'; key: string; column: string; from: string; to: string; custom: boolean; def: FacetDef };
247
251
 
248
252
  const MAX_CHIPS = 60;
249
253
 
250
254
  /** The report's settings in the URL as chips (what reportState() reads, in the same limits). */
251
- export function chipsOf(params: URLSearchParams, rid: number): Chip[] {
255
+ export function chipsOf(params: URLSearchParams, rid: number, facets?: Map<string, FacetDef>): Chip[] {
252
256
  const k = (x: string) => `r${rid}_${x}`;
253
257
  const out: Chip[] = [];
254
258
  const q = (params.get(k('q')) ?? '').trim();
@@ -287,6 +291,9 @@ export function chipsOf(params: URLSearchParams, rid: number): Chip[] {
287
291
  for (const x of params.getAll(k('x')).filter(Boolean).slice(0, 100)) out.push({ kind: 'hide', key: `x:${x}`, column: x });
288
292
  if (params.get(k('bb'))) out.push({ kind: 'area', key: 'bb' });
289
293
  if (params.get(k('near'))) out.push({ kind: 'near', key: 'near' });
294
+ for (const f of facets ? facetFilters(params, rid, facets) : [])
295
+ if (f.kind === 'values') for (const value of f.values) out.push({ kind: 'facet', key: `fx:${f.column}:${value}`, column: f.column, value, exclude: f.exclude });
296
+ else out.push({ kind: 'facetrange', key: `fr:${f.column}:${f.from}|${f.to}`, column: f.column, from: f.from, to: f.to, custom: f.custom, def: facets!.get(f.column)! });
290
297
  return out.slice(0, MAX_CHIPS);
291
298
  }
292
299
 
@@ -334,6 +341,13 @@ export function removeChip(params: URLSearchParams, rid: number, chip: Chip) {
334
341
  case 'hide': dropValue(params, k('x'), chip.column); break;
335
342
  case 'area': params.delete(k('bb')); break;
336
343
  case 'near': params.delete(k('near')); break;
344
+ case 'facet': {
345
+ const name = facetKeys(rid).values + chip.column;
346
+ dropValue(params, name, chip.value);
347
+ if (!params.getAll(name).length) params.delete(facetKeys(rid).exclude + chip.column);
348
+ break;
349
+ }
350
+ case 'facetrange': for (const n of facetParamNames(rid, chip.column)) params.delete(n); break;
337
351
  }
338
352
  params.delete(k('p'));
339
353
  params.delete(k('k'));
@@ -1,8 +1,13 @@
1
1
  import { appDateReader } from './items.ts';
2
+ import { valueLookup } from './ai-filter.ts';
3
+ import { applyFacetSettings, facetSettings } from './ask-facets.ts';
4
+ import { parseQuestion } from './ir-phrases.ts';
5
+ import { checkPlan, type Column } from './ir-plan.ts';
6
+ import { headingOf, isNumeric } from './report.ts';
2
7
  import { html, type Raw } from '../html.ts';
3
8
  import { icon } from '../icons.ts';
4
9
  import type { Region } from '../metadata.ts';
5
- import { publicError, type PageContext } from './context.ts';
10
+ import { dbg, publicError, type PageContext } from './context.ts';
6
11
  import { regionUrl } from './report.ts';
7
12
  import { describeFacetFilter, facetDefs, facetFilters, facetKeys, facetParamNames, rangeLabel, rangeValue, type FacetDef, type FacetFilter } from './facet-state.ts';
8
13
  import { facetLabel, facetSource, isFacetSource, rangeCounts, valueCounts } from './facets.ts';
@@ -14,6 +19,12 @@ import { facetLabel, facetSource, isFacetSource, rangeCounts, valueCounts } from
14
19
  // works without JavaScript and can be bookmarked.
15
20
  // config: {"report": <report region id>, "suggestions": 3, "placeholder": "Search or filter…",
16
21
  // "facets": [{"column": "job"}, {"column": "sal", "type": "range", "ranges": [...]}]}
22
+ //
23
+ // (sprint 122, WS-5; APEX 26.2) With "ask": true the typed text is also read
24
+ // as a phrase ("clerks in sales with salary between 1000 and 3000", in the
25
+ // application's language: ir-phrases.ts, no AI service): what this region's
26
+ // facets can hold (ask-facets.ts) is offered as the first suggestion, which
27
+ // sets those facets at once. Values are looked up in the report's own rows.
17
28
 
18
29
  const MAX_SUGGESTIONS = 10;
19
30
 
@@ -110,6 +121,28 @@ export async function renderSmartFilters(ctx: PageContext, r: Region): Promise<R
110
121
  }
111
122
  }
112
123
 
124
+ // (sprint 122) the search term read as a phrase: one suggestion that sets the facets it names
125
+ let understood: Raw | '' = '';
126
+ if (r.config.ask === true && fs.search && ctx.client)
127
+ try {
128
+ const columns: Column[] = defs.map((f) => {
129
+ const oid = fs.cols.get(f.column)!;
130
+ return { name: f.column, label: f.label ?? headingOf(report, f.column, ctx.locale.tr), kind: isNumeric(oid) ? 'number' : [1082, 1114, 1184].includes(oid) ? 'date' : oid === 16 ? 'boolean' : 'text', pos: 0 };
131
+ });
132
+ const parsed = await parseQuestion(fs.search, columns, ctx.locale.lang, valueLookup(ctx, columns, fs.src));
133
+ const settings = facetSettings(checkPlan(parsed.plan, columns), new Map(defs.map((f) => [f.column, f])), columns);
134
+ // a single value the matching suggestions already offer needs no second chip
135
+ const single = settings.length === 1 && settings[0].kind === 'values' && settings[0].values.length === 1 && !settings[0].exclude;
136
+ dbg(ctx, 6, 'smart', () => `"${fs.search}" as facets: ${JSON.stringify(settings)}; not understood: ${JSON.stringify(parsed.left)}`);
137
+ if (settings.length && !(single && !parsed.left.length && suggestions.some((x) => x.f.column === settings[0].column)))
138
+ understood = html`<div class="sf-suggestions sf-understood">
139
+ <span class="sf-suggest-title" id="${formId}_u">${t('smart.understood')}</span>
140
+ <ul class="sf-chips" aria-labelledby="${formId}_u"><li><a class="chip chip-suggest" href="${regionUrl(ctx, report, (p) => { applyFacetSettings(p, report.id, settings); p.delete(qName); })}">${settings.map((x, i) => html`${i ? ' · ' : ''}${describeFacetFilter(x, facetLabel(ctx, defs.find((d) => d.column === x.column)!), t, defs.find((d) => d.column === x.column))}`)}</a></li></ul>
141
+ </div>`;
142
+ } catch (e) {
143
+ dbg(ctx, 4, 'smart', () => `"${fs.search}" not read as a phrase: ${(e as Error).message}`);
144
+ }
145
+
113
146
  // GET form: the search term replaces the old one; every other parameter stays
114
147
  const keep = [...ctx.params.entries()].filter(([name]) => ![qName, page, 'clear', 'cs'].includes(name));
115
148
  ctx.detached.push(
@@ -128,12 +161,13 @@ export async function renderSmartFilters(ctx: PageContext, r: Region): Promise<R
128
161
  ? html`<a class="sf-clear" href="${regionUrl(ctx, report, (p) => { p.delete(qName); p.delete(page); for (const f of defs) for (const n of facetParamNames(report.id, f.column)) p.delete(n); })}">${t('facets.clear')}</a>`
129
162
  : ''}
130
163
  </div>
164
+ ${understood}
131
165
  ${suggestions.length
132
166
  ? html`<div class="sf-suggestions">
133
167
  <span class="sf-suggest-title" id="${formId}_s">${fs.search ? t('smart.matching') : t('smart.suggested')}</span>
134
168
  <ul class="sf-chips" aria-labelledby="${formId}_s">${suggestions.map((s) => html`<li><a class="chip chip-suggest" href="${s.href}">${s.label} <span class="facet-count">${s.n}</span></a></li>`)}</ul>
135
169
  </div>`
136
- : fs.search && defs.some((f) => f.type === 'checkbox')
170
+ : fs.search && !understood && defs.some((f) => f.type === 'checkbox')
137
171
  ? html`<p class="muted sf-none">${t('smart.no_match')}</p>`
138
172
  : ''}
139
173
  ${errors}