@akinon/pz-rate-review 0.0.0-stage → 2.0.152-rc.1

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 (76) hide show
  1. package/.prettierrc +13 -0
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +269 -2
  4. package/jest/__mocks__/akinon-next-api.js +10 -0
  5. package/jest/__mocks__/akinon-next-button.js +6 -0
  6. package/jest/__mocks__/akinon-next-hooks.js +6 -0
  7. package/jest/__mocks__/akinon-next-image.js +6 -0
  8. package/jest/__mocks__/akinon-next-loader-spinner.js +6 -0
  9. package/jest/__mocks__/akinon-next-modal.js +12 -0
  10. package/jest/__mocks__/next-auth-react.js +3 -0
  11. package/jest/__mocks__/settings.js +7 -0
  12. package/jest/settings.d.ts +4 -0
  13. package/jest/setup.ts +1 -0
  14. package/jest/tsconfig.json +19 -0
  15. package/jest.config.js +53 -0
  16. package/package.json +30 -4
  17. package/src/__tests__/settings.test.ts +56 -0
  18. package/src/api/__tests__/helpers.ts +142 -0
  19. package/src/api/__tests__/ratings-and-images.test.ts +347 -0
  20. package/src/api/__tests__/reviews.test.ts +691 -0
  21. package/src/api/commerce.ts +57 -0
  22. package/src/api/errors.ts +173 -0
  23. package/src/api/extension.ts +172 -0
  24. package/src/api/index.ts +313 -0
  25. package/src/api/queries.ts +68 -0
  26. package/src/api/serializers.ts +127 -0
  27. package/src/api/validation.ts +347 -0
  28. package/src/attrs.ts +7 -0
  29. package/src/data/__tests__/endpoints.test.ts +117 -0
  30. package/src/data/endpoints.ts +126 -0
  31. package/src/data/server.ts +64 -0
  32. package/src/hooks/__tests__/use-rate-review-translation.test.tsx +51 -0
  33. package/src/hooks/use-product-rating-summary.ts +46 -0
  34. package/src/hooks/use-rate-review-settings.ts +6 -0
  35. package/src/hooks/use-rate-review-translation.ts +15 -0
  36. package/src/i18n/__tests__/defaults.test.ts +40 -0
  37. package/src/i18n/en.ts +75 -0
  38. package/src/i18n/index.ts +29 -0
  39. package/src/i18n/tr.ts +75 -0
  40. package/src/i18n/types.ts +71 -0
  41. package/src/index.ts +73 -0
  42. package/src/renderer.ts +190 -0
  43. package/src/settings.ts +77 -0
  44. package/src/theme/__tests__/theme.test.tsx +509 -0
  45. package/src/theme/create.ts +28 -0
  46. package/src/theme/designer-samples.ts +108 -0
  47. package/src/theme/index.ts +38 -0
  48. package/src/theme/options.ts +61 -0
  49. package/src/theme/order-items-block.tsx +175 -0
  50. package/src/theme/parts.ts +123 -0
  51. package/src/theme/product-reviews-section.tsx +118 -0
  52. package/src/theme/rating-badge-block.tsx +110 -0
  53. package/src/theme/settings.ts +40 -0
  54. package/src/theme/use-theme-review-product.ts +61 -0
  55. package/src/types.ts +148 -0
  56. package/src/utils/__tests__/format.test.ts +79 -0
  57. package/src/utils/__tests__/json-ld.test.ts +78 -0
  58. package/src/utils/error-code.ts +34 -0
  59. package/src/utils/format.ts +25 -0
  60. package/src/utils/json-ld.ts +58 -0
  61. package/src/utils/review-window.ts +13 -0
  62. package/src/views/__tests__/order-item-rate-action.test.tsx +137 -0
  63. package/src/views/__tests__/plp-ratings.test.tsx +75 -0
  64. package/src/views/__tests__/rating-summary.test.tsx +124 -0
  65. package/src/views/__tests__/renderer.test.tsx +454 -0
  66. package/src/views/__tests__/review-form-modal.test.tsx +309 -0
  67. package/src/views/__tests__/review-list.test.tsx +107 -0
  68. package/src/views/__tests__/stars.test.tsx +59 -0
  69. package/src/views/order-item-rate-action.tsx +150 -0
  70. package/src/views/plp-ratings.tsx +134 -0
  71. package/src/views/product-rate-review.tsx +120 -0
  72. package/src/views/rating-badge.tsx +101 -0
  73. package/src/views/rating-summary.tsx +196 -0
  74. package/src/views/review-form-modal.tsx +479 -0
  75. package/src/views/review-list.tsx +313 -0
  76. package/src/views/stars.tsx +164 -0
package/.prettierrc ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "bracketSameLine": false,
3
+ "tabWidth": 2,
4
+ "singleQuote": true,
5
+ "jsxSingleQuote": false,
6
+ "bracketSpacing": true,
7
+ "semi": true,
8
+ "useTabs": false,
9
+ "arrowParens": "always",
10
+ "endOfLine": "lf",
11
+ "proseWrap": "never",
12
+ "trailingComma": "none"
13
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # @akinon/pz-rate-review
2
+
3
+ ## 2.0.152-rc.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 97d29893: ZERO-5220: add the pz-rate-review plugin for the Rate & Review extension
8
+ - ad5240c4: ZERO-5254: add custom render and theme editor support to pz-rate-review
9
+ - Updated dependencies [97d29893]
10
+ - Updated dependencies [ad5240c4]
11
+ - @akinon/next@2.0.152-rc.1
12
+ - @akinon/pz-theme@2.0.152-rc.1
package/README.md CHANGED
@@ -1,3 +1,270 @@
1
- # Temporary Holding Version
1
+ # @akinon/pz-rate-review
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared rate & review plugin for Project Zero Next storefronts. It talks to the Akinon Rate & Review extension from the server only: the extension base url and Basic auth credentials never reach the browser, the customer identity comes from the storefront session, and the public review list is limited to approved reviews with a whitelisted field set.
4
+
5
+ ## Installation
6
+
7
+ The template mounts the components on the product, listing and order pages but does not ship the package. Install it with the CLI, add `pz-rate-review` to the list in `src/plugins.js`, then add the route files and the environment variables described below. Until the plugin is listed, the mounts render nothing.
8
+
9
+ ```bash
10
+ npx @akinon/projectzero@latest --plugins
11
+ ```
12
+
13
+ ## Environment
14
+
15
+ | Variable | Required | Purpose |
16
+ | --- | --- | --- |
17
+ | `RATE_REVIEW_API_URL` | yes | Base url of the Rate & Review extension |
18
+ | `RATE_REVIEW_BASIC_AUTH_USER` / `RATE_REVIEW_BASIC_AUTH_PASS` | one of the two options | Basic auth pair |
19
+ | `RATE_REVIEW_BASIC_AUTH_TOKEN` | one of the two options | Ready `base64(user:pass)` value, used instead of the pair when set |
20
+
21
+ None of them is prefixed with `NEXT_PUBLIC_`. A missing value answers every request with `500` and the `configuration` error code.
22
+
23
+ ## Route files
24
+
25
+ Add the route files under `src/app/api/rate-review/` and pass the session reader of your core version.
26
+
27
+ ```ts
28
+ import { auth } from 'auth';
29
+ import { createRateReviewHandlers } from '@akinon/pz-rate-review/src/api';
30
+
31
+ export const { GET, POST } = createRateReviewHandlers({ auth }).reviews;
32
+ ```
33
+
34
+ | File | Export | Handler |
35
+ | ------------------------------ | ------------- | ----------------- |
36
+ | `reviews/route.ts` | `GET`, `POST` | `.reviews` |
37
+ | `reviews/[id]/route.ts` | `PATCH` | `.review` |
38
+ | `reviews/[id]/images/route.ts` | `POST` | `.reviewImages` |
39
+ | `my-reviews/route.ts` | `GET` | `.myReviews` |
40
+ | `rating-history/route.ts` | `GET` | `.ratingHistory` |
41
+ | `grouped-ratings/route.ts` | `GET` | `.groupedRatings` |
42
+
43
+ `auth` must resolve to the storefront session (`null` when signed out). With next-auth 5 that is the `auth` export of `src/auth.ts`; with next-auth 4 pass `() => getServerSession(authOptions)`.
44
+
45
+ ## Settings
46
+
47
+ Configure the plugin under `plugins['pz-rate-review']` in `settings.js`. Every key is optional.
48
+
49
+ | Key | Default | Meaning |
50
+ | --- | --- | --- |
51
+ | `level` | `'base_code'` | Which product code the public list and the grouped ratings are keyed by (`'sku'` or `'base_code'`) |
52
+ | `plpRating` | `true` | Serves grouped ratings for product listings; `false` answers `404` |
53
+ | `maskAuthorName` | `true` | Masks the author name on the storefront side as a second layer over the extension's own masking |
54
+ | `imageUpload` | `false` | Enables image upload for a review that is still waiting for moderation |
55
+ | `imageUploadLimits` | `{ maxFiles: 3, maxSizeMb: 5, mimeTypes: ['image/jpeg', 'image/png', 'image/webp'] }` | Enforced on the server before the files reach the extension |
56
+ | `orderNumberRequired` | `true` | Requires the Commerce order id of a delivered order on creation |
57
+ | `reviewWindowDays` | `0` | Days after the order date during which a review can be created; `0` means no limit. Enforced on the server and mirrored by the order line button |
58
+ | `consentRequired` | `false` | Adds a mandatory consent checkbox to the form and refuses a creation without `consent: true` |
59
+ | `reviewMaxLength` | `250` | Review text limit, capped at the extension's 250 characters |
60
+ | `titleEnabled` | `true` | Accepts an optional title |
61
+ | `pageSize` | `5` | Default page size of the lists, capped at 50 |
62
+ | `isPrivated` | `false` | Forwarded to the extension as `is_privated` on creation; a private review is listed without an author name |
63
+ | `privacyChoice` | `false` | Lets the customer choose `is_privated` with a checkbox in the form, `isPrivated` being the preselected value |
64
+
65
+ ## Endpoints
66
+
67
+ | Method and path | Session | Notes |
68
+ | --- | --- | --- |
69
+ | `GET /api/rate-review/reviews?base_code=…` (or `sku=…`) | no | Approved reviews only; `page`, `limit`, `ordering` (`-created_date`, `created_date`, `-rating`, `rating`); response `{ count, page, page_size, has_next, results }` |
70
+ | `POST /api/rate-review/reviews` | yes | Body `{ sku, base_code, product_name, order_id?, rating, title?, review, consent?, is_privated? }`; identity and `rating_types` are set on the server, `consent` is required by `consentRequired` and `is_privated` is read only with `privacyChoice` |
71
+ | `PATCH /api/rate-review/reviews/{id}` | yes | Own review that is still `waiting`; body `{ rating?, title?, review? }` |
72
+ | `POST /api/rate-review/reviews/{id}/images` | yes | Multipart `file` fields; own review that is still `waiting`; answers `{ images }` |
73
+ | `GET /api/rate-review/my-reviews` | yes | The customer's reviews in every status, optionally filtered by `order_number` or `sku` |
74
+ | `GET /api/rate-review/rating-history?sku=…` | no | `{ average, count, distribution }` |
75
+ | `GET /api/rate-review/grouped-ratings?codes=a,b` | no | `{ [code]: { average, count } }`, up to 60 codes |
76
+
77
+ Public reviews expose `id`, `title`, `review`, `rating`, `author_name`, `images`, `useful` and `created_date`. The customer's own reviews add `status` and `product` instead of the author name.
78
+
79
+ ### Errors
80
+
81
+ Every error answers `{ error: { code, message, details? } }` with no caching. Codes: `unauthorized` (401), `validation` (400, `details` names the fields), `profile_incomplete` (422, `details` lists the missing profile fields), `not_owner` and `order_not_owned` (403), `not_found` and `feature_disabled` (404), `review_exists` (409, with `review: { id, status }`), `review_locked` (409) and `review_window_closed` (409, `details.days`), `configuration` (500), `upstream` (the extension's own 4xx status, or 502 when it is unreachable, fails or answers without JSON), `internal` (500).
82
+
83
+ ## Components
84
+
85
+ All components are client components exported from the package entry and registered in `PluginModule`; `PluginModule` passes the `plugins['pz-rate-review']` block as the `settings` prop, which every component also accepts directly. Each component takes a `classNames` object whose keys map to its inner elements and are merged with Tailwind classes. Mount `PluginModule` from a client component (`'use client'`): the `Component` enum is not available to server components, so on a server page wrap the call in a small client view as the template does for the product page.
86
+
87
+ | Component | Where | Props |
88
+ | --- | --- | --- |
89
+ | `ProductRateReview` | Product page section | `product` (`sku`, `base_code`), `summary?`, `reviews?`, `pageSize?`, `allowSorting?`, `showHeading?`, `showSummary?` |
90
+ | `RateReviewBadge` | Product page header | `product`, `summary?`, `href?` (defaults to the section anchor), `size?`, `showCount?`, `fallback?` |
91
+ | `RateReviewSummary` | Average, count and distribution bars | `product`, `summary?` |
92
+ | `RateReviewList` | Approved reviews with load more and optional sorting | `product`, `reviews?` (preloaded first page), `pageSize?`, `allowSorting?` |
93
+ | `RateReviewStars` | Read only or interactive stars | `value`, `onChange?`, `size?`, `label?` |
94
+ | `RateReviewPlpProvider` | Wraps a product grid, batches the grouped ratings request | `products` (`sku`, `base_code` each), `ratings?` |
95
+ | `RateReviewPlpBadge` | Product card | `product` (`sku`, `base_code`), `size?`, `showCount?`, `fallback?` |
96
+ | `OrderItemRateAction` | Order detail line | `orderId`, `orderNumber`, `orderDate?` (ISO, for `reviewWindowDays`), `product` (`sku`, `base_code`, `name`), `review?` (preloaded own review, `null` for none) |
97
+ | `RateReviewModal` | Review form (create or edit) | `open`, `setOpen`, `product`, `orderId?`, `review?`, `onSuccess?` |
98
+
99
+ `fallback` is what the badges render while there is nothing to show (no data yet or no reviews); it defaults to nothing. `summary`, `reviews`, `ratings` and `review` are preloaded data: when one is given the component renders it without a request (the list queries again for further pages or another ordering).
100
+
101
+ Every component also takes `attrs`, an object with the same keys as its `classNames` whose values are attribute maps spread onto the matching element (`attrs={{ item: { 'data-analytics': 'review' } }}`). The theme entry uses it to stamp pz-theme parts; the modal shell takes no attributes because it is a portal, use `renderModal` there.
102
+
103
+ Every component also takes `attrs`, an object with the same keys as its `classNames` whose values are attribute maps spread onto the matching element (`attrs={{ item: { 'data-analytics': 'review' } }}`). The theme entry uses it to stamp pz-theme parts; the modal shell takes no attributes because it is a portal, use `renderModal` there.
104
+
105
+ ```tsx
106
+ import { PluginModule, Component } from '@akinon/next/components/plugin-module';
107
+
108
+ <PluginModule
109
+ component={Component.ProductRateReview}
110
+ props={{
111
+ product: { sku: product.sku, base_code: product.base_code },
112
+ allowSorting: true
113
+ }}
114
+ />;
115
+ ```
116
+
117
+ Render `RateReviewModal` only while it is open (or give it a `key`), because it initialises its form from the `review` prop on mount.
118
+
119
+ ### Custom render
120
+
121
+ Every component also takes a `renderer` object whose keys replace one piece of the default markup with the brand's own. A key that is left out keeps the default, so a brand overrides only what it needs and the data flow, the texts and the requests stay in the package. The `renderContainer`, `renderList`, `renderDistribution`, `renderModal` and `renderForm` keys receive the already rendered `children`, so a brand can also replace a wrapper alone; together with the leaf keys every element the package draws can be replaced. Each function receives the resolved data (translated labels, formatted values, handlers) and returns a React node; the `stars` key is forwarded to every star rendered inside the component, and the composite components forward `summary`, `list` and `modal` to their children.
122
+
123
+ | Component | `renderer` keys |
124
+ | --- | --- |
125
+ | `RateReviewStars` | `renderStars({ value, max, size, label, onChange? })` for the whole widget, `renderIcon({ size, className })` for the icon only |
126
+ | `RateReviewSummary` | `renderContainer({ summary, children })`, `renderAverage({ summary, average, countLabel })`, `renderDistribution({ bars, label, children })`, `renderBar({ value, count, percentage, label })`, `stars` |
127
+ | `RateReviewList` | `renderContainer({ children })`, `renderSort({ value, options, onChange, label })`, `renderLoading()`, `renderError({ message })`, `renderEmpty({ message })`, `renderList({ reviews, children })`, `renderItem({ review, authorName, date })`, `renderLoadMore({ onClick, disabled, label })`, `stars` |
128
+ | `ProductRateReview` | `renderContainer({ id, title, children })`, `renderHeading({ id, title })`, `summary`, `list` |
129
+ | `RateReviewBadge` | `renderBadge({ summary, average, countLabel, href })`, `stars` |
130
+ | `RateReviewPlpBadge` | `renderBadge({ average, count, formattedAverage })`, `stars` |
131
+ | `RateReviewModal` | `renderModal({ open, setOpen, title, children })`, `renderLoginNotice({ message })`, `renderForm({ onSubmit, children })`, `renderProductName({ name })`, `renderRatingField({ value, onChange, label })`, `renderTitleField({ id, value, onChange, label, placeholder, maxLength })`, `renderReviewField({ id, value, onChange, label, placeholder, maxLength, remaining, counter })`, `renderImageField({ id, accept, onChange, label, hint, slots })`, `renderPrivacyField({ id, checked, onChange, label })`, `renderConsentField({ id, checked, onChange, label })`, `renderError({ message })`, `renderSubmit({ label, disabled, isEdit })`, `stars` |
132
+ | `OrderItemRateAction` | `renderContainer({ review?, children })`, `renderStatus({ review, label })`, `renderButton({ onClick, label, isEdit })`, `modal`, `stars` |
133
+
134
+ ```tsx
135
+ <PluginModule
136
+ component={Component.ProductRateReview}
137
+ props={{
138
+ product: { sku: product.sku, base_code: product.base_code },
139
+ renderer: {
140
+ renderHeading: ({ id, title }) => (
141
+ <h2 id={id} className="brand-heading">
142
+ {title}
143
+ </h2>
144
+ ),
145
+ list: {
146
+ renderItem: ({ review, authorName, date }) => (
147
+ <li className="brand-review">
148
+ <RateReviewStars value={review.rating} />
149
+ <p>{review.review}</p>
150
+ <small>
151
+ {authorName}, {date}
152
+ </small>
153
+ </li>
154
+ )
155
+ }
156
+ }
157
+ }}
158
+ />
159
+ ```
160
+
161
+ The render functions are called during the component's render, so they must not use hooks; put stateful markup in a component of your own and return it. Items returned from `renderItem` and `renderBar` are keyed by the package, so they need no `key`. A `renderer` passed through `PluginModule` must come from a client component because it carries functions.
162
+
163
+ ### Server side reads
164
+
165
+ `@akinon/pz-rate-review/src/data/server` exposes `getProductRatingSummary`, `getProductReviews` and `getGroupedRatings` for server components. They call the extension directly, never the storefront's own API, and return `null` when the extension is unavailable so a page never fails because of reviews. Pass their results to the components through `summary`, `reviews` and `ratings` to avoid a client request.
166
+
167
+ `toAggregateRating(summary)` and `toReviewJsonLd(review, anonymousName)` turn the same data into schema.org `AggregateRating` and `Review` objects for the brand's own product JSON-LD; the plugin never writes markup into the page head.
168
+
169
+ ```tsx
170
+ import { getGroupedRatings } from '@akinon/pz-rate-review/src/data/server';
171
+
172
+ const ratings = await getGroupedRatings(
173
+ products.map((product) => product.base_code)
174
+ );
175
+
176
+ <PluginModule
177
+ component={Component.RateReviewPlpProvider}
178
+ props={{ products, ratings }}
179
+ >
180
+ {products.map((product) => (
181
+ <PluginModule
182
+ key={product.pk}
183
+ component={Component.RateReviewPlpBadge}
184
+ props={{ product }}
185
+ />
186
+ ))}
187
+ </PluginModule>;
188
+ ```
189
+
190
+ ### Hooks
191
+
192
+ `useGetReviewsQuery`, `useGetRatingHistoryQuery`, `useGetGroupedRatingsQuery`, `useGetMyReviewsQuery`, `useCreateReviewMutation`, `useUpdateReviewMutation` and `useUploadReviewImagesMutation` are RTK Query hooks on the storefront `api`; `useRateReviewSettings` resolves the plugin settings with defaults and `useProductRatingSummary` picks the right summary source for the configured level.
193
+
194
+ ## Theme editor
195
+
196
+ Storefronts on `@akinon/pz-theme` compositions replace the template markup on the composed pages, so the template mounts above never show there. The package ships the same surfaces as editor types instead: a `Product reviews` section for the product page (also available as a block for existing sections) and two more blocks, `Rating badge` and `Order item reviews`. They read the product from the page context (or from the product row they are placed in), the plugin settings from `settings.js` and their display options from the editor panel. `@akinon/pz-theme` is an optional peer dependency; the `theme` entry is the only place that imports it, so a storefront without pz-theme is not affected.
197
+
198
+ Register them from the client root, under the brand's own vendor. pz-theme carries one vendor per build, so the package never registers a vendor of its own; the registration can share the call site with the brand's blocks.
199
+
200
+ ```ts
201
+ 'use client';
202
+
203
+ import { registerRateReviewTheme } from '@akinon/pz-rate-review/src/theme';
204
+
205
+ registerRateReviewTheme('acme');
206
+ ```
207
+
208
+ `registerRateReviewTheme(vendor, options?)` registers the blocks and the section and returns them. `createRateReviewTheme(options?)` only builds the definitions, for a brand that registers everything itself with `registerCustomBlocks` and `registerCustomSections`. The registered type names are `custom:<vendor>:rate-review-product-reviews`, `custom:<vendor>:rate-review-reviews`, `custom:<vendor>:rate-review-rating-badge` and `custom:<vendor>:rate-review-order-items` (`RATE_REVIEW_THEME_NAMES`); they are part of saved compositions, so they never change.
209
+
210
+ | Type | Placement | Editor settings | Behaviour |
211
+ | --- | --- | --- | --- |
212
+ | `rate-review-product-reviews` (section) | Product page placeholder | Show heading, Show rating summary, Allow sorting, Reviews per page (defaults to the plugin `pageSize`) | `ProductRateReview` for the page product |
213
+ | `rate-review-reviews` (block) | Inside any section with a product, for brands that keep reviews within an existing product page section | Same as the section | Same as the section |
214
+ | `rate-review-rating-badge` (block) | Anywhere with a product: product page sections, product grid rows | Star size, Show review count | `RateReviewBadge` on the page product; inside a product row it batches one grouped ratings request from the page's product list, like `RateReviewPlpProvider` |
215
+ | `rate-review-order-items` (block) | Order detail placeholder, or inside the order list's row layout | Show product image | One `OrderItemRateAction` per delivered line (`statusValue === '550'`), read from the row it is placed in on the order list and from the live order page context on the order detail |
216
+
217
+ On the order list the merchant adds a child to the `Order List` block, marks it as the row layout and drops `Order item reviews` into it; the block then rates the delivered lines of each order in place. On the order detail it reads the order the page publishes.
218
+
219
+ `options.renderer` and `options.classNames` apply the same `renderer` and `classNames` objects as the components (`productReviews`, `badge`, `plpBadge`, `orderItem`), plus `orderItems` for the order block's own list (`renderList({ items, children })`, `renderItem({ item, showImage, action })` and the `root`, `item`, `image`, `name`, `action` class names), so an editor-placed block looks like the template mount of the same brand.
220
+
221
+ ```ts
222
+ registerRateReviewTheme('acme', {
223
+ renderer: { badge: { stars: { renderIcon: BrandStar } } },
224
+ classNames: { productReviews: { heading: 'brand-heading' } }
225
+ });
226
+ ```
227
+
228
+ ### Styling from the editor
229
+
230
+ Each type's root takes the editor's own style panel and the scoped custom CSS hatch (`& [data-part="item"] { … }`). Inside, every element the package draws is stamped as a pz-theme part through `attrs`, so the properties panel offers it as a styling target with colours, spacing and typography, and `load-more`, `button` (hover, focus) and `sort` (focus) carry states. The part names are the `classNames` keys in kebab case, shared across the types:
231
+
232
+ | Type | Parts |
233
+ | --- | --- |
234
+ | `rate-review-product-reviews`, `rate-review-reviews` | `heading`; summary: `summary`, `average`, `count`, `bars`, `bar`, `bar-label`, `bar-track`, `bar-fill`, `bar-count`; list: `reviews`, `toolbar`, `sort`, `list`, `item`, `item-header`, `title`, `text`, `meta`, `images`, `image`, `empty`, `error`, `load-more`; stars: `stars`, `star`, `star-filled`, `star-empty` |
235
+ | `rate-review-rating-badge` | `badge`, `average`, `count`, `stars`, `star`, `star-filled`, `star-empty` |
236
+ | `rate-review-order-items` | `items`, `item`, `image`, `name`, `action`, `status`, `button`, `stars`, `star`, `star-filled`, `star-empty` |
237
+
238
+ The review form opens in a portal outside the block, so it is not reachable from the editor panel; style it with `classNames` or `renderer` from code. A brand that replaces markup through `options.renderer` keeps the panel working by stamping its own elements with pz-theme's `partAttrs` using the same names (`PRODUCT_REVIEWS_PARTS`, `BADGE_PARTS`, `ORDER_ITEMS_PARTS` list them, `stampParts` turns a map into `attrs`).
239
+
240
+ ### Styling from the editor
241
+
242
+ Each type's root takes the editor's own style panel and the scoped custom CSS hatch (`& [data-part="item"] { … }`). Inside, every element the package draws is stamped as a pz-theme part through `attrs`, so the properties panel offers it as a styling target with colours, spacing and typography; `load-more` and `button` carry `hover` and `focus`, `sort` carries `focus`. The part names are the `classNames` keys in kebab case, shared across the types:
243
+
244
+ | Type | Parts |
245
+ | --- | --- |
246
+ | `rate-review-product-reviews`, `rate-review-reviews` | `heading`; summary: `summary`, `average`, `count`, `bars`, `bar`, `bar-label`, `bar-track`, `bar-fill`, `bar-count`; list: `reviews`, `toolbar`, `sort`, `list`, `item`, `item-header`, `title`, `text`, `meta`, `images`, `image`, `empty`, `error`, `load-more`; stars: `stars`, `star`, `star-filled`, `star-empty` |
247
+ | `rate-review-rating-badge` | `badge`, `average`, `count`, `stars`, `star`, `star-filled`, `star-empty` |
248
+ | `rate-review-order-items` | `items`, `item`, `image`, `name`, `action`, `status`, `button`, `stars`, `star`, `star-filled`, `star-empty` |
249
+
250
+ The review form opens in a portal outside the block, so the editor panel cannot reach it; style it with `classNames` or `renderer` from code. A brand that replaces markup through `options.renderer` keeps the panel working by stamping its own elements with pz-theme's `partAttrs` under the same names; `PRODUCT_REVIEWS_PARTS`, `BADGE_PARTS` and `ORDER_ITEMS_PARTS` list them and `stampParts` turns such a map into `attrs`.
251
+
252
+ ### Designer samples
253
+
254
+ While the editor canvas is in edit mode (`isDesigner`), every type renders sample data without touching the extension: a 4.3 rating from 12 reviews, three sample reviews and a sample order with one reviewed and one unreviewed delivered line, so the merchant can place and style the blocks on any page, even before the first review exists. The editor's **Use preview** toggle and the live site render the real data, and a block without a product or an order then renders nothing. A review submitted from a sample row is refused by the storefront (the sample order is not the customer's), so samples never reach the extension. The order block needs the `statusValue` and `createdDate` the order page context and the order list rows publish from pz-theme 2.0.146 on.
255
+
256
+ ## Translations
257
+
258
+ The package ships its own English and Turkish texts, so a storefront needs no translation work to start. Every text is looked up in the brand's `public/locales/<lang>/product.json` and `account.json` first and falls back to the package default of the active language (English for other languages), so a brand overrides any text by defining the same key in its own locale files.
259
+
260
+ - `product.rate_review`: `title`, `reviews_count` (`{count}`), `no_reviews`, `author_anonymous`, `star_label` (`{value}`), `rating_bar_label` (`{value}`), `distribution_label`, `load_more`, `sort.{label,newest,oldest,highest,lowest}`, `error.load`
261
+ - `account.rate_review`: `button`, `edit_button`, `modal_title`, `edit_modal_title`, `rating_label`, `title_label`, `title_placeholder`, `review_label`, `review_placeholder`, `characters_left` (`{count}`), `consent_label`, `privacy_label`, `submit`, `update`, `login_required`, `status.{waiting,approved,rejected}`, `image.add`, `image.limit` (`{count}`, `{size}`), `error.{rating_required,review_required,too_long,image_limit,image_size,image_type,image_upload,login_required,invalid,profile_incomplete,not_owner,order_not_owned,already_reviewed,locked,window_closed,consent_required,generic}`
262
+
263
+ `useRateReviewTranslation` exposes the same lookup for brand code that extends the components, and `DEFAULT_RATE_REVIEW_TRANSLATIONS` holds the shipped dictionaries.
264
+
265
+ ## Extension behaviour to know
266
+
267
+ - The extension caches its list for 5 minutes, the rating history for 2 hours and the grouped ratings for 30 seconds, so a freshly approved review reaches the storefront with that delay.
268
+ - The order number is read from Commerce (`/users/orders/{id}/`) with the customer's session, so a review can only be attached to an order that belongs to the customer and contains the product.
269
+ - Ratings are whole numbers from 1 to 5; the extension derives the average from `rating_types`, which the plugin always sends.
270
+ - Image uploads also need `REVIEW_IMAGE_COUNT` configured on the extension; the plugin only checks count, size and type on its side.
@@ -0,0 +1,10 @@
1
+ const { createApi, fetchBaseQuery } = require('@reduxjs/toolkit/query/react');
2
+
3
+ module.exports = {
4
+ api: createApi({
5
+ reducerPath: 'api',
6
+ baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost' }),
7
+ tagTypes: [],
8
+ endpoints: () => ({})
9
+ })
10
+ };
@@ -0,0 +1,6 @@
1
+ const React = require('react');
2
+
3
+ module.exports = {
4
+ Button: ({ children, appearance, size, ...props }) =>
5
+ React.createElement('button', props, children)
6
+ };
@@ -0,0 +1,6 @@
1
+ module.exports = {
2
+ useLocalization: () => ({
3
+ t: (key) => key,
4
+ locale: 'en'
5
+ })
6
+ };
@@ -0,0 +1,6 @@
1
+ const React = require('react');
2
+
3
+ module.exports = {
4
+ Image: ({ src, alt, className }) =>
5
+ React.createElement('img', { src, alt, className })
6
+ };
@@ -0,0 +1,6 @@
1
+ const React = require('react');
2
+
3
+ module.exports = {
4
+ LoaderSpinner: () =>
5
+ React.createElement('span', { 'data-testid': 'loader-spinner' })
6
+ };
@@ -0,0 +1,12 @@
1
+ const React = require('react');
2
+
3
+ module.exports = {
4
+ Modal: ({ open, title, children, portalId }) =>
5
+ open
6
+ ? React.createElement(
7
+ 'div',
8
+ { role: 'dialog', 'aria-label': title, id: portalId },
9
+ children
10
+ )
11
+ : null
12
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ useSession: () => ({ status: 'authenticated' })
3
+ };
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ __esModule: true,
3
+ default: {
4
+ commerceUrl: 'https://commerce.test',
5
+ plugins: {}
6
+ }
7
+ };
@@ -0,0 +1,4 @@
1
+ declare module 'settings' {
2
+ const settings: import('@akinon/next/types').Settings;
3
+ export default settings;
4
+ }
package/jest/setup.ts ADDED
@@ -0,0 +1 @@
1
+ import '@testing-library/jest-dom';
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "isolatedModules": true,
4
+ "jsx": "react-jsx",
5
+ "esModuleInterop": true,
6
+ "allowSyntheticDefaultImports": true,
7
+ "module": "commonjs",
8
+ "target": "es2020",
9
+ "lib": ["es2020", "dom", "dom.iterable"],
10
+ "moduleResolution": "node",
11
+ "resolveJsonModule": true,
12
+ "skipLibCheck": true,
13
+ "strict": true,
14
+ "noImplicitAny": false,
15
+ "types": ["jest", "@testing-library/jest-dom", "node"]
16
+ },
17
+ "files": ["./settings.d.ts"],
18
+ "include": ["../src", "./setup.ts"]
19
+ }
package/jest.config.js ADDED
@@ -0,0 +1,53 @@
1
+ const tsJest = [
2
+ 'ts-jest',
3
+ {
4
+ tsconfig: '<rootDir>/jest/tsconfig.json'
5
+ }
6
+ ];
7
+
8
+ const shared = {
9
+ preset: 'ts-jest',
10
+ clearMocks: true,
11
+ roots: ['<rootDir>/src'],
12
+ transform: {
13
+ '^.+\\.(ts|tsx)$': tsJest
14
+ }
15
+ };
16
+
17
+ module.exports = {
18
+ projects: [
19
+ {
20
+ ...shared,
21
+ displayName: 'api',
22
+ testEnvironment: 'node',
23
+ testMatch: ['**/*.test.ts'],
24
+ moduleNameMapper: {
25
+ '^settings$': '<rootDir>/jest/__mocks__/settings.js',
26
+ '^@akinon/next/data/client/api$':
27
+ '<rootDir>/jest/__mocks__/akinon-next-api.js'
28
+ }
29
+ },
30
+ {
31
+ ...shared,
32
+ displayName: 'views',
33
+ testEnvironment: 'jsdom',
34
+ testMatch: ['**/*.test.tsx'],
35
+ setupFilesAfterEnv: ['<rootDir>/jest/setup.ts'],
36
+ moduleNameMapper: {
37
+ '^settings$': '<rootDir>/jest/__mocks__/settings.js',
38
+ '^@akinon/next/hooks$': '<rootDir>/jest/__mocks__/akinon-next-hooks.js',
39
+ '^@akinon/next/components/button$':
40
+ '<rootDir>/jest/__mocks__/akinon-next-button.js',
41
+ '^@akinon/next/components/modal$':
42
+ '<rootDir>/jest/__mocks__/akinon-next-modal.js',
43
+ '^@akinon/next/components/image$':
44
+ '<rootDir>/jest/__mocks__/akinon-next-image.js',
45
+ '^@akinon/next/components/loader-spinner$':
46
+ '<rootDir>/jest/__mocks__/akinon-next-loader-spinner.js',
47
+ '^@akinon/next/data/client/api$':
48
+ '<rootDir>/jest/__mocks__/akinon-next-api.js',
49
+ '^next-auth/react$': '<rootDir>/jest/__mocks__/next-auth-react.js'
50
+ }
51
+ }
52
+ ]
53
+ };
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@akinon/pz-rate-review",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.152-rc.1",
4
+ "license": "MIT",
5
+ "main": "src/index.ts",
6
+ "scripts": {
7
+ "test": "jest"
8
+ },
9
+ "peerDependencies": {
10
+ "@akinon/pz-theme": "2.0.152-rc.1",
11
+ "next": "^14.0.0 || ^15.0.0 || ^16.0.0",
12
+ "react": "^18.0.0 || ^19.0.0",
13
+ "react-dom": "^18.0.0 || ^19.0.0"
14
+ },
15
+ "peerDependenciesMeta": {
16
+ "@akinon/pz-theme": {
17
+ "optional": true
18
+ }
19
+ },
20
+ "dependencies": {
21
+ "@akinon/next": "2.0.152-rc.1"
22
+ },
23
+ "devDependencies": {
24
+ "@types/jest": "29.5.14",
25
+ "@types/node": "^18.7.8",
26
+ "@types/react": "^18.0.17",
27
+ "@types/react-dom": "^18.0.6",
28
+ "jest": "29.7.0",
29
+ "ts-jest": "29.2.6",
30
+ "typescript": "^5.2.2"
31
+ }
32
+ }
@@ -0,0 +1,56 @@
1
+ import settings from 'settings';
2
+ import {
3
+ DEFAULT_RATE_REVIEW_SETTINGS,
4
+ getRateReviewSettings,
5
+ RATE_REVIEW_PLUGIN,
6
+ resolveRateReviewSettings
7
+ } from '../settings';
8
+
9
+ describe('resolveRateReviewSettings', () => {
10
+ it('applies the defaults when nothing is configured', () => {
11
+ expect(resolveRateReviewSettings()).toEqual(DEFAULT_RATE_REVIEW_SETTINGS);
12
+ });
13
+
14
+ it('merges partial overrides including nested upload limits', () => {
15
+ const resolved = resolveRateReviewSettings({
16
+ level: 'sku',
17
+ imageUploadLimits: { maxFiles: 1 }
18
+ });
19
+
20
+ expect(resolved.level).toBe('sku');
21
+ expect(resolved.imageUploadLimits).toEqual({
22
+ maxFiles: 1,
23
+ maxSizeMb: 5,
24
+ mimeTypes: ['image/jpeg', 'image/png', 'image/webp']
25
+ });
26
+ expect(resolved.pageSize).toBe(5);
27
+ });
28
+
29
+ it('clamps the review length to the extension limit and the page size to the api cap', () => {
30
+ const resolved = resolveRateReviewSettings({
31
+ reviewMaxLength: 1000,
32
+ pageSize: 500
33
+ });
34
+
35
+ expect(resolved.reviewMaxLength).toBe(250);
36
+ expect(resolved.pageSize).toBe(50);
37
+ expect(
38
+ resolveRateReviewSettings({ reviewMaxLength: 0, pageSize: 0 })
39
+ ).toMatchObject({
40
+ reviewMaxLength: 1,
41
+ pageSize: 1
42
+ });
43
+ });
44
+ });
45
+
46
+ describe('getRateReviewSettings', () => {
47
+ it('reads the plugin entry of the brand settings', () => {
48
+ settings.plugins = { [RATE_REVIEW_PLUGIN]: { maskAuthorName: false } };
49
+
50
+ expect(getRateReviewSettings().maskAuthorName).toBe(false);
51
+
52
+ settings.plugins = {};
53
+
54
+ expect(getRateReviewSettings().maskAuthorName).toBe(true);
55
+ });
56
+ });