@xpert-ai/plugin-live-dashboard 0.3.0 → 0.4.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.
- package/.xpertai-plugin/plugin.json +10 -2
- package/README.md +70 -0
- package/assets/branding/cover-v1.prompt.txt +27 -0
- package/assets/branding/cover-v1.webp +0 -0
- package/assets/previews/customer-brief.png +0 -0
- package/assets/previews/profit-atlas.png +0 -0
- package/assets/previews/trend-workspace.png +0 -0
- package/dist/index.js +14 -1
- package/dist/lib/agent.schema.d.ts +43 -37
- package/dist/lib/agent.schema.js +2 -1
- package/dist/lib/app-config.d.ts +62 -0
- package/dist/lib/app-config.js +38 -0
- package/dist/lib/artifact-type.provider.d.ts +15 -0
- package/dist/lib/artifact-type.provider.js +78 -0
- package/dist/lib/assistant-template.d.ts +2 -0
- package/dist/lib/assistant-template.js +7 -0
- package/dist/lib/content.provider.js +13 -5
- package/dist/lib/dashboard-navigation.d.ts +58 -14
- package/dist/lib/dashboard-navigation.js +11 -10
- package/dist/lib/dashboard-view.schema.d.ts +197 -46
- package/dist/lib/dashboard-view.schema.js +8 -1
- package/dist/lib/dashboard.service.d.ts +39 -2
- package/dist/lib/dashboard.service.js +52 -28
- package/dist/lib/document-libraries.d.ts +1 -1
- package/dist/lib/document-libraries.js +3 -2
- package/dist/lib/document-network.d.ts +1 -1
- package/dist/lib/document-network.js +2 -6
- package/dist/lib/editing-feedback.d.ts +5 -0
- package/dist/lib/editing-feedback.js +19 -0
- package/dist/lib/editing-patch.d.ts +22 -0
- package/dist/lib/editing-patch.js +46 -0
- package/dist/lib/editing-session.d.ts +167 -0
- package/dist/lib/editing-session.js +53 -0
- package/dist/lib/editing.d.ts +92 -60
- package/dist/lib/editing.js +36 -24
- package/dist/lib/html-guidance.d.ts +1 -1
- package/dist/lib/html-guidance.js +1 -1
- package/dist/lib/middleware.js +48 -20
- package/dist/lib/monitor.d.ts +70 -0
- package/dist/lib/monitor.js +101 -0
- package/dist/lib/plugin.js +5 -1
- package/dist/lib/project.d.ts +106 -0
- package/dist/lib/project.js +17 -0
- package/dist/lib/projects.schema.d.ts +49 -0
- package/dist/lib/projects.schema.js +7 -0
- package/dist/lib/projects.service.d.ts +23 -0
- package/dist/lib/projects.service.js +65 -0
- package/dist/lib/prompt-workflows.d.ts +3 -2
- package/dist/lib/prompt-workflows.js +17 -3
- package/dist/lib/provider-options.controller.d.ts +10 -0
- package/dist/lib/provider-options.controller.js +49 -0
- package/dist/lib/resource-card.js +1 -1
- package/dist/lib/runtime-context.d.ts +3 -0
- package/dist/lib/runtime-context.js +13 -0
- package/dist/lib/save-evidence.d.ts +1 -1
- package/dist/lib/templates.d.ts +2 -0
- package/dist/lib/templates.js +55 -0
- package/dist/lib/view.provider.d.ts +97 -7
- package/dist/lib/view.provider.js +39 -10
- package/dist/libraries/TREND-WORKSPACE-ICONS-LICENSE.txt +43 -0
- package/dist/libraries/catalog.json +1 -1
- package/dist/remote/app.css +1 -1
- package/dist/remote/app.js +33 -33
- package/dist/remote/build-manifest.json +118 -32
- package/dist/sandbox-actions/action.json +1 -1
- package/dist/sandbox-actions/bundle/host.js +2 -2
- package/dist/sandbox-actions/bundle/resource-cache.mjs +2 -1
- package/dist/sandbox-actions/bundle/validate.mjs +1 -1
- package/docs/docs.json +7 -0
- package/docs/frontend-libraries.mdx +12 -4
- package/docs/html-mode.md +3 -3
- package/docs/quick-start-acceptance.mdx +50 -0
- package/docs/quick-start.mdx +64 -0
- package/docs/superstore.mdx +38 -0
- package/docs/team-sharing.mdx +6 -2
- package/docs/trend-workspace-acceptance.mdx +43 -0
- package/docs/trend-workspace.mdx +30 -0
- package/docs/verification.mdx +4 -2
- package/docs/visual-styles-acceptance.mdx +40 -0
- package/docs/visual-styles.mdx +46 -0
- package/package.json +25 -18
- package/scripts/import-prompts.mjs +108 -0
- package/skills/live-dashboard/SKILL.md +27 -3
- package/skills/live-dashboard/examples/README.md +25 -0
- package/skills/live-dashboard/examples/catalog.json +79 -0
- package/skills/live-dashboard/examples/production-quality/README.md +25 -0
- package/skills/live-dashboard/examples/production-quality/dashboard.html +129 -0
- package/skills/live-dashboard/examples/production-quality/definition.json +67 -0
- package/skills/live-dashboard/examples/production-quality/demo.csv +7 -0
- package/skills/live-dashboard/examples/production-quality/demo.json +44 -0
- package/skills/live-dashboard/examples/production-quality/expected.json +26 -0
- package/skills/live-dashboard/examples/production-quality/preview.png +0 -0
- package/skills/live-dashboard/examples/production-quality/query.json +53 -0
- package/skills/live-dashboard/examples/regional-sales/README.md +25 -0
- package/skills/live-dashboard/examples/regional-sales/dashboard-create.json +35 -0
- package/skills/live-dashboard/examples/regional-sales/definition.json +35 -0
- package/skills/live-dashboard/examples/regional-sales/demo.csv +5 -0
- package/skills/live-dashboard/examples/regional-sales/demo.json +18 -0
- package/skills/live-dashboard/examples/regional-sales/expected.json +19 -0
- package/skills/live-dashboard/examples/regional-sales/preview.png +0 -0
- package/skills/live-dashboard/examples/regional-sales/query.json +45 -0
- package/skills/live-dashboard/examples/sales-overview/README.md +25 -0
- package/skills/live-dashboard/examples/sales-overview/dashboard.html +129 -0
- package/skills/live-dashboard/examples/sales-overview/definition.json +57 -0
- package/skills/live-dashboard/examples/sales-overview/demo.csv +7 -0
- package/skills/live-dashboard/examples/sales-overview/demo.json +38 -0
- package/skills/live-dashboard/examples/sales-overview/expected.json +22 -0
- package/skills/live-dashboard/examples/sales-overview/preview.png +0 -0
- package/skills/live-dashboard/examples/sales-overview/query.json +52 -0
- package/skills/live-dashboard/examples/superstore/README.md +64 -0
- package/skills/live-dashboard/examples/superstore/THIRD_PARTY_LICENSE.txt +207 -0
- package/skills/live-dashboard/examples/superstore/build_data.py +155 -0
- package/skills/live-dashboard/examples/superstore/build_pages.py +129 -0
- package/skills/live-dashboard/examples/superstore/checks.json +104 -0
- package/skills/live-dashboard/examples/superstore/customers-mobile-dark.png +0 -0
- package/skills/live-dashboard/examples/superstore/customers-select.png +0 -0
- package/skills/live-dashboard/examples/superstore/customers.html +316 -0
- package/skills/live-dashboard/examples/superstore/customers.png +0 -0
- package/skills/live-dashboard/examples/superstore/customers.queries.json +512 -0
- package/skills/live-dashboard/examples/superstore/expected.json +4069 -0
- package/skills/live-dashboard/examples/superstore/import.json +200 -0
- package/skills/live-dashboard/examples/superstore/orders.csv +10195 -0
- package/skills/live-dashboard/examples/superstore/overview-mobile-dark.png +0 -0
- package/skills/live-dashboard/examples/superstore/overview-select.png +0 -0
- package/skills/live-dashboard/examples/superstore/overview.html +310 -0
- package/skills/live-dashboard/examples/superstore/overview.png +0 -0
- package/skills/live-dashboard/examples/superstore/overview.queries.json +636 -0
- package/skills/live-dashboard/examples/superstore/page.js +109 -0
- package/skills/live-dashboard/examples/superstore/profitability-mobile-dark.png +0 -0
- package/skills/live-dashboard/examples/superstore/profitability-select.png +0 -0
- package/skills/live-dashboard/examples/superstore/profitability.html +307 -0
- package/skills/live-dashboard/examples/superstore/profitability.png +0 -0
- package/skills/live-dashboard/examples/superstore/profitability.queries.json +334 -0
- package/skills/live-dashboard/examples/superstore/provenance.json +24 -0
- package/skills/live-dashboard/examples/superstore/semantic-model.json +220 -0
- package/skills/live-dashboard/examples/superstore/test_data.py +62 -0
- package/skills/live-dashboard/references/html-runtime.md +1 -1
- package/skills/live-dashboard/themes/README.md +50 -0
- package/skills/live-dashboard/themes/customer-brief/README.md +47 -0
- package/skills/live-dashboard/themes/customer-brief/charts.js +17 -0
- package/skills/live-dashboard/themes/customer-brief/layout.html +22 -0
- package/skills/live-dashboard/themes/customer-brief/theme.css +108 -0
- package/skills/live-dashboard/themes/profit-atlas/README.md +43 -0
- package/skills/live-dashboard/themes/profit-atlas/charts.js +30 -0
- package/skills/live-dashboard/themes/profit-atlas/layout.html +19 -0
- package/skills/live-dashboard/themes/profit-atlas/theme.css +75 -0
- package/skills/live-dashboard/themes/trend-workspace/ICON_LICENSE.txt +43 -0
- package/skills/live-dashboard/themes/trend-workspace/README.md +144 -0
- package/skills/live-dashboard/themes/trend-workspace/charts.js +60 -0
- package/skills/live-dashboard/themes/trend-workspace/icons.js +11 -0
- package/skills/live-dashboard/themes/trend-workspace/layout.html +45 -0
- package/skills/live-dashboard/themes/trend-workspace/select.js +127 -0
- package/skills/live-dashboard/themes/trend-workspace/theme.css +137 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Superstore 企业 BI — v1
|
|
2
|
+
|
|
3
|
+
一个 ChatKit 项目,三个看板:`overview.html`(零售经营总览)、`profitability.html`(商品盈利)、`customers.html`(客户与退货)。这是 Tableau 的虚构教学数据,必须保留页面演示标识。页面参考经典企业经营分析的信息组织,自行实现;不是第三方产品截图。
|
|
4
|
+
|
|
5
|
+
## 数据准备(管理员一次完成)
|
|
6
|
+
|
|
7
|
+
1. 阅读 `provenance.json` 和 `THIRD_PARTY_LICENSE.txt`。`orders.csv` 是固定官方工作簿的确定性转换结果,10,194 行;不要把整个文件送入模型上下文。
|
|
8
|
+
2. 在 Data Xpert 中为有权限的工作空间绑定一个 PostgreSQL 演示数据源,通过“导入”上传 `orders.csv`。`import.json` 是字段定义:金额为 NUMERIC(20,6),邮编为文本,`returned_order_id` 允许 NULL。使用一个尚不存在的表名;不要选择删除/覆盖已有表。API 自动化也必须先检查表是否存在,不能重复追加。
|
|
9
|
+
3. 创建新的 SQL 语义模型,以 `semantic-model.json` 为结构模板,按实际元数据调整数据库/schema/表名;保留技术 Cube 名 `SuperstoreOrders` 和字段名。核对所有度量与维度后执行草稿验证,发布到有权限的业务域。
|
|
10
|
+
4. 将发布后的本体资源授权给当前 Live Dashboard Assistant,配置 Data Xpert integration 和当前查看者的只读查询权限。数据权限不会由安装本样例自动授予。
|
|
11
|
+
5. 通过 Data Xpert 真实查询核对 `expected.json`。全量订单 5,111、客户 804、退货订单 296;金额核对到 6 位小数。未经验证不能宣布“数据准备完成”。
|
|
12
|
+
|
|
13
|
+
此配方使用 `data-xpert.ontology`,不是 `file.table`。缺少已发布模型时报告这一前置步骤;不得用三个入门配方、小量自造数据或浏览器内嵌数据替代。数据准备不需要增加新的 Project View 或后台定时任务。
|
|
14
|
+
|
|
15
|
+
## 助理制作步骤
|
|
16
|
+
|
|
17
|
+
先读 [主题选择说明](../../themes/README.md),再读目标页的独立主题指南。三个可选风格都使用键盘可用的双层标签选择器;CSS、选择器和图表组件随技能安装,通过版本和内容哈希固定的文档库加载。
|
|
18
|
+
|
|
19
|
+
| 页面 | 风格及指南 | libraries |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| `overview.html` | [Trend Workspace](../../themes/trend-workspace/README.md):浅蓝 KPI 侧栏、上下趋势 | `["echarts","trend-workspace"]` |
|
|
22
|
+
| `profitability.html` | [Profit Atlas](../../themes/profit-atlas/README.md):深色横向指标、大散点图、带正负号的利润排名 | `["echarts","profit-atlas"]` |
|
|
23
|
+
| `customers.html` | [Customer Brief](../../themes/customer-brief/README.md):暖纸色、衬线标题、分组退货指标 | `["echarts","customer-brief"]` |
|
|
24
|
+
|
|
25
|
+
用户要求美化已有看板时,逐个 `dashboard_open` / `dashboard_update`,保留 Artifact、Binding、控件和已有 HTML ID,显式传入目标页对应的 libraries。先读当前编辑副本,用有界精确编辑替换业务布局,不能新建副本。没有要求重设计时保留已有风格。用于其他数据时须重新匹配字段和口径,不能只替换标题而保留 Superstore 字段。
|
|
26
|
+
|
|
27
|
+
1. 先阅读主技能和 HTML runtime/lifecycle。确认当前 ChatKit Project。用户请求整个案例时制作三个草稿;只请求其中一个时仅制作该页。
|
|
28
|
+
2. 使用 `dashboard_list_sources` 和 Data Xpert analytics definition 的 connections/inspect/register/discover 流程,找到当前 Assistant 已授权的 **SuperstoreOrders**。记录实际 definitionId/versionId、resourceId、entityRef;不能沿用别的 Assistant/项目的 ID。
|
|
29
|
+
3. 用 `read_skill_file` 阅读目标页的 `*.queries.json`(相对技能目录定位)。每个 binding 是查询计划,尚未包含 source;替换 payload 中发现得到的 resourceId/entityRef,并添加本次 source。字段类型、可空性、action schema 以实际发现结果为准;稳定保留 binding.id、output.datasetId、output.fields[].id 和控件 ID,HTML 使用这些名字。
|
|
30
|
+
4. 每个查询包含同样的 year/region/category 参数。空字符串表示全部,通过 contains 匹配;allowedValues 严格限定工作簿中真实存在的枚举。总计 Binding 的 dimensions 必须为空,让后端执行 COUNT DISTINCT;不能把月度、子品类或分群的订单/客户数相加冒充全量。
|
|
31
|
+
5. 使用 `dashboard_preview_binding` 预览每个完整 Binding。先读小文件 `checks.json`,对总计 Binding 用 `dashboard_test_filter` 验证全量、West、East、2024、Furniture 和组合筛选;`controls` 原样传全部三个值,`expectations` 选择实际存在的字段,`fieldId` 设为该字段名,`oneOf` 使用对应 case 的 summary 中原样字符串值。Data Xpert 的 int64/decimal 查询结果是字符串,oneOf 必须同类型。不要把全量计数当成区域计数;不要为验证筛选反复修改 Binding 默认值。分组查询与 `expected.json` 对照,并完成 preview 返回的 validation.suggestedCall。
|
|
32
|
+
6. 调用 `dashboard_libraries`,按上表只选择 ECharts 和该页一个主题。使用 `read_skill_file` 读取目标 HTML **完整内容**(不是只读前一段);若改用 sandbox_read_file 必须读取全部行。逐页读取、写入并保存,完成一页后再处理下一页,不在一次模型输出中重写三页。原样保留 HTML/CSS/JS,不压缩或简化。写入当前项目的新相对路径,例如 `superstore-v1/overview.html`。若路径已有不同内容,改用新的文件名,不覆盖别的 Artifact。使用 SandboxFile 工具;不需要重写模板代码或复制 10,194 行数据到 Sandbox。
|
|
33
|
+
7. 对三个页面分别调用 `dashboard_create_html`:标题为 `Superstore · 零售经营总览`、`Superstore · 商品盈利分析`、`Superstore · 客户与退货分析`,传入各自全部 previewIds、原样 controls 和 libraries。预检失败则按具体错误修复后重试,不省略 Binding 或控件。**三个页面的 Binding 集合不同,不能只把标题换掉。**
|
|
34
|
+
8. 收到成功的草稿回执后报告三个 Artifact 和修订,用户通过回执卡片/级联选择器打开。不要重新打开未改变的看板来确认保存;不要自动发布。
|
|
35
|
+
|
|
36
|
+
## 总计筛选基准(当前固定数据版本)
|
|
37
|
+
|
|
38
|
+
执行 `dashboard_test_filter` 时用下表当前筛选对应的值,不猜测常见 Superstore 版本的计数。int64 和 decimal 都使用字符串。全量参数都是空字符串。先验证 Orders 与 Customers;金额同时与真实返回值核对。
|
|
39
|
+
|
|
40
|
+
| year | region | category | Orders | Customers | Sales | Profit |
|
|
41
|
+
| --- | --- | --- | --- | --- | --- | --- |
|
|
42
|
+
| `""` | `""` | `""` | `"5111"` | `"804"` | `"2326534.354300"` | `"292296.814600"` |
|
|
43
|
+
| `""` | `"West"` | `""` | `"1635"` | `"686"` | `"739813.608500"` | `"110798.817000"` |
|
|
44
|
+
| `""` | `"East"` | `""` | `"1475"` | `"685"` | `"691828.168000"` | `"94883.260300"` |
|
|
45
|
+
| `"2024"` | `""` | `""` | `"1723"` | `"704"` | `"745567.531200"` | `"95926.347600"` |
|
|
46
|
+
| `""` | `""` | `"Furniture"` | `"1819"` | `"714"` | `"754747.761300"` | `"19729.995600"` |
|
|
47
|
+
| `"2024"` | `"West"` | `"Furniture"` | `"202"` | `"184"` | `"74155.119500"` | `"2892.830000"` |
|
|
48
|
+
|
|
49
|
+
West 的 Orders 必须为 `"1635"`,不是其他版本的示例计数。若校验失败,读取 `checks.json` 与查询结果查明差异,不要通过更改默认筛选反复重试同一错误期望。
|
|
50
|
+
|
|
51
|
+
## 指标与交互
|
|
52
|
+
|
|
53
|
+
- Sales/Profit/Quantity 为订单行求和;Orders/Customers 为当前筛选的不同订单/客户数。
|
|
54
|
+
- 利润率 = 总利润 / 总销售额;客单价 = 总销售额 / 订单数。分母为零不显示伪造比率。
|
|
55
|
+
- Returns 原表 800 行,先按 Order ID 去重成 296 个订单再关联。ReturnedOrders 忽略 NULL,ReturnedSales 是退货订单关联的销售额,**不是退款或损失**。
|
|
56
|
+
- 年份、区域、品类改变时查询当前页的所有 Binding。各看板控件状态独立;同一页所有面板同范围。
|
|
57
|
+
- 查询错误、截断、无结果时清除之前的指标,保留明确状态;不要继续展示上一筛选的数值。
|
|
58
|
+
- 原值以 decimal 字符串传输,金额展示到两位;绘图及比率计算在验证安全数值范围后转换为 Number。
|
|
59
|
+
|
|
60
|
+
## 重建与验收
|
|
61
|
+
|
|
62
|
+
开发者安装 `xlrd==2.0.2` 后运行 `python build_data.py --workbook <下载文件>`;哈希不一致会停止。再运行 `python build_pages.py`,将本目录的业务布局与运行时组合成三个 HTML;主题组件由每页对应的受控文档库注入。Agent 直接使用已安装的组件与配方,不需要运行构建器。原始数据版本、CSV 哈希和许可见 `provenance.json`。
|
|
63
|
+
|
|
64
|
+
验收:全量 → West → East → 全量,2024、Furniture、组合筛选,刷新、空结果、权限失败、截断、窄屏和深色主题。比较所有图表和总计,确认项目双向同步与 Artifact 归属。浏览器模拟检查只证明页面生命周期;真实 Data Xpert 查询与安装后界面验收另行记录。
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Apache License Version 2.0
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Salesforce, Inc.
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Apache License
|
|
7
|
+
Version 2.0, January 2004
|
|
8
|
+
http://www.apache.org/licenses/
|
|
9
|
+
|
|
10
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
11
|
+
|
|
12
|
+
1. Definitions.
|
|
13
|
+
|
|
14
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
15
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
16
|
+
|
|
17
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
18
|
+
the copyright owner that is granting the License.
|
|
19
|
+
|
|
20
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
21
|
+
other entities that control, are controlled by, or are under common
|
|
22
|
+
control with that entity. For the purposes of this definition,
|
|
23
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
24
|
+
direction or management of such entity, whether by contract or
|
|
25
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
26
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
27
|
+
|
|
28
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
29
|
+
exercising permissions granted by this License.
|
|
30
|
+
|
|
31
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
32
|
+
including but not limited to software source code, documentation
|
|
33
|
+
source, and configuration files.
|
|
34
|
+
|
|
35
|
+
"Object" form shall mean any form resulting from mechanical
|
|
36
|
+
transformation or translation of a Source form, including but
|
|
37
|
+
not limited to compiled object code, generated documentation,
|
|
38
|
+
and conversions to other media types.
|
|
39
|
+
|
|
40
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
41
|
+
Object form, made available under the License, as indicated by a
|
|
42
|
+
copyright notice that is included in or attached to the work
|
|
43
|
+
(an example is provided in the Appendix below).
|
|
44
|
+
|
|
45
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
46
|
+
form, that is based on (or derived from) the Work and for which the
|
|
47
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
48
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
49
|
+
of this License, Derivative Works shall not include works that remain
|
|
50
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
51
|
+
the Work and Derivative Works thereof.
|
|
52
|
+
|
|
53
|
+
"Contribution" shall mean any work of authorship, including
|
|
54
|
+
the original version of the Work and any modifications or additions
|
|
55
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
56
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
57
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
58
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
59
|
+
means any form of electronic, verbal, or written communication sent
|
|
60
|
+
to the Licensor or its representatives, including but not limited to
|
|
61
|
+
communication on electronic mailing lists, source code control systems,
|
|
62
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
63
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
64
|
+
excluding communication that is conspicuously marked or otherwise
|
|
65
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
66
|
+
|
|
67
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
68
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
69
|
+
subsequently incorporated within the Work.
|
|
70
|
+
|
|
71
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
72
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
73
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
74
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
75
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
76
|
+
Work and such Derivative Works in Source or Object form.
|
|
77
|
+
|
|
78
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
79
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
80
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
81
|
+
(except as stated in this section) patent license to make, have made,
|
|
82
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
83
|
+
where such license applies only to those patent claims licensable
|
|
84
|
+
by such Contributor that are necessarily infringed by their
|
|
85
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
86
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
87
|
+
institute patent litigation against any entity (including a
|
|
88
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
89
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
90
|
+
or contributory patent infringement, then any patent licenses
|
|
91
|
+
granted to You under this License for that Work shall terminate
|
|
92
|
+
as of the date such litigation is filed.
|
|
93
|
+
|
|
94
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
95
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
96
|
+
modifications, and in Source or Object form, provided that You
|
|
97
|
+
meet the following conditions:
|
|
98
|
+
|
|
99
|
+
(a) You must give any other recipients of the Work or
|
|
100
|
+
Derivative Works a copy of this License; and
|
|
101
|
+
|
|
102
|
+
(b) You must cause any modified files to carry prominent notices
|
|
103
|
+
stating that You changed the files; and
|
|
104
|
+
|
|
105
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
106
|
+
that You distribute, all copyright, patent, trademark, and
|
|
107
|
+
attribution notices from the Source form of the Work,
|
|
108
|
+
excluding those notices that do not pertain to any part of
|
|
109
|
+
the Derivative Works; and
|
|
110
|
+
|
|
111
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
112
|
+
distribution, then any Derivative Works that You distribute must
|
|
113
|
+
include a readable copy of the attribution notices contained
|
|
114
|
+
within such NOTICE file, excluding those notices that do not
|
|
115
|
+
pertain to any part of the Derivative Works, in at least one
|
|
116
|
+
of the following places: within a NOTICE text file distributed
|
|
117
|
+
as part of the Derivative Works; within the Source form or
|
|
118
|
+
documentation, if provided along with the Derivative Works; or,
|
|
119
|
+
within a display generated by the Derivative Works, if and
|
|
120
|
+
wherever such third-party notices normally appear. The contents
|
|
121
|
+
of the NOTICE file are for informational purposes only and
|
|
122
|
+
do not modify the License. You may add Your own attribution
|
|
123
|
+
notices within Derivative Works that You distribute, alongside
|
|
124
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
125
|
+
that such additional attribution notices cannot be construed
|
|
126
|
+
as modifying the License.
|
|
127
|
+
|
|
128
|
+
You may add Your own copyright statement to Your modifications and
|
|
129
|
+
may provide additional or different license terms and conditions
|
|
130
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
131
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
132
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
133
|
+
the conditions stated in this License.
|
|
134
|
+
|
|
135
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
136
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
137
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
138
|
+
this License, without any additional terms or conditions.
|
|
139
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
140
|
+
the terms of any separate license agreement you may have executed
|
|
141
|
+
with Licensor regarding such Contributions.
|
|
142
|
+
|
|
143
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
144
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
145
|
+
except as required for reasonable and customary use in describing the
|
|
146
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
147
|
+
|
|
148
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
149
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
150
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
151
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
152
|
+
implied, including, without limitation, any warranties or conditions
|
|
153
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
154
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
155
|
+
appropriateness of using or redistributing the Work and assume any
|
|
156
|
+
risks associated with Your exercise of permissions under this License.
|
|
157
|
+
|
|
158
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
159
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
160
|
+
unless required by applicable law (such as deliberate and grossly
|
|
161
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
162
|
+
liable to You for damages, including any direct, indirect, special,
|
|
163
|
+
incidental, or consequential damages of any character arising as a
|
|
164
|
+
result of this License or out of the use or inability to use the
|
|
165
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
166
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
167
|
+
other commercial damages or losses), even if such Contributor
|
|
168
|
+
has been advised of the possibility of such damages.
|
|
169
|
+
|
|
170
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
171
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
172
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
173
|
+
or other liability obligations and/or rights consistent with this
|
|
174
|
+
License. However, in accepting such obligations, You may act only
|
|
175
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
176
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
177
|
+
defend, and hold each Contributor harmless for any liability
|
|
178
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
179
|
+
of your accepting any such warranty or additional liability.
|
|
180
|
+
|
|
181
|
+
END OF TERMS AND CONDITIONS
|
|
182
|
+
|
|
183
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
184
|
+
|
|
185
|
+
To apply the Apache License to your work, attach the following
|
|
186
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
187
|
+
replaced with your own identifying information. (Don't include
|
|
188
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
189
|
+
comment syntax for the file format. We also recommend that a
|
|
190
|
+
file or class name and description of purpose be included on the
|
|
191
|
+
same "printed page" as the copyright notice for easier
|
|
192
|
+
identification within third-party archives.
|
|
193
|
+
|
|
194
|
+
Copyright {yyyy} {name of copyright owner}
|
|
195
|
+
|
|
196
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
197
|
+
you may not use this file except in compliance with the License.
|
|
198
|
+
You may obtain a copy of the License at
|
|
199
|
+
|
|
200
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
201
|
+
|
|
202
|
+
Unless required by applicable law or agreed to in writing, software
|
|
203
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
204
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
205
|
+
See the License for the specific language governing permissions and
|
|
206
|
+
limitations under the License.
|
|
207
|
+
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Rebuild the pinned Tableau teaching dataset (requires xlrd==2.0.2).
|
|
2
|
+
|
|
3
|
+
Usage: python build_data.py --workbook /path/to/Sample-Superstore.xls
|
|
4
|
+
The original workbook is not modified. Only files in this recipe are generated.
|
|
5
|
+
"""
|
|
6
|
+
import argparse
|
|
7
|
+
import csv
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
from collections import defaultdict
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from decimal import Decimal
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
SHA256 = 'add4e193479cae8e9f22bfa734dd8bb706355dce38353967668f4e2b6643d19c'
|
|
16
|
+
ROOT = Path(__file__).resolve().parent
|
|
17
|
+
FIELDS = [
|
|
18
|
+
'row_id', 'order_id', 'order_date', 'ship_date', 'ship_mode', 'customer_id',
|
|
19
|
+
'customer_name', 'segment', 'country', 'city', 'state', 'postal_code', 'region',
|
|
20
|
+
'product_id', 'category', 'sub_category', 'product_name', 'sales', 'quantity',
|
|
21
|
+
'discount', 'profit', 'order_year', 'order_month', 'regional_manager',
|
|
22
|
+
'returned', 'returned_order_id', 'returned_sales',
|
|
23
|
+
]
|
|
24
|
+
NUMERIC = {'sales', 'profit', 'discount', 'returned_sales'}
|
|
25
|
+
INTEGER = {'row_id', 'quantity'}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def money(value):
|
|
29
|
+
# Excel binary floating-point noise is normalized at six decimal places.
|
|
30
|
+
return Decimal(str(value)).quantize(Decimal('0.000001'))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def read_workbook(path):
|
|
34
|
+
if hashlib.sha256(path.read_bytes()).hexdigest() != SHA256:
|
|
35
|
+
raise ValueError('Workbook SHA-256 differs from the pinned Tableau release')
|
|
36
|
+
import xlrd
|
|
37
|
+
book = xlrd.open_workbook(str(path))
|
|
38
|
+
orders, returns, people = [book.sheet_by_name(name) for name in ('Orders', 'Returns', 'People')]
|
|
39
|
+
if orders.nrows - 1 != 10194 or orders.ncols != 21:
|
|
40
|
+
raise ValueError('Unexpected Orders shape')
|
|
41
|
+
return_ids = {str(returns.cell_value(i, 1)) for i in range(1, returns.nrows)}
|
|
42
|
+
if len(return_ids) != 296 or returns.nrows - 1 != 800:
|
|
43
|
+
raise ValueError('Unexpected Returns shape')
|
|
44
|
+
managers = {}
|
|
45
|
+
for i in range(1, people.nrows):
|
|
46
|
+
name, region = people.row_values(i)
|
|
47
|
+
if region in managers:
|
|
48
|
+
raise ValueError('Duplicate region manager would multiply fact rows')
|
|
49
|
+
managers[region] = name
|
|
50
|
+
rows = []
|
|
51
|
+
for i in range(1, orders.nrows):
|
|
52
|
+
values = orders.row_values(i)
|
|
53
|
+
row = dict(zip(FIELDS[:21], values))
|
|
54
|
+
for key in ('order_date', 'ship_date'):
|
|
55
|
+
row[key] = xlrd.xldate_as_datetime(row[key], book.datemode).date().isoformat()
|
|
56
|
+
for key in NUMERIC - {'returned_sales'}:
|
|
57
|
+
row[key] = money(row[key])
|
|
58
|
+
for key in INTEGER:
|
|
59
|
+
if row[key] != int(row[key]):
|
|
60
|
+
raise ValueError('Non-integer identifier or quantity')
|
|
61
|
+
row[key] = int(row[key])
|
|
62
|
+
# Postal codes are labels, never numbers or measures.
|
|
63
|
+
row['postal_code'] = str(int(row['postal_code'])).zfill(5) if isinstance(row['postal_code'], (int, float)) else str(row['postal_code'])
|
|
64
|
+
row['order_year'], row['order_month'] = row['order_date'][:4], row['order_date'][:7]
|
|
65
|
+
row['regional_manager'] = managers[row['region']]
|
|
66
|
+
returned = row['order_id'] in return_ids
|
|
67
|
+
row['returned'] = 'Yes' if returned else 'No'
|
|
68
|
+
row['returned_order_id'] = row['order_id'] if returned else None
|
|
69
|
+
row['returned_sales'] = row['sales'] if returned else Decimal('0.000000')
|
|
70
|
+
rows.append(row)
|
|
71
|
+
if len({r['row_id'] for r in rows}) != len(rows):
|
|
72
|
+
raise ValueError('Duplicate order-line primary key')
|
|
73
|
+
if return_ids - {r['order_id'] for r in rows}:
|
|
74
|
+
raise ValueError('Unmatched return order')
|
|
75
|
+
return rows
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def aggregate(rows):
|
|
79
|
+
total = lambda field: str(sum((r[field] for r in rows), Decimal(0)).quantize(Decimal('0.000001')))
|
|
80
|
+
return {
|
|
81
|
+
'Sales': total('sales'), 'Profit': total('profit'),
|
|
82
|
+
'Quantity': sum(r['quantity'] for r in rows),
|
|
83
|
+
'Orders': len({r['order_id'] for r in rows}),
|
|
84
|
+
'Customers': len({r['customer_id'] for r in rows}),
|
|
85
|
+
'ReturnedOrders': len({r['returned_order_id'] for r in rows if r['returned_order_id']}),
|
|
86
|
+
'ReturnedSales': total('returned_sales'),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def write_json(name, value):
|
|
91
|
+
(ROOT / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def build(rows):
|
|
95
|
+
with (ROOT / 'orders.csv').open('w', newline='') as handle:
|
|
96
|
+
writer = csv.DictWriter(handle, fieldnames=FIELDS, lineterminator='\n')
|
|
97
|
+
writer.writeheader()
|
|
98
|
+
writer.writerows(rows)
|
|
99
|
+
dimensions = {
|
|
100
|
+
'OrderYear': ('order_year', '年份'), 'OrderMonth': ('order_month', '订单月份'),
|
|
101
|
+
'Region': ('region', '区域'), 'Category': ('category', '品类'),
|
|
102
|
+
'SubCategory': ('sub_category', '子品类'), 'Segment': ('segment', '客户分群'),
|
|
103
|
+
'Returned': ('returned', '退货标记'), 'RegionalManager': ('regional_manager', '区域经理'),
|
|
104
|
+
}
|
|
105
|
+
measures = [
|
|
106
|
+
('Sales', 'sales', 'sum', '销售额(USD)'),
|
|
107
|
+
('Profit', 'profit', 'sum', '利润(USD)'),
|
|
108
|
+
('Quantity', 'quantity', 'sum', '商品件数'),
|
|
109
|
+
('Orders', 'order_id', 'distinct-count', '订单数'),
|
|
110
|
+
('Customers', 'customer_id', 'distinct-count', '客户数'),
|
|
111
|
+
('ReturnedOrders', 'returned_order_id', 'distinct-count', '退货订单数'),
|
|
112
|
+
('ReturnedSales', 'returned_sales', 'sum', '退货关联销售额(USD,非退款)'),
|
|
113
|
+
]
|
|
114
|
+
write_json('semantic-model.json', {'cubes': [{
|
|
115
|
+
'name': 'SuperstoreOrders', 'caption': 'Superstore 订单分析(演示)',
|
|
116
|
+
'fact': {'type': 'table', 'table': {'name': 'superstore_orders_v1', 'schema': 'public'}},
|
|
117
|
+
'defaultMeasure': 'Sales',
|
|
118
|
+
'measures': [{'name': n, 'column': c, 'aggregator': a, 'caption': label,
|
|
119
|
+
'datatype': 'Numeric', 'visible': True} for n, c, a, label in measures],
|
|
120
|
+
'dimensions': [{'name': name, 'caption': label, 'hierarchies': [{
|
|
121
|
+
'name': name, 'hasAll': True,
|
|
122
|
+
'levels': [{'name': name, 'column': column, 'type': 'String', 'uniqueMembers': True}],
|
|
123
|
+
}]} for name, (column, label) in dimensions.items()],
|
|
124
|
+
}]})
|
|
125
|
+
cases = {'all': {}, 'west': {'region': 'West'}, 'east': {'region': 'East'},
|
|
126
|
+
'year2024': {'order_year': '2024'}, 'furniture': {'category': 'Furniture'},
|
|
127
|
+
'west2024furniture': {'region': 'West', 'order_year': '2024', 'category': 'Furniture'},
|
|
128
|
+
'empty': {'order_year': '1999'}}
|
|
129
|
+
expected = {'sourceSha256': SHA256, 'orderLines': len(rows), 'cases': {}}
|
|
130
|
+
for key, filters in cases.items():
|
|
131
|
+
selected = [r for r in rows if all(r[k] == v for k, v in filters.items())]
|
|
132
|
+
item = {'filters': filters, 'rows': len(selected), 'totals': aggregate(selected), 'groups': {}}
|
|
133
|
+
for dim, (column, _) in dimensions.items():
|
|
134
|
+
groups = defaultdict(list)
|
|
135
|
+
for row in selected:
|
|
136
|
+
groups[row[column]].append(row)
|
|
137
|
+
item['groups'][dim] = [{dim: member, **aggregate(group)} for member, group in sorted(groups.items())]
|
|
138
|
+
expected['cases'][key] = item
|
|
139
|
+
write_json('expected.json', expected)
|
|
140
|
+
write_json('import.json', [{
|
|
141
|
+
'catalog': 'public', 'name': 'superstore_orders_v1', 'withHeader': 1,
|
|
142
|
+
'columns': [{'name': f, 'fieldName': f, 'isKey': f == 'row_id',
|
|
143
|
+
'type': 'decimal' if f in NUMERIC else 'integer' if f in INTEGER else 'varchar',
|
|
144
|
+
**({'precision': 20, 'fraction': 6} if f in NUMERIC else {'length': 512} if f not in INTEGER else {})}
|
|
145
|
+
for f in FIELDS],
|
|
146
|
+
}])
|
|
147
|
+
print(json.dumps({'rows': len(rows), 'totals': aggregate(rows),
|
|
148
|
+
'csvSha256': hashlib.sha256((ROOT / 'orders.csv').read_bytes()).hexdigest()}))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
if __name__ == '__main__':
|
|
152
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
153
|
+
parser.add_argument('--workbook', type=Path, required=True)
|
|
154
|
+
args = parser.parse_args()
|
|
155
|
+
build(read_workbook(args.workbook))
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Generate self-contained, inspectable HTML recipes and query plans. No data rows are embedded."""
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
ROOT = Path(__file__).resolve().parent
|
|
6
|
+
THEME = ROOT.parent.parent / 'themes' / 'trend-workspace'
|
|
7
|
+
OPTIONS = {
|
|
8
|
+
'year': [['', '全部年份']] + [[str(y), str(y)] for y in range(2021, 2025)],
|
|
9
|
+
'region': [['', '全部区域']] + [[r, r] for r in ['Central', 'East', 'South', 'West']],
|
|
10
|
+
'category': [['', '全部品类']] + [[c, c] for c in ['Furniture', 'Office Supplies', 'Technology']],
|
|
11
|
+
}
|
|
12
|
+
CONTROLS = [{'controlId': key, 'label': label, 'type': 'string', 'defaultValue': '',
|
|
13
|
+
'allowedValues': [value for value, _ in OPTIONS[key]]}
|
|
14
|
+
for key, label in [('year', '年份'), ('region', '区域'), ('category', '品类')]]
|
|
15
|
+
PAGES = [
|
|
16
|
+
{'key': 'overview', 'title': '零售经营总览', 'description': '从经营结果到区域与品类贡献',
|
|
17
|
+
'bindings': {'summary': [], 'trend': ['OrderMonth'], 'regions': ['Region'], 'categories': ['Category']},
|
|
18
|
+
'panels': ['月度销售与利润', '区域销售贡献'], 'notes': ['USD · 独立总计保留订单和客户去重口径', 'USD · 同一筛选范围'],
|
|
19
|
+
'dimension': '品类', 'table': '品类经营表现'},
|
|
20
|
+
{'key': 'profitability', 'title': '商品盈利分析', 'description': '找到贡献利润的商品,以及高销售背后的亏损',
|
|
21
|
+
'bindings': {'summary': [], 'subcategories': ['SubCategory']},
|
|
22
|
+
'panels': ['子品类利润排序', '销售额与利润关系'], 'notes': ['USD · 红色表示负利润', '每个点代表一个子品类,悬停查看金额'],
|
|
23
|
+
'dimension': '子品类', 'table': '子品类盈利明细'},
|
|
24
|
+
{'key': 'customers', 'title': '客户与退货分析', 'description': '客户结构、订单价值与退货订单关联表现',
|
|
25
|
+
'bindings': {'summary': [], 'segments': ['Segment'], 'regions': ['Region']},
|
|
26
|
+
'panels': ['客户分群销售贡献', '各区域退货订单数'], 'notes': ['USD · 客户数在当前范围内去重', '按 Order ID 去重;不代表退货商品件数'],
|
|
27
|
+
'dimension': '客户分群', 'table': '客户分群与退货明细'},
|
|
28
|
+
]
|
|
29
|
+
checks = []
|
|
30
|
+
for name, case in json.loads((ROOT / 'expected.json').read_text())['cases'].items():
|
|
31
|
+
if name == 'empty':
|
|
32
|
+
continue # 1999 is an SDK/data test, outside the page's allowed years.
|
|
33
|
+
checks.append({'case': name, 'controls': {
|
|
34
|
+
'year': case['filters'].get('order_year', ''),
|
|
35
|
+
'region': case['filters'].get('region', ''),
|
|
36
|
+
'category': case['filters'].get('category', '')},
|
|
37
|
+
'summary': {key: str(value) for key, value in case['totals'].items()}})
|
|
38
|
+
(ROOT / 'checks.json').write_text(json.dumps(checks, ensure_ascii=False, indent=2) + '\n')
|
|
39
|
+
CSS = '/* Theme CSS is supplied by the pinned trend-workspace document library. */'
|
|
40
|
+
JS = (ROOT / 'page.js').read_text()
|
|
41
|
+
for page in PAGES:
|
|
42
|
+
key = page['key']
|
|
43
|
+
measures = ['Sales', 'Orders', 'Customers', 'ReturnedOrders', 'ReturnedSales'] if key == 'customers' else ['Sales', 'Profit', 'Orders', 'Customers']
|
|
44
|
+
config = {**page, 'bindings': list(page['bindings']), 'options': OPTIONS, 'measures': measures}
|
|
45
|
+
metrics = [('销售额(USD)', '订单行销售额合计'), ('利润(USD)', '订单行利润合计'),
|
|
46
|
+
('利润率', '利润 ÷ 销售额'), ('订单数', 'Order ID 去重'), ('客户数', 'Customer ID 去重')]
|
|
47
|
+
if key == 'customers':
|
|
48
|
+
metrics = [('客户数', 'Customer ID 去重'), ('订单数', 'Order ID 去重'),
|
|
49
|
+
('客单价(USD)', '销售额 ÷ 订单数'), ('退货订单数', '退货 Order ID 去重'), ('退货订单占比', '退货订单数 ÷ 订单数')]
|
|
50
|
+
filters = ''.join(f'<div class="filter-field"><label for="filter-{c["controlId"]}">{c["label"]}</label><select id="filter-{c["controlId"]}" data-dashboard-control="{c["controlId"]}" disabled></select></div>' for c in CONTROLS)
|
|
51
|
+
metric_blocks = [f'<div class="metric"><p>{label}</p><output id="metric-{i}">—</output><small>{note}</small></div>' for i, (label, note) in enumerate(metrics)]
|
|
52
|
+
cards = ''.join(metric_blocks)
|
|
53
|
+
panels = ''.join(f'<section class="panel"><h2>{page["panels"][i]}</h2><p class="note">{page["notes"][i]}</p><div id="chart-{name}" class="chart" role="img" aria-label="{page["panels"][i]}"></div></section>' for i, name in enumerate(['primary', 'secondary']))
|
|
54
|
+
headings = [page['dimension'], '销售额(USD)', '利润(USD)', '利润率']
|
|
55
|
+
if key == 'profitability':
|
|
56
|
+
headings += ['订单数', '客户数']
|
|
57
|
+
if key == 'customers':
|
|
58
|
+
headings = [page['dimension'], '销售额(USD)', '订单数', '客户数', '退货订单数', '退货订单占比', '退货关联销售额(USD)']
|
|
59
|
+
heads = ''.join(f'<th scope="col">{heading}</th>' for heading in headings)
|
|
60
|
+
table = f'<section class="details"><h2>{page["table"]}</h2><p class="note">USD · 同一筛选范围</p><div class="table-scroll" tabindex="0" role="region" aria-label="{page["table"]}"><table><thead><tr>{heads}</tr></thead><tbody id="details-rows"></tbody></table></div></section>'
|
|
61
|
+
if key == 'overview':
|
|
62
|
+
content = f'''<section class="hero"><h2>月度经营趋势</h2><p class="note">2021–2024 · USD · 销售额与利润分别使用独立刻度</p>
|
|
63
|
+
<h3 class="chart-heading">销售额(USD)</h3><div id="chart-primary" class="chart" role="img" aria-label="月度销售额"></div>
|
|
64
|
+
<h3 class="chart-heading profit">利润(USD)</h3><div id="chart-profit" class="chart chart-profit" role="img" aria-label="月度利润"></div></section>
|
|
65
|
+
<div class="lower-grid"><section class="region-panel"><h2>区域销售贡献</h2><p class="note">USD · 按销售额从高到低</p><div id="chart-secondary" class="chart" role="img" aria-label="区域销售贡献"></div></section>{table}</div>'''
|
|
66
|
+
else:
|
|
67
|
+
content = f'<div class="plots">{panels}</div><div class="full-details">{table}</div>'
|
|
68
|
+
html = f'''<!doctype html>
|
|
69
|
+
<html lang="zh-Hans"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Superstore · {page['title']}</title><style>{CSS}</style></head>
|
|
70
|
+
<body data-page="{key}" data-dashboard-theme="trend-workspace@1"><main class="workspace">
|
|
71
|
+
<aside class="metric-rail"><header><span class="demo">Superstore 演示数据</span><h1>{page['title']}</h1><p class="description">{page['description']}</p></header><section class="metrics" aria-label="当前筛选主要指标">{cards}</section></aside>
|
|
72
|
+
<div class="analysis"><div class="filters" aria-label="分析筛选">{filters}</div>{content}
|
|
73
|
+
<p id="status" class="status" role="status">正在加载…</p>
|
|
74
|
+
<details class="methodology"><summary>数据与指标口径</summary><p>来源:Tableau Superstore 虚构教学工作簿,2021–2024 年,金额单位 USD。退货表先按订单去重,再关联订单行。退货关联销售额不等于退款或收入损失。利润率为合计利润除以合计销售额;订单数与客户数由后端在当前范围内去重,不能累加分组计数。各看板筛选状态独立。</p></details></div>
|
|
75
|
+
<footer><span>2021–2024 · 演示数据 · Data Xpert</span><span id="freshness">尚无当前查询结果</span></footer></main>
|
|
76
|
+
<script>const config={json.dumps(config, ensure_ascii=False, indent=2)};
|
|
77
|
+
{JS}</script></body></html>
|
|
78
|
+
'''
|
|
79
|
+
if key != 'overview':
|
|
80
|
+
theme = 'profit-atlas' if key == 'profitability' else 'customer-brief'
|
|
81
|
+
prefix = 'atlas' if key == 'profitability' else 'brief'
|
|
82
|
+
global_name = 'ProfitAtlas' if key == 'profitability' else 'CustomerBrief'
|
|
83
|
+
description = '看清销售与利润之间的差距' if key == 'profitability' else '理解客户结构,关注退货表现'
|
|
84
|
+
header = f'<header class="{prefix}-header"><div><h1>{page["title"]}</h1><p class="description">{description}</p><span class="demo">Superstore 演示数据 · 2021–2024</span></div><div class="filters" aria-label="分析筛选">{filters}</div></header>'
|
|
85
|
+
if key == 'profitability':
|
|
86
|
+
summary = f'<section class="atlas-metrics" aria-label="当前筛选主要指标">{cards}</section>'
|
|
87
|
+
panel_specs = [('secondary', '销售额与利润关系', '每个点代表一个子品类,悬停查看金额'), ('primary', '子品类利润排名', 'USD · 红色表示负利润')]
|
|
88
|
+
table = table.replace('USD · 同一筛选范围', '按利润升序 · 完整明细可滚动查看')
|
|
89
|
+
else:
|
|
90
|
+
summary = f'<section class="brief-metrics" aria-label="当前筛选主要指标"><div class="brief-primary-metrics">{"".join(metric_blocks[:3])}</div><div class="brief-return-metrics">{metric_blocks[4]}{metric_blocks[3]}</div></section>'
|
|
91
|
+
panel_specs = [('primary', '<span class="section-number" aria-hidden="true">01</span>客户分群销售贡献', 'USD · 客户数在当前范围内去重'), ('secondary', '<span class="section-number" aria-hidden="true">02</span>各区域退货订单数', '按 Order ID 去重;不代表退货商品件数')]
|
|
92
|
+
variant_panels = ''.join(f'<section class="panel"><h2>{title}</h2><p class="note">{note}</p><div id="chart-{name}" class="chart" role="img" aria-label="{page["panels"][0 if name == "primary" else 1]}"></div></section>' for name, title, note in panel_specs)
|
|
93
|
+
script = JS.replace('window.TrendWorkspace', f'window.{global_name}').replace('TrendWorkspaceCharts', 'DashboardCharts')
|
|
94
|
+
if key == 'customers':
|
|
95
|
+
script = script.replace("dimension:'Segment',measure:'Sales',label:'销售额(USD)'", "dimension:'Segment',measure:'Sales',label:'销售额(USD)',palette:['blue','segment-two','segment-three']")
|
|
96
|
+
script = script.replace("label:'退货订单数',decimals:0", "label:'退货订单数',decimals:0,palette:['returns']")
|
|
97
|
+
html = f'''<!doctype html>
|
|
98
|
+
<html lang="zh-Hans"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Superstore · {page['title']}</title></head>
|
|
99
|
+
<body data-page="{key}" data-dashboard-theme="{theme}@1"><main class="workspace">{header}{summary}
|
|
100
|
+
<div class="analysis"><div class="{prefix}-plots">{variant_panels}</div><div class="full-details">{table}</div>
|
|
101
|
+
<p id="status" class="status" role="status">正在加载…</p>
|
|
102
|
+
<details class="methodology"><summary>数据与指标口径</summary><p>来源:Tableau Superstore 虚构教学工作簿,2021–2024 年,金额单位 USD。退货表先按订单去重,再关联订单行。退货关联销售额不等于退款或收入损失。利润率为合计利润除以合计销售额;订单数与客户数由后端在当前范围内去重,不能累加分组计数。各看板筛选状态独立。</p></details></div>
|
|
103
|
+
<footer><span>2021–2024 · 演示数据 · Data Xpert</span><span id="freshness">尚无当前查询结果</span></footer></main>
|
|
104
|
+
<script>const config={json.dumps(config, ensure_ascii=False, indent=2)};
|
|
105
|
+
{script}</script></body></html>
|
|
106
|
+
'''
|
|
107
|
+
# Sandbox readers bound individual lines: keep the complete recipe inspectable.
|
|
108
|
+
markup, scripts = html.split('<script>', 1)
|
|
109
|
+
html = markup.replace('><', '>\n<') + '<script>' + scripts
|
|
110
|
+
assert max(len(line.encode('utf-8')) for line in html.splitlines()) <= 500
|
|
111
|
+
(ROOT / (key + '.html')).write_text(html)
|
|
112
|
+
queries = []
|
|
113
|
+
for binding_id, dimensions in page['bindings'].items():
|
|
114
|
+
fields = [{'id': d, 'sourceField': d, 'label': d, 'logicalType': 'string', 'role': 'dimension', 'nullable': False} for d in dimensions]
|
|
115
|
+
fields += [{'id': m, 'sourceField': m, 'label': m, 'logicalType': 'decimal' if m in ['Sales', 'Profit', 'ReturnedSales'] else 'int64',
|
|
116
|
+
'role': 'measure', 'nullable': m in ['Sales', 'Profit', 'ReturnedSales']} for m in measures]
|
|
117
|
+
queries.append({
|
|
118
|
+
'id': binding_id, 'providerId': 'data-xpert.ontology', 'operation': 'action', 'contractVersion': 1,
|
|
119
|
+
'payload': {'resourceId': '<discovered-resource-id>', 'actionTypeCode': 'sql.query_cube_slice',
|
|
120
|
+
'target': {'entityTypeCode': 'semantic_cube', 'entityRef': '<published-model-id>::SuperstoreOrders'},
|
|
121
|
+
'params': {'dimensions': dimensions, 'measures': measures,
|
|
122
|
+
'filters': [{'field': d, 'op': 'contains', 'value': ''} for d in ['OrderYear', 'Region', 'Category']], 'limit': 100},
|
|
123
|
+
'parameterPaths': {c['controlId']: ['filters', str(i), 'value'] for i, c in enumerate(CONTROLS)}},
|
|
124
|
+
'parameters': [{'name': c['controlId'], 'controlId': c['controlId'], 'type': 'string', 'required': True,
|
|
125
|
+
'defaultValue': '', 'allowedValues': c['allowedValues']} for c in CONTROLS],
|
|
126
|
+
'output': {'datasetId': binding_id, 'fields': fields, 'grain': dimensions},
|
|
127
|
+
})
|
|
128
|
+
(ROOT / (key + '.queries.json')).write_text(json.dumps({'controls': CONTROLS, 'bindings': queries}, ensure_ascii=False, indent=2)+'\n')
|
|
129
|
+
print('Generated three HTML recipes and query plans (no embedded data).')
|