@procraft/widget-order 2.32.2 → 2.33.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 (40) hide show
  1. package/dist/CourseItem/OrderButton/index.js +7 -4
  2. package/dist/CourseItem/OrderButton/index.js.map +1 -1
  3. package/dist/CourseItem/Sales/Sale/index.js +18 -7
  4. package/dist/CourseItem/Sales/Sale/index.js.map +1 -1
  5. package/dist/components/OldPrice/index.js +19 -2
  6. package/dist/components/OldPrice/index.js.map +1 -1
  7. package/dist/components/OldPrice/interfaces.d.ts +7 -0
  8. package/dist/components/OldPrice/styles.d.ts +8 -0
  9. package/dist/components/OldPrice/styles.js +14 -1
  10. package/dist/components/OldPrice/styles.js.map +1 -1
  11. package/dist/components/ProlongationWidget/index.js +16 -6
  12. package/dist/components/ProlongationWidget/index.js.map +1 -1
  13. package/dist/interfaces/index.d.ts +14 -0
  14. package/dist/modules/gql/generated/helpers/apollo-helpers.d.ts +88 -12
  15. package/dist/modules/gql/generated/types.d.ts +77 -1
  16. package/dist/modules/gql/generated/types.js +2 -0
  17. package/dist/modules/gql/generated/types.js.map +1 -1
  18. package/dist/money/SecondaryPrices.d.ts +26 -0
  19. package/dist/money/SecondaryPrices.js +58 -0
  20. package/dist/money/SecondaryPrices.js.map +1 -0
  21. package/dist/money/convert.d.ts +37 -0
  22. package/dist/money/convert.js +114 -0
  23. package/dist/money/convert.js.map +1 -0
  24. package/dist/tsconfig.build.tsbuildinfo +1 -1
  25. package/package.json +1 -1
  26. package/src/CourseItem/OrderButton/index.tsx +10 -0
  27. package/src/CourseItem/Sales/Sale/index.tsx +35 -6
  28. package/src/components/OldPrice/index.tsx +40 -2
  29. package/src/components/OldPrice/interfaces.ts +8 -0
  30. package/src/components/OldPrice/styles.ts +15 -0
  31. package/src/components/ProlongationWidget/__tests__/ProlongationWidget.test.tsx +101 -0
  32. package/src/components/ProlongationWidget/index.tsx +29 -34
  33. package/src/interfaces/index.ts +16 -0
  34. package/src/modules/gql/generated/helpers/apollo-helpers.ts +95 -19
  35. package/src/modules/gql/generated/schema.json +704 -25
  36. package/src/modules/gql/generated/types.ts +88 -1
  37. package/src/money/SecondaryPrices.tsx +99 -0
  38. package/src/money/__tests__/SecondaryPrices.test.tsx +110 -0
  39. package/src/money/__tests__/convert.test.ts +181 -0
  40. package/src/money/convert.ts +127 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@procraft/widget-order",
3
3
  "description": "Order widget for landing",
4
- "version": "2.32.2",
4
+ "version": "2.33.1",
5
5
  "private": false,
6
6
  "main": "dist",
7
7
  "scripts": {
@@ -9,6 +9,7 @@ import React, {
9
9
  import Button from '../../components/Button'
10
10
  import Container from '../../components/Container'
11
11
  import OldPrice from '../../components/OldPrice'
12
+ import { SecondaryPrices } from '../../money/SecondaryPrices'
12
13
  import Typography from '../../components/Typography'
13
14
  import {
14
15
  COLORED_TEXT_DEFAULT_COLOR,
@@ -219,6 +220,8 @@ export const OrderButton: React.FC<OrderButtonProps> = ({
219
220
  prefix={currencyPrefix}
220
221
  suffix={currencySuffix}
221
222
  price={oldPrice}
223
+ primaryCurrency={catalogItem.master?.currency || ''}
224
+ displayCurrencies={catalogItem.org?.displayCurrencies}
222
225
  />
223
226
  ) : null}
224
227
 
@@ -245,6 +248,12 @@ export const OrderButton: React.FC<OrderButtonProps> = ({
245
248
  suffix={currencySuffix}
246
249
  value={price}
247
250
  />
251
+ <SecondaryPrices
252
+ amount={price}
253
+ primaryCurrency={catalogItem.master?.currency || ''}
254
+ displayCurrencies={catalogItem.org?.displayCurrencies}
255
+ mode="inline"
256
+ />
248
257
  </>
249
258
  ) : (
250
259
  'Зарегистрироваться'
@@ -264,6 +273,7 @@ export const OrderButton: React.FC<OrderButtonProps> = ({
264
273
  uri,
265
274
  catalogItem.course?.tariffId,
266
275
  catalogItem.master?.currency,
276
+ catalogItem.org?.displayCurrencies,
267
277
  dateIndex,
268
278
  onClickDateIndex,
269
279
  buttonBgColor,
@@ -1,6 +1,7 @@
1
1
  import React, { useMemo } from 'react'
2
2
  import Button from '../../../components/Button'
3
3
  import OldPrice from '../../../components/OldPrice'
4
+ import { SecondaryPrices } from '../../../money/SecondaryPrices'
4
5
  import {
5
6
  TITLE_BG_DEFAULT_COLOR,
6
7
  TITLE_TEXT_DEFAULT_COLOR,
@@ -182,11 +183,24 @@ const Sale: React.FC<SaleProps> = ({
182
183
  {n.name}
183
184
  </span>{' '}
184
185
  {priceWithDiscount && (
185
- <PriceFormat
186
- prefix={currencyPrefix}
187
- suffix={currencySuffix}
188
- value={price}
189
- />
186
+ <>
187
+ <PriceFormat
188
+ prefix={currencyPrefix}
189
+ suffix={currencySuffix}
190
+ value={price}
191
+ />
192
+ {/*
193
+ * `inline` (контракт §7): строка акции читается как «название цена», а
194
+ * `block` — блочный узел, который уезжает под строку целиком и во всю ширину
195
+ * `.item`, то есть встаёт не под ценой, а под названием.
196
+ */}
197
+ <SecondaryPrices
198
+ amount={price}
199
+ primaryCurrency={catalogItem.master?.currency || ''}
200
+ displayCurrencies={catalogItem.org?.displayCurrencies}
201
+ mode="inline"
202
+ />
203
+ </>
190
204
  )}
191
205
  </span>
192
206
  )
@@ -199,7 +213,14 @@ const Sale: React.FC<SaleProps> = ({
199
213
  totalPrice,
200
214
  saleFieldsValueSelected,
201
215
  }
202
- }, [fieldsValueSelected, sale, currencyPrefix, currencySuffix])
216
+ }, [
217
+ fieldsValueSelected,
218
+ sale,
219
+ currencyPrefix,
220
+ currencySuffix,
221
+ catalogItem.master?.currency,
222
+ catalogItem.org?.displayCurrencies,
223
+ ])
203
224
 
204
225
  const uri = useOrderLink({
205
226
  catalogItem,
@@ -264,6 +285,8 @@ const Sale: React.FC<SaleProps> = ({
264
285
  price={totalPriceOriginal}
265
286
  prefix={currencyPrefix}
266
287
  suffix={currencySuffix}
288
+ primaryCurrency={catalogItem.master?.currency || ''}
289
+ displayCurrencies={catalogItem.org?.displayCurrencies}
267
290
  />
268
291
  </div>
269
292
 
@@ -281,6 +304,12 @@ const Sale: React.FC<SaleProps> = ({
281
304
  suffix={currencySuffix}
282
305
  value={totalPrice}
283
306
  />
307
+ <SecondaryPrices
308
+ amount={totalPrice}
309
+ primaryCurrency={catalogItem.master?.currency || ''}
310
+ displayCurrencies={catalogItem.org?.displayCurrencies}
311
+ mode="inline"
312
+ />
284
313
  </Button>
285
314
  </a>
286
315
  </div>
@@ -1,19 +1,57 @@
1
1
  import React from 'react'
2
2
  import { OldPriceProps } from './interfaces'
3
- import { OldPriceStyled } from './styles'
3
+ import {
4
+ OldPriceGroupStyled,
5
+ OldPriceSecondaryStyled,
6
+ OldPriceStyled,
7
+ } from './styles'
4
8
  import { PriceFormat } from '../../PriceFormat'
9
+ import { getCurrencyPrefix, getCurrencySuffix } from '../../utils'
10
+ import { convertMoney, secondaryCurrencies } from '../../money/convert'
5
11
 
6
12
  const OldPrice: React.FC<OldPriceProps> = ({
7
13
  price,
8
14
  prefix,
9
15
  suffix,
16
+ primaryCurrency,
17
+ displayCurrencies,
10
18
  ...other
11
19
  }) => {
12
- return (
20
+ const primary = (
13
21
  <OldPriceStyled component="span" {...other}>
14
22
  <PriceFormat prefix={prefix} suffix={suffix} value={price} />
15
23
  </OldPriceStyled>
16
24
  )
25
+
26
+ const secondary = secondaryCurrencies(
27
+ displayCurrencies,
28
+ primaryCurrency ?? ''
29
+ )
30
+ if (!secondary.length) {
31
+ // Со снятой галкой разметка обязана совпасть с той, что была до SL-13080.
32
+ return primary
33
+ }
34
+
35
+ /**
36
+ * SL-13080: каждая валюта зачёркивается СВОИМ узлом.
37
+ * Зачёркивание в `OldPriceStyled` — абсолютный `:after` с `bottom: 8px`, поэтому вложить
38
+ * вторую строку внутрь одного зачёркнутого узла нельзя: линия окажется поперёк одной из
39
+ * двух строк, а не поперёк каждой цены.
40
+ */
41
+ return (
42
+ <OldPriceGroupStyled>
43
+ {primary}
44
+ {secondary.map((n) => (
45
+ <OldPriceSecondaryStyled component="span" key={n.currency}>
46
+ <PriceFormat
47
+ prefix={getCurrencyPrefix(n.currency)}
48
+ suffix={getCurrencySuffix(n.currency)}
49
+ value={convertMoney(price, n.rate)}
50
+ />
51
+ </OldPriceSecondaryStyled>
52
+ ))}
53
+ </OldPriceGroupStyled>
54
+ )
17
55
  }
18
56
 
19
57
  export default OldPrice
@@ -1,5 +1,13 @@
1
+ import { DisplayCurrencyRate } from '../../money/convert'
2
+
1
3
  export type OldPriceProps = {
2
4
  price: number
3
5
  prefix?: string
4
6
  suffix?: string
7
+ /**
8
+ * SL-13080: основная валюта (валюта Organization) и весь список валют показа.
9
+ * Пока хвост пуст — разметка и стили ровно те, что были до изменения.
10
+ */
11
+ primaryCurrency?: string
12
+ displayCurrencies?: ReadonlyArray<DisplayCurrencyRate> | null
5
13
  }
@@ -20,3 +20,18 @@ export const OldPriceStyled = styled(Typography)`
20
20
  transform: rotate(-13.04deg);
21
21
  }
22
22
  `
23
+
24
+ /**
25
+ * SL-13080: вторичная зачёркнутая цена — тот же зачёркнутый узел, на 2 пункта меньше.
26
+ * Цвет и прозрачность наследуются от `OldPriceStyled`, отдельного приглушения не нужно:
27
+ * блок и так нарисован приглушённым (`opacity: .5`).
28
+ */
29
+ export const OldPriceSecondaryStyled = styled(OldPriceStyled)`
30
+ display: block;
31
+ font-size: 15px;
32
+ `
33
+
34
+ /** Обёртка появляется ТОЛЬКО когда вторичные валюты есть. */
35
+ export const OldPriceGroupStyled = styled.span`
36
+ display: inline-block;
37
+ `
@@ -0,0 +1,101 @@
1
+ import React from 'react'
2
+ import { render } from '@testing-library/react'
3
+
4
+ import { ProlongationWidget } from '../index'
5
+ import { ProlongationWidgetProps } from '../interfaces'
6
+
7
+ /**
8
+ * Попутный фикс SL-13080 §11: продления брали захардкоженный `₽` вместо валюты школы.
9
+ * Эти тесты держат обе границы фикса — он обязан поменять валюту и **ничего больше**.
10
+ *
11
+ * Проверить иначе негде: истории Storybook у ProlongationWidget нет, а в лендинге блок
12
+ * продлений отключён заглушкой `if (1 === 1) { return null }`
13
+ * (`lms-landing/src/components/Redactor2/components/CourseProlongation/View/index.tsx`),
14
+ * поэтому §12 п.8 проверяется только здесь и на dev-странице `dev/pages/Prolongation`.
15
+ */
16
+
17
+ const TARIFF_ID = 193
18
+
19
+ const course = {
20
+ id: 'Q291cnNlOjEx',
21
+ uid: 11,
22
+ name: 'Курс',
23
+ tariffs: [{ id: 'VGFyaWZmOjE5Mw==', uid: TARIFF_ID, name: 'Пакет' }],
24
+ } as unknown as ProlongationWidgetProps['course']
25
+
26
+ function catalogItem(
27
+ extra: Record<string, unknown>
28
+ ): ProlongationWidgetProps['catalogItems'][number] {
29
+ return {
30
+ id: 'item-1',
31
+ uid: 1,
32
+ name: 'Продление',
33
+ title: [],
34
+ course: { courseId: 11, flowId: 11, tariffId: TARIFF_ID },
35
+ ...extra,
36
+ } as unknown as ProlongationWidgetProps['catalogItems'][number]
37
+ }
38
+
39
+ function renderWidget(
40
+ catalogItems: ProlongationWidgetProps['catalogItems']
41
+ ): string {
42
+ const { container } = render(
43
+ <ProlongationWidget course={course} catalogItems={catalogItems} />
44
+ )
45
+ // Неразрывные и узкие пробелы мешают сравнивать строки — приводим к обычному.
46
+ return (container.textContent || '').replace(/[\u00A0\u202F]/g, ' ')
47
+ }
48
+
49
+ describe('ProlongationWidget: цена продления', () => {
50
+ it('берёт валюту школы, а не захардкоженный рубль', () => {
51
+ const text = renderWidget([
52
+ catalogItem({
53
+ unitPrice: 499,
54
+ master: { id: 'TWFzdGVyOjE=', uid: 1, currency: 'USD' },
55
+ }),
56
+ ])
57
+
58
+ expect(text).toContain('$499')
59
+ expect(text).not.toContain('₽')
60
+ })
61
+
62
+ it('без master валюту берёт из валют показа, а не остаётся без знака валюты', () => {
63
+ // Первый элемент displayCurrencies по контракту §3.2 п.6-7 — валюта Organization.
64
+ const text = renderWidget([
65
+ catalogItem({
66
+ unitPrice: 77777,
67
+ org: { displayCurrencies: [{ currency: 'RUB', rate: 1 }] },
68
+ }),
69
+ ])
70
+
71
+ expect(text).toContain('77 777 ₽')
72
+ })
73
+
74
+ it('дробную цену не округляет: PriceFormat с decimalScale={0} сюда не годится', () => {
75
+ const text = renderWidget([
76
+ catalogItem({
77
+ unitPrice: 7.99,
78
+ master: { id: 'TWFzdGVyOjE=', uid: 1, currency: 'USD' },
79
+ }),
80
+ ])
81
+
82
+ expect(text).toContain('$7.99')
83
+ })
84
+
85
+ it('вторая валюта стоит в той же строке (mode=inline)', () => {
86
+ const text = renderWidget([
87
+ catalogItem({
88
+ unitPrice: 499,
89
+ master: { id: 'TWFzdGVyOjE=', uid: 1, currency: 'USD' },
90
+ org: {
91
+ displayCurrencies: [
92
+ { currency: 'USD', rate: 1 },
93
+ { currency: 'RUB', rate: 0.0125 },
94
+ ],
95
+ },
96
+ }),
97
+ ])
98
+
99
+ expect(text).toContain('$499 (39 920 ₽)')
100
+ })
101
+ })
@@ -13,6 +13,8 @@ import { ProlongationWidgetProps } from './interfaces'
13
13
  import { ContainerStyled } from '../Container/styles'
14
14
  import Button from '../Button'
15
15
  import NumberFormat from 'react-number-format'
16
+ import { getCurrencyPrefix, getCurrencySuffix } from '../../utils'
17
+ import { SecondaryPrices } from '../../money/SecondaryPrices'
16
18
  import { RadioGroup, RadioGroupItem } from '../RadioGroup'
17
19
 
18
20
  /**
@@ -83,6 +85,17 @@ export const ProlongationWidget: React.FC<ProlongationWidgetProps> = ({
83
85
  const items: RadioGroupItem[] = []
84
86
 
85
87
  prolongationCatalogItems.forEach((n) => {
88
+ /**
89
+ * SL-13080 §11: раньше здесь стоял захардкоженный `₽`, теперь — валюта школы.
90
+ *
91
+ * Фолбэк ведёт на валюту Organization, а не на пустую строку: `getCurrencySuffix('')`
92
+ * уходит в `default` и возвращает один узкий пробел, то есть строка осталась бы вообще
93
+ * без знака валюты — отказ хуже неверной валюты. Первый элемент `displayCurrencies` по
94
+ * контракту §3.2 п.6-7 всегда валюта Organization с `rate = 1`, независимо от галки.
95
+ */
96
+ const currency =
97
+ n.master?.currency || n.org?.displayCurrencies?.[0]?.currency || ''
98
+
86
99
  items.push({
87
100
  uid: n.uid,
88
101
  label: (
@@ -95,12 +108,26 @@ export const ProlongationWidget: React.FC<ProlongationWidgetProps> = ({
95
108
  ? `Продление на ${n.course?.prolongationDays} дней`
96
109
  : n.name}{' '}
97
110
  -{' '}
111
+ {/*
112
+ * Не `PriceFormat`: он несёт `decimalScale={0}`, а прежний рендер продлений
113
+ * не округлял. Попутный фикс §11 меняет ровно валюту, поэтому и формат числа,
114
+ * и разделитель разрядов остаются те же, что были до SL-13080. Цена продления
115
+ * бывает дробной — `formatMoney` в корзине лендинга печатает 2 знака при
116
+ * `value % 1`, и округление до целых показало бы `7.99` как `8`.
117
+ */}
98
118
  <NumberFormat
99
119
  value={n.unitPrice}
100
120
  displayType="text"
101
121
  thousandSeparator={' '}
102
- />{' '}
103
- ₽
122
+ prefix={getCurrencyPrefix(currency)}
123
+ suffix={getCurrencySuffix(currency)}
124
+ />
125
+ <SecondaryPrices
126
+ amount={n.unitPrice || 0}
127
+ primaryCurrency={currency}
128
+ displayCurrencies={n.org?.displayCurrencies}
129
+ mode="inline"
130
+ />
104
131
  </Typography>
105
132
  ),
106
133
  })
@@ -122,38 +149,6 @@ export const ProlongationWidget: React.FC<ProlongationWidgetProps> = ({
122
149
  <Typography className="subtitle">Сроки продления</Typography>
123
150
 
124
151
  {itemsContent}
125
-
126
- {/* {prolongationCatalogItems.map((n) => {
127
- const checked = n.uid === itemId
128
-
129
- return (
130
- <ProlongationWidgetRadioInputRowStyled
131
- key={n.id}
132
- className="option"
133
- data-value={n.uid}
134
- onClick={onClickCatalogItem}
135
- checked={checked}
136
- >
137
- <input type="radio" checked={checked} onChange={onChange} />{' '}
138
- <Typography
139
- variant="grey-sm"
140
- component="label"
141
- className="altItemText"
142
- >
143
- {n.course?.prolongationDays
144
- ? `Продление на ${n.course?.prolongationDays} дней`
145
- : n.name}{' '}
146
- -{' '}
147
- <NumberFormat
148
- value={n.unitPrice}
149
- displayType="text"
150
- thousandSeparator={' '}
151
- />{' '}
152
- ₽
153
- </Typography>
154
- </ProlongationWidgetRadioInputRowStyled>
155
- )
156
- })} */}
157
152
  </ContainerStyled>
158
153
  </>
159
154
  )
@@ -38,6 +38,21 @@ export type CatalogItemMaster = {
38
38
  currency: string
39
39
  }
40
40
 
41
+ /** SL-13080: валюта показа. Парная к `DisplayCurrency` в схеме gateway. */
42
+ export type CatalogItemDisplayCurrency = {
43
+ currency: string
44
+ rate: number
45
+ }
46
+
47
+ /**
48
+ * SL-13080: `org` в этом рукописном типе не было вовсе.
49
+ * Всё опционально — это и есть защитное чтение: новый виджет обязан пережить старый gateway,
50
+ * который поля ещё не отдаёт (контракт §9).
51
+ */
52
+ export type CatalogItemOrg = {
53
+ displayCurrencies?: Maybe<Array<CatalogItemDisplayCurrency>>
54
+ }
55
+
41
56
  export type CatalogItem = {
42
57
  id: string
43
58
  uid: number
@@ -45,6 +60,7 @@ export type CatalogItem = {
45
60
  sales?: CatalogItemSale[] | null
46
61
  course?: CourseItem | null
47
62
  master?: Maybe<CatalogItemMaster>
63
+ org?: Maybe<CatalogItemOrg>
48
64
  }
49
65
 
50
66
  /**