@cranberry-money/shared-utils 8.17.7 → 8.17.9

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 (49) hide show
  1. package/dist/allocations.js +20 -0
  2. package/dist/cash-account.d.ts.map +1 -0
  3. package/dist/cash-account.js +52 -0
  4. package/dist/collections.d.ts.map +1 -0
  5. package/dist/collections.js +127 -0
  6. package/dist/country.d.ts.map +1 -0
  7. package/dist/country.js +116 -0
  8. package/dist/currency.d.ts.map +1 -0
  9. package/dist/currency.js +128 -0
  10. package/dist/dashboard.js +121 -0
  11. package/dist/date.d.ts.map +1 -0
  12. package/dist/date.js +91 -0
  13. package/dist/document.d.ts.map +1 -0
  14. package/dist/document.js +56 -0
  15. package/dist/downloads.d.ts.map +1 -0
  16. package/dist/downloads.js +91 -0
  17. package/dist/filters.d.ts.map +1 -0
  18. package/dist/filters.js +206 -0
  19. package/dist/formatting.d.ts.map +1 -0
  20. package/dist/formatting.js +81 -0
  21. package/dist/holdings.js +139 -0
  22. package/dist/index.js +68 -0
  23. package/dist/industry.d.ts.map +1 -0
  24. package/dist/industry.js +152 -0
  25. package/dist/investment-preference.js +33 -0
  26. package/dist/numbers.d.ts.map +1 -0
  27. package/dist/numbers.js +101 -0
  28. package/dist/portfolio-template.d.ts.map +1 -0
  29. package/dist/portfolio-template.js +60 -0
  30. package/dist/portfolio.d.ts.map +1 -0
  31. package/dist/portfolio.js +87 -0
  32. package/dist/sector.d.ts.map +1 -0
  33. package/dist/sector.js +134 -0
  34. package/dist/stock-exchange.d.ts.map +1 -0
  35. package/dist/stock-exchange.js +101 -0
  36. package/dist/tax-residency.d.ts.map +1 -0
  37. package/dist/tax-residency.js +70 -0
  38. package/dist/text.d.ts.map +1 -0
  39. package/dist/text.js +25 -0
  40. package/dist/withdrawal-status.d.ts.map +1 -0
  41. package/dist/withdrawal-status.js +127 -0
  42. package/package.json +1 -1
  43. package/dist/auth.d.ts +0 -55
  44. package/dist/badge-status.d.ts +0 -65
  45. package/dist/badge.d.ts +0 -41
  46. package/dist/instruments.d.ts +0 -66
  47. package/dist/portfolio-validation.d.ts +0 -42
  48. package/dist/validation.d.ts +0 -238
  49. package/dist/withdrawal.d.ts +0 -87
@@ -0,0 +1,101 @@
1
+ import { sortByStringField, findByStringField } from './collections';
2
+ /**
3
+ * Extract unique countries from stock exchanges
4
+ *
5
+ * @param exchanges - List of stock exchanges
6
+ * @returns Array of unique countries
7
+ *
8
+ * @example
9
+ * const exchanges = [
10
+ * { uuid: '1', name: 'NYSE', shortName: 'NYSE', country: { uuid: 'us', code: 'US' } },
11
+ * { uuid: '2', name: 'NASDAQ', shortName: 'NASDAQ', country: { uuid: 'us', code: 'US' } },
12
+ * { uuid: '3', name: 'TSX', shortName: 'TSX', country: { uuid: 'ca', code: 'CA' } }
13
+ * ];
14
+ * getCountriesFromExchanges(exchanges); // returns [{ uuid: 'us', code: 'US' }, { uuid: 'ca', code: 'CA' }]
15
+ */
16
+ export const getCountriesFromExchanges = (exchanges) => {
17
+ const countriesMap = new Map();
18
+ exchanges.forEach(exchange => {
19
+ if (exchange.country) {
20
+ countriesMap.set(exchange.country.uuid, exchange.country);
21
+ }
22
+ });
23
+ return Array.from(countriesMap.values());
24
+ };
25
+ /**
26
+ * Group stock exchanges by country code
27
+ *
28
+ * @param exchanges - List of stock exchanges
29
+ * @returns Object with country codes as keys and exchanges as values
30
+ *
31
+ * @example
32
+ * const exchanges = [
33
+ * { uuid: '1', name: 'NYSE', shortName: 'NYSE', country: { uuid: 'us', code: 'US' } },
34
+ * { uuid: '2', name: 'TSX', shortName: 'TSX', country: { uuid: 'ca', code: 'CA' } }
35
+ * ];
36
+ * groupExchangesByCountry(exchanges);
37
+ * // returns { 'US': [NYSE exchange], 'CA': [TSX exchange], 'Unknown': [] }
38
+ */
39
+ export const groupExchangesByCountry = (exchanges) => {
40
+ return exchanges.reduce((groups, exchange) => {
41
+ const countryCode = exchange.country?.code || 'Unknown';
42
+ if (!groups[countryCode]) {
43
+ groups[countryCode] = [];
44
+ }
45
+ groups[countryCode].push(exchange);
46
+ return groups;
47
+ }, {});
48
+ };
49
+ /**
50
+ * Find stock exchange by short name
51
+ *
52
+ * @param exchanges - List of stock exchanges
53
+ * @param shortName - Short name to search for
54
+ * @returns The exchange if found, undefined otherwise
55
+ *
56
+ * @example
57
+ * const exchanges = [
58
+ * { uuid: '1', name: 'New York Stock Exchange', shortName: 'NYSE' },
59
+ * { uuid: '2', name: 'NASDAQ', shortName: 'NASDAQ' }
60
+ * ];
61
+ * findExchangeByShortName(exchanges, 'NYSE'); // returns NYSE exchange
62
+ */
63
+ export const findExchangeByShortName = (exchanges, shortName) => {
64
+ return findByStringField([...exchanges], 'shortName', shortName);
65
+ };
66
+ /**
67
+ * Sort stock exchanges by name
68
+ *
69
+ * @param exchanges - List of stock exchanges
70
+ * @param direction - Sort direction ('asc' or 'desc')
71
+ * @returns New sorted array of exchanges
72
+ *
73
+ * @example
74
+ * const exchanges = [
75
+ * { uuid: '2', name: 'NASDAQ', shortName: 'NASDAQ' },
76
+ * { uuid: '1', name: 'NYSE', shortName: 'NYSE' }
77
+ * ];
78
+ * sortExchangesByName(exchanges); // returns [NASDAQ, NYSE] (alphabetical)
79
+ * sortExchangesByName(exchanges, 'desc'); // returns [NYSE, NASDAQ] (reverse)
80
+ */
81
+ export const sortExchangesByName = (exchanges, direction = 'asc') => {
82
+ const sorted = sortByStringField([...exchanges], 'name');
83
+ return direction === 'asc' ? sorted : sorted.reverse();
84
+ };
85
+ /**
86
+ * Filter stock exchanges by country code
87
+ *
88
+ * @param exchanges - List of stock exchanges
89
+ * @param countryCode - Country code to filter by
90
+ * @returns Array of exchanges in the specified country
91
+ *
92
+ * @example
93
+ * const exchanges = [
94
+ * { uuid: '1', name: 'NYSE', shortName: 'NYSE', country: { uuid: 'us', code: 'US' } },
95
+ * { uuid: '2', name: 'TSX', shortName: 'TSX', country: { uuid: 'ca', code: 'CA' } }
96
+ * ];
97
+ * filterExchangesByCountry(exchanges, 'US'); // returns [NYSE exchange]
98
+ */
99
+ export const filterExchangesByCountry = (exchanges, countryCode) => {
100
+ return exchanges.filter(exchange => exchange.country?.code === countryCode);
101
+ };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tax-residency.d.ts","sourceRoot":"","sources":["../src/tax-residency.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;CAC9B;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,GAAI,CAAC,SAAS,gBAAgB,EAAE,gBAAgB,SAAS,CAAC,EAAE,KAAG,CAAC,GAAG,SAEtG,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,6BAA6B,GAAI,CAAC,SAAS,gBAAgB,EACtE,gBAAgB,SAAS,CAAC,EAAE,EAC5B,aAAa,MAAM,KAClB,CAAC,EAEH,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,wBAAwB,GAAI,CAAC,SAAS,gBAAgB,EACjE,gBAAgB,SAAS,CAAC,EAAE,EAC5B,aAAa,MAAM,KAClB,OAEF,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,4BAA4B,GAAI,CAAC,SAAS,gBAAgB,EAAE,gBAAgB,SAAS,CAAC,EAAE,KAAG,CAAC,EAExG,CAAC"}
@@ -0,0 +1,70 @@
1
+ import { findByField, hasItemWithFieldValue, filterByBooleanField } from './collections';
2
+ /**
3
+ * Find the primary tax residency from a list
4
+ *
5
+ * @param taxResidencies - List of tax residencies
6
+ * @returns The primary tax residency if found, undefined otherwise
7
+ *
8
+ * @example
9
+ * const residencies = [
10
+ * { country: 'US', isPrimary: false, isExempted: false },
11
+ * { country: 'CA', isPrimary: true, isExempted: false }
12
+ * ];
13
+ * findPrimaryTaxResidency(residencies); // returns CA residency
14
+ */
15
+ export const findPrimaryTaxResidency = (taxResidencies) => {
16
+ return findByField([...taxResidencies], 'isPrimary', true);
17
+ };
18
+ /**
19
+ * Filter tax residencies by country code
20
+ *
21
+ * @param taxResidencies - List of tax residencies
22
+ * @param countryCode - Country code to filter by
23
+ * @returns List of tax residencies for the specified country
24
+ *
25
+ * @example
26
+ * const residencies = [
27
+ * { country: 'US', isPrimary: true, isExempted: false },
28
+ * { country: 'US', isPrimary: false, isExempted: true },
29
+ * { country: 'CA', isPrimary: false, isExempted: false }
30
+ * ];
31
+ * filterTaxResidenciesByCountry(residencies, 'US'); // returns 2 US residencies
32
+ */
33
+ export const filterTaxResidenciesByCountry = (taxResidencies, countryCode) => {
34
+ return taxResidencies.filter(residency => residency.country === countryCode);
35
+ };
36
+ /**
37
+ * Check if user has tax residency in a specific country
38
+ *
39
+ * @param taxResidencies - List of tax residencies
40
+ * @param countryCode - Country code to check
41
+ * @returns True if user has residency in the country, false otherwise
42
+ *
43
+ * @example
44
+ * const residencies = [
45
+ * { country: 'US', isPrimary: true, isExempted: false },
46
+ * { country: 'CA', isPrimary: false, isExempted: false }
47
+ * ];
48
+ * hasTaxResidencyInCountry(residencies, 'US'); // returns true
49
+ * hasTaxResidencyInCountry(residencies, 'UK'); // returns false
50
+ */
51
+ export const hasTaxResidencyInCountry = (taxResidencies, countryCode) => {
52
+ return hasItemWithFieldValue([...taxResidencies], 'country', countryCode);
53
+ };
54
+ /**
55
+ * Get all non-exempted tax residencies
56
+ *
57
+ * @param taxResidencies - List of tax residencies
58
+ * @returns List of non-exempted tax residencies
59
+ *
60
+ * @example
61
+ * const residencies = [
62
+ * { country: 'US', isPrimary: true, isExempted: false },
63
+ * { country: 'CA', isPrimary: false, isExempted: true },
64
+ * { country: 'UK', isPrimary: false, isExempted: false }
65
+ * ];
66
+ * getNonExemptedTaxResidencies(residencies); // returns US and UK residencies
67
+ */
68
+ export const getNonExemptedTaxResidencies = (taxResidencies) => {
69
+ return filterByBooleanField([...taxResidencies], 'isExempted', false);
70
+ };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text.d.ts","sourceRoot":"","sources":["../src/text.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;;;;;;;GAaG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,GAAE,MAAW,GAAG,MAAM,CAGzE"}
package/dist/text.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Text manipulation utility functions
3
+ *
4
+ * This module provides pure functions for common text operations
5
+ * such as truncation, formatting, and manipulation.
6
+ */
7
+ /**
8
+ * Truncates text to a specified maximum length and adds ellipsis if needed
9
+ *
10
+ * @param text - The text to truncate
11
+ * @param maxLength - The maximum length of the text (default: 30)
12
+ * @returns The truncated text with ellipsis if it exceeds maxLength
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * truncateText('This is a very long text', 10) // 'This is a...'
17
+ * truncateText('Short', 10) // 'Short'
18
+ * truncateText('', 10) // ''
19
+ * ```
20
+ */
21
+ export function truncateText(text, maxLength = 30) {
22
+ if (text.length <= maxLength)
23
+ return text;
24
+ return `${text.substring(0, maxLength)}...`;
25
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withdrawal-status.d.ts","sourceRoot":"","sources":["../src/withdrawal-status.ts"],"names":[],"mappings":"AAAA,OAAO,EAWL,gCAAgC,EAChC,0BAA0B,EAC1B,0BAA0B,EAC1B,4BAA4B,EAC5B,sCAAsC,EACtC,yCAAyC,EACzC,2BAA2B,EAC3B,2BAA2B,EAC3B,wBAAwB,EAUxB,yBAAyB,EACzB,4BAA4B,EAG5B,qCAAqC,EACrC,mCAAmC,EACnC,2BAA2B,EAC3B,uBAAuB,EAKvB,0BAA0B,EAC1B,iCAAiC,EACjC,2BAA2B,EAC3B,0BAA0B,EAC1B,yBAAyB,EAM1B,MAAM,mCAAmC,CAAC;AAG3C,MAAM,MAAM,gBAAgB,GACxB,OAAO,gCAAgC,GACvC,OAAO,0BAA0B,GACjC,OAAO,0BAA0B,GACjC,OAAO,4BAA4B,GACnC,OAAO,sCAAsC,GAC7C,OAAO,yCAAyC,GAChD,OAAO,2BAA2B,GAClC,OAAO,2BAA2B,GAClC,OAAO,wBAAwB,CAAC;AAEpC,MAAM,MAAM,cAAc,GAAG,OAAO,yBAAyB,GAAG,OAAO,4BAA4B,CAAC;AAEpG,MAAM,MAAM,gBAAgB,GACxB,OAAO,qCAAqC,GAC5C,OAAO,mCAAmC,GAC1C,OAAO,2BAA2B,GAClC,OAAO,uBAAuB,CAAC;AAEnC,MAAM,MAAM,iBAAiB,GACzB,OAAO,0BAA0B,GACjC,OAAO,iCAAiC,GACxC,OAAO,2BAA2B,GAClC,OAAO,0BAA0B,GACjC,OAAO,yBAAyB,CAAC;AAErC;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,QAAQ,gBAAgB,KAAG,MAazD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,QAAQ,gBAAgB,KAAG,MAazD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,GAAI,MAAM,cAAc,KAAG,MAM7D,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,QAAQ,gBAAgB,GAAG,IAAI,GAAG,SAAS,KAAG,MAU5E,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,yBAAyB,GAAI,QAAQ,iBAAiB,KAAG,MASrE,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,yBAAyB,GAAI,QAAQ,iBAAiB,KAAG,MASrE,CAAC"}
@@ -0,0 +1,127 @@
1
+ import { STATUS_COLOR_PENDING, STATUS_COLOR_APPROVED, STATUS_COLOR_REJECTED, STATUS_COLOR_PROCESSING, STATUS_COLOR_AWAITING, STATUS_COLOR_IN_PROGRESS, STATUS_COLOR_COMPLETED, STATUS_COLOR_CANCELLED, STATUS_COLOR_FAILED, STATUS_COLOR_DEFAULT, WITHDRAWAL_STATUS_PENDING_REVIEW, WITHDRAWAL_STATUS_APPROVED, WITHDRAWAL_STATUS_REJECTED, WITHDRAWAL_STATUS_PROCESSING, WITHDRAWAL_STATUS_AWAITING_LIQUIDATION, WITHDRAWAL_STATUS_LIQUIDATION_IN_PROGRESS, WITHDRAWAL_STATUS_COMPLETED, WITHDRAWAL_STATUS_CANCELLED, WITHDRAWAL_STATUS_FAILED, WITHDRAWAL_STATUS_LABEL_PENDING_REVIEW, WITHDRAWAL_STATUS_LABEL_APPROVED, WITHDRAWAL_STATUS_LABEL_REJECTED, WITHDRAWAL_STATUS_LABEL_PROCESSING, WITHDRAWAL_STATUS_LABEL_AWAITING_LIQUIDATION, WITHDRAWAL_STATUS_LABEL_LIQUIDATION_IN_PROGRESS, WITHDRAWAL_STATUS_LABEL_COMPLETED, WITHDRAWAL_STATUS_LABEL_CANCELLED, WITHDRAWAL_STATUS_LABEL_FAILED, WITHDRAWAL_TYPE_FULL_CASH, WITHDRAWAL_TYPE_PARTIAL_CASH, WITHDRAWAL_TYPE_LABEL_FULL_CASH, WITHDRAWAL_TYPE_LABEL_PARTIAL_CASH, WITHDRAWAL_REASON_INVESTMENT_STRATEGY, WITHDRAWAL_REASON_PERSONAL_EXPENSES, WITHDRAWAL_REASON_EMERGENCY, WITHDRAWAL_REASON_OTHER, WITHDRAWAL_REASON_LABEL_INVESTMENT_STRATEGY, WITHDRAWAL_REASON_LABEL_PERSONAL_EXPENSES, WITHDRAWAL_REASON_LABEL_EMERGENCY, WITHDRAWAL_REASON_LABEL_OTHER, LIQUIDATION_STATUS_PENDING, LIQUIDATION_STATUS_TRADES_CREATED, LIQUIDATION_STATUS_EXECUTED, LIQUIDATION_STATUS_SETTLED, LIQUIDATION_STATUS_FAILED, LIQUIDATION_STATUS_LABEL_PENDING, LIQUIDATION_STATUS_LABEL_TRADES_CREATED, LIQUIDATION_STATUS_LABEL_EXECUTED, LIQUIDATION_STATUS_LABEL_SETTLED, LIQUIDATION_STATUS_LABEL_FAILED, } from '@cranberry-money/shared-constants';
2
+ /**
3
+ * Get the color class for a withdrawal status
4
+ *
5
+ * @param status - The withdrawal status
6
+ * @returns The corresponding color class string
7
+ *
8
+ * @example
9
+ * getStatusColor('pending_review'); // returns 'text-warning-600'
10
+ * getStatusColor('completed'); // returns 'text-success-600'
11
+ */
12
+ export const getStatusColor = (status) => {
13
+ const statusColors = {
14
+ [WITHDRAWAL_STATUS_PENDING_REVIEW]: STATUS_COLOR_PENDING,
15
+ [WITHDRAWAL_STATUS_APPROVED]: STATUS_COLOR_APPROVED,
16
+ [WITHDRAWAL_STATUS_REJECTED]: STATUS_COLOR_REJECTED,
17
+ [WITHDRAWAL_STATUS_PROCESSING]: STATUS_COLOR_PROCESSING,
18
+ [WITHDRAWAL_STATUS_AWAITING_LIQUIDATION]: STATUS_COLOR_AWAITING,
19
+ [WITHDRAWAL_STATUS_LIQUIDATION_IN_PROGRESS]: STATUS_COLOR_IN_PROGRESS,
20
+ [WITHDRAWAL_STATUS_COMPLETED]: STATUS_COLOR_COMPLETED,
21
+ [WITHDRAWAL_STATUS_CANCELLED]: STATUS_COLOR_CANCELLED,
22
+ [WITHDRAWAL_STATUS_FAILED]: STATUS_COLOR_FAILED,
23
+ };
24
+ return statusColors[status] || STATUS_COLOR_DEFAULT;
25
+ };
26
+ /**
27
+ * Get the display label for a withdrawal status
28
+ *
29
+ * @param status - The withdrawal status
30
+ * @returns The human-readable label
31
+ *
32
+ * @example
33
+ * getStatusLabel('pending_review'); // returns 'Pending Review'
34
+ * getStatusLabel('liquidation_in_progress'); // returns 'Liquidation in Progress'
35
+ */
36
+ export const getStatusLabel = (status) => {
37
+ const statusLabels = {
38
+ [WITHDRAWAL_STATUS_PENDING_REVIEW]: WITHDRAWAL_STATUS_LABEL_PENDING_REVIEW,
39
+ [WITHDRAWAL_STATUS_APPROVED]: WITHDRAWAL_STATUS_LABEL_APPROVED,
40
+ [WITHDRAWAL_STATUS_REJECTED]: WITHDRAWAL_STATUS_LABEL_REJECTED,
41
+ [WITHDRAWAL_STATUS_PROCESSING]: WITHDRAWAL_STATUS_LABEL_PROCESSING,
42
+ [WITHDRAWAL_STATUS_AWAITING_LIQUIDATION]: WITHDRAWAL_STATUS_LABEL_AWAITING_LIQUIDATION,
43
+ [WITHDRAWAL_STATUS_LIQUIDATION_IN_PROGRESS]: WITHDRAWAL_STATUS_LABEL_LIQUIDATION_IN_PROGRESS,
44
+ [WITHDRAWAL_STATUS_COMPLETED]: WITHDRAWAL_STATUS_LABEL_COMPLETED,
45
+ [WITHDRAWAL_STATUS_CANCELLED]: WITHDRAWAL_STATUS_LABEL_CANCELLED,
46
+ [WITHDRAWAL_STATUS_FAILED]: WITHDRAWAL_STATUS_LABEL_FAILED,
47
+ };
48
+ return statusLabels[status] || status;
49
+ };
50
+ /**
51
+ * Get the display label for a withdrawal type
52
+ *
53
+ * @param type - The withdrawal type
54
+ * @returns The human-readable label
55
+ *
56
+ * @example
57
+ * getWithdrawalTypeLabel('full_cash'); // returns 'Full Cash'
58
+ * getWithdrawalTypeLabel('partial_cash'); // returns 'Partial Cash'
59
+ */
60
+ export const getWithdrawalTypeLabel = (type) => {
61
+ const typeLabels = {
62
+ [WITHDRAWAL_TYPE_FULL_CASH]: WITHDRAWAL_TYPE_LABEL_FULL_CASH,
63
+ [WITHDRAWAL_TYPE_PARTIAL_CASH]: WITHDRAWAL_TYPE_LABEL_PARTIAL_CASH,
64
+ };
65
+ return typeLabels[type] || type;
66
+ };
67
+ /**
68
+ * Get the display label for a withdrawal reason
69
+ *
70
+ * @param reason - The withdrawal reason (optional)
71
+ * @returns The human-readable label
72
+ *
73
+ * @example
74
+ * getReasonLabel('investment_strategy'); // returns 'Investment Strategy'
75
+ * getReasonLabel(null); // returns 'Not specified'
76
+ */
77
+ export const getReasonLabel = (reason) => {
78
+ if (!reason)
79
+ return 'Not specified';
80
+ const reasonLabels = {
81
+ [WITHDRAWAL_REASON_INVESTMENT_STRATEGY]: WITHDRAWAL_REASON_LABEL_INVESTMENT_STRATEGY,
82
+ [WITHDRAWAL_REASON_PERSONAL_EXPENSES]: WITHDRAWAL_REASON_LABEL_PERSONAL_EXPENSES,
83
+ [WITHDRAWAL_REASON_EMERGENCY]: WITHDRAWAL_REASON_LABEL_EMERGENCY,
84
+ [WITHDRAWAL_REASON_OTHER]: WITHDRAWAL_REASON_LABEL_OTHER,
85
+ };
86
+ return reasonLabels[reason] || reason;
87
+ };
88
+ /**
89
+ * Get the color class for a liquidation status
90
+ *
91
+ * @param status - The liquidation status
92
+ * @returns The corresponding color class string
93
+ *
94
+ * @example
95
+ * getLiquidationStatusColor('pending'); // returns 'text-warning-600'
96
+ * getLiquidationStatusColor('settled'); // returns 'text-success-600'
97
+ */
98
+ export const getLiquidationStatusColor = (status) => {
99
+ const statusColors = {
100
+ [LIQUIDATION_STATUS_PENDING]: 'text-warning-600',
101
+ [LIQUIDATION_STATUS_TRADES_CREATED]: 'text-primary-600',
102
+ [LIQUIDATION_STATUS_EXECUTED]: 'text-accent-secondary',
103
+ [LIQUIDATION_STATUS_SETTLED]: 'text-success-600',
104
+ [LIQUIDATION_STATUS_FAILED]: 'text-error-600',
105
+ };
106
+ return statusColors[status] || 'text-content-muted';
107
+ };
108
+ /**
109
+ * Get the display label for a liquidation status
110
+ *
111
+ * @param status - The liquidation status
112
+ * @returns The human-readable label
113
+ *
114
+ * @example
115
+ * getLiquidationStatusLabel('trades_created'); // returns 'Trades Created'
116
+ * getLiquidationStatusLabel('executed'); // returns 'Executed'
117
+ */
118
+ export const getLiquidationStatusLabel = (status) => {
119
+ const statusLabels = {
120
+ [LIQUIDATION_STATUS_PENDING]: LIQUIDATION_STATUS_LABEL_PENDING,
121
+ [LIQUIDATION_STATUS_TRADES_CREATED]: LIQUIDATION_STATUS_LABEL_TRADES_CREATED,
122
+ [LIQUIDATION_STATUS_EXECUTED]: LIQUIDATION_STATUS_LABEL_EXECUTED,
123
+ [LIQUIDATION_STATUS_SETTLED]: LIQUIDATION_STATUS_LABEL_SETTLED,
124
+ [LIQUIDATION_STATUS_FAILED]: LIQUIDATION_STATUS_LABEL_FAILED,
125
+ };
126
+ return statusLabels[status] || status;
127
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cranberry-money/shared-utils",
3
- "version": "8.17.7",
3
+ "version": "8.17.9",
4
4
  "description": "Shared utility functions for MyPortfolio platform",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/dist/auth.d.ts DELETED
@@ -1,55 +0,0 @@
1
- /**
2
- * Authentication and token management utilities
3
- */
4
- import type { DeviceInfo, TokenRefreshResponse, TokenRefreshError, AutoRefreshHandler } from '@cranberry-money/shared-types';
5
- /**
6
- * Check if a token has expired based on its expiration timestamp
7
- * @param expiresAt - The expiration timestamp
8
- * @returns true if token is expired, false otherwise
9
- */
10
- export declare function isTokenExpired(expiresAt: string): boolean;
11
- /**
12
- * Check if a token will expire within a specified number of minutes
13
- * @param expiresAt - The expiration timestamp
14
- * @param minutesBeforeExpiry - Minutes before expiry to consider as "expiring soon"
15
- * @returns true if token is expiring soon, false otherwise
16
- */
17
- export declare function isTokenExpiringSoon(expiresAt: string, minutesBeforeExpiry?: number): boolean;
18
- /**
19
- * Get the remaining time until token expiry in minutes
20
- * @param expiresAt - The expiration timestamp
21
- * @returns Number of minutes until expiry
22
- */
23
- export declare function getTimeUntilExpiry(expiresAt: string): number;
24
- /**
25
- * Format the time until expiry in a human-readable format
26
- * @param expiresAt - The expiration timestamp
27
- * @returns Formatted time string
28
- */
29
- export declare function formatTimeUntilExpiry(expiresAt: string): string;
30
- /**
31
- * Parse device information from user agent string
32
- * @param userAgent - The user agent string
33
- * @returns Parsed device info
34
- */
35
- export declare function parseDeviceInfo(userAgent: string): DeviceInfo;
36
- /**
37
- * Check if token refresh was successful
38
- * @param response - The refresh response
39
- * @returns true if refresh was successful, false otherwise
40
- */
41
- export declare function isRefreshSuccess(response: TokenRefreshResponse): boolean;
42
- /**
43
- * Get error message from token refresh error
44
- * @param error - The refresh error
45
- * @returns Error message string
46
- */
47
- export declare function getRefreshErrorMessage(error: TokenRefreshError): string;
48
- /**
49
- * Create an auto-refresh handler for tokens
50
- * @param refreshCallback - Callback function to refresh token
51
- * @param checkInterval - Interval in milliseconds to check for refresh
52
- * @returns Auto refresh handler with start/stop methods
53
- */
54
- export declare function createAutoRefreshHandler(refreshCallback: () => Promise<void>, checkInterval?: number): AutoRefreshHandler;
55
- //# sourceMappingURL=auth.d.ts.map
@@ -1,65 +0,0 @@
1
- /**
2
- * Badge Status Utilities - Status-specific badge functions
3
- *
4
- * This module provides pre-configured badge functions for common status types
5
- * in the MyPortfolio platform. It builds on top of the core badge system.
6
- */
7
- import type { StatusBadgeStyle, TradeStatus, WithdrawalStatus, LiquidationStatus, TargetTradeStatus } from '@cranberry-money/shared-types';
8
- import type { BadgeSize } from '@cranberry-money/shared-types';
9
- /**
10
- * Creates a badge for trade status
11
- *
12
- * @param status - Trade status constant
13
- * @param size - Badge size (default: 'md')
14
- * @returns Badge style with display text and accessibility attributes
15
- *
16
- * @example
17
- * ```typescript
18
- * const badge = getTradeStatusBadge(TRADE_STATUS_SETTLED);
19
- * // Returns badge with success variant and "Settled" display text
20
- * ```
21
- */
22
- export declare function getTradeStatusBadge(status: TradeStatus, size?: BadgeSize): StatusBadgeStyle;
23
- /**
24
- * Creates a badge for withdrawal status
25
- *
26
- * @param status - Withdrawal status constant
27
- * @param size - Badge size (default: 'md')
28
- * @returns Badge style with display text and accessibility attributes
29
- *
30
- * @example
31
- * ```typescript
32
- * const badge = getWithdrawalStatusBadge(WITHDRAWAL_STATUS_APPROVED);
33
- * // Returns badge with success variant and "Approved" display text
34
- * ```
35
- */
36
- export declare function getWithdrawalStatusBadge(status: WithdrawalStatus, size?: BadgeSize): StatusBadgeStyle;
37
- /**
38
- * Creates a badge for liquidation status
39
- *
40
- * @param status - Liquidation status constant
41
- * @param size - Badge size (default: 'md')
42
- * @returns Badge style with display text and accessibility attributes
43
- *
44
- * @example
45
- * ```typescript
46
- * const badge = getLiquidationStatusBadge(LIQUIDATION_STATUS_SETTLED);
47
- * // Returns badge with success variant and "Settled" display text
48
- * ```
49
- */
50
- export declare function getLiquidationStatusBadge(status: LiquidationStatus, size?: BadgeSize): StatusBadgeStyle;
51
- /**
52
- * Creates a badge for target trade status
53
- *
54
- * @param status - Target trade status constant
55
- * @param size - Badge size (default: 'md')
56
- * @returns Badge style with display text and accessibility attributes
57
- *
58
- * @example
59
- * ```typescript
60
- * const badge = getTargetTradeStatusBadge(TARGET_TRADE_STATUS_PENDING);
61
- * // Returns badge with warning variant and "Pending" display text
62
- * ```
63
- */
64
- export declare function getTargetTradeStatusBadge(status: TargetTradeStatus, size?: BadgeSize): StatusBadgeStyle;
65
- //# sourceMappingURL=badge-status.d.ts.map
package/dist/badge.d.ts DELETED
@@ -1,41 +0,0 @@
1
- /**
2
- * Badge System Core - Type definitions and factory function
3
- *
4
- * This module provides a standardized way to create and style badges.
5
- * It ensures consistency in colors, typography, and semantic meaning
6
- * while maintaining accessibility standards.
7
- *
8
- * Note: The actual style classes are designed to work with Tailwind CSS
9
- * and assume a specific color system is in place.
10
- */
11
- import type { BadgeVariant, BadgeSize, BadgeConfig, BadgeStyle } from '@cranberry-money/shared-types';
12
- /**
13
- * Creates a badge style configuration with appropriate CSS classes
14
- *
15
- * @param config - Badge configuration options
16
- * @param variantStyles - Optional custom variant styles (defaults to DEFAULT_BADGE_VARIANTS)
17
- * @param sizeStyles - Optional custom size styles (defaults to DEFAULT_BADGE_SIZES)
18
- * @returns Badge style object with className and accessibility attributes
19
- *
20
- * @example
21
- * ```typescript
22
- * // Create a success badge
23
- * const successBadge = createBadge({ variant: 'success' });
24
- * // Returns: { className: 'inline-flex items-center rounded-md font-medium whitespace-nowrap transition-colors bg-success-900/80 text-success-300 text-xs px-2 py-1', ariaLabel: 'success status' }
25
- *
26
- * // Create a large warning badge with custom class
27
- * const warningBadge = createBadge({ variant: 'warning', size: 'lg', className: 'ml-2' });
28
- *
29
- * // Use custom variant styles
30
- * const customVariants = { primary: 'bg-blue-500 text-white', ... };
31
- * const customBadge = createBadge({ variant: 'primary' }, customVariants);
32
- * ```
33
- */
34
- export declare function createBadge({ variant, size, className }: BadgeConfig, variantStyles?: Record<BadgeVariant, string>, sizeStyles?: Record<BadgeSize, string>): BadgeStyle;
35
- /**
36
- * Export the default style mappings for consumers who want to use them directly
37
- * or extend them with their own styles
38
- */
39
- export declare const BADGE_VARIANTS: Record<BadgeVariant, string>;
40
- export declare const BADGE_SIZES: Record<BadgeSize, string>;
41
- //# sourceMappingURL=badge.d.ts.map
@@ -1,66 +0,0 @@
1
- /**
2
- * Instrument and market data formatting utilities
3
- */
4
- import type { InstrumentTypeInfo, InstrumentBasicInfo, PriceChangeResult, PriceSnapshot, FormattedPriceChange, TradeableInstrument, MarketDataInfo } from '@cranberry-money/shared-types';
5
- /**
6
- * Format instrument price with currency symbol
7
- * @param price - The price as string
8
- * @param currency - The currency code
9
- * @returns Formatted price with currency symbol
10
- */
11
- export declare function formatInstrumentPrice(price: string, currency?: string | null): string;
12
- /**
13
- * Get currency symbol for display
14
- * @param currency - The currency code
15
- * @returns Currency symbol
16
- */
17
- export declare function getCurrencySymbol(currency?: string | null): string;
18
- /**
19
- * Determine instrument type based on flags
20
- * @param instrument - The instrument with type flags
21
- * @returns Instrument type string
22
- */
23
- export declare function getInstrumentType(instrument: InstrumentTypeInfo): string;
24
- /**
25
- * Format instrument display name with symbol
26
- * @param instrument - The instrument with symbol and name
27
- * @returns Formatted display name
28
- */
29
- export declare function formatInstrumentName(instrument: InstrumentBasicInfo): string;
30
- /**
31
- * Calculate price change from snapshot
32
- * @param snapshot - The price snapshot
33
- * @returns Price change calculation result
34
- */
35
- export declare function calculatePriceChange(snapshot: PriceSnapshot): PriceChangeResult;
36
- /**
37
- * Format price change with appropriate color class
38
- * @param snapshot - The price snapshot
39
- * @returns Formatted price change with color class
40
- */
41
- export declare function formatPriceChange(snapshot: PriceSnapshot): FormattedPriceChange;
42
- /**
43
- * Check if instrument is actively tradeable
44
- * @param instrument - The instrument with trading flags
45
- * @returns true if tradeable, false otherwise
46
- */
47
- export declare function isInstrumentTradeable(instrument: TradeableInstrument): boolean;
48
- /**
49
- * Format market cap value
50
- * @param marketCap - The market cap value as string or null
51
- * @returns Formatted market cap string
52
- */
53
- export declare function formatMarketCap(marketCap: string | null | undefined): string;
54
- /**
55
- * Format trading volume
56
- * @param volume - The volume number
57
- * @returns Formatted volume string
58
- */
59
- export declare function formatVolume(volume: number): string;
60
- /**
61
- * Check if market data is available
62
- * @param marketData - The market data to check
63
- * @returns true if market data is available, false otherwise
64
- */
65
- export declare function hasMarketData(marketData: MarketDataInfo): boolean;
66
- //# sourceMappingURL=instruments.d.ts.map
@@ -1,42 +0,0 @@
1
- import type { MessageFieldValidation, BaseFormValidation } from '@cranberry-money/shared-types';
2
- /**
3
- * Portfolio selection form validation interface
4
- */
5
- export interface PortfolioSelectionValidation extends BaseFormValidation {
6
- readonly selectedTemplate: MessageFieldValidation;
7
- }
8
- /**
9
- * Portfolio selection state interface
10
- */
11
- export interface PortfolioSelectionState {
12
- readonly selectedTemplateUuid: string | null;
13
- readonly viewingDetailsForUuid?: string | null;
14
- }
15
- /**
16
- * Validates if a portfolio template is selected
17
- *
18
- * @param selectedTemplateUuid - The UUID of the selected template
19
- * @returns true if a template is selected, false otherwise
20
- *
21
- * @example
22
- * isValidTemplateSelection('123-456'); // returns true
23
- * isValidTemplateSelection(null); // returns false
24
- * isValidTemplateSelection(''); // returns false
25
- */
26
- export declare const isValidTemplateSelection: (selectedTemplateUuid: string | null) => boolean;
27
- /**
28
- * Comprehensive validation for portfolio selection form
29
- *
30
- * @param state - The portfolio selection state
31
- * @returns Validation object with field-level and form-level validity
32
- *
33
- * @example
34
- * const state = { selectedTemplateUuid: '123-456' };
35
- * validatePortfolioSelection(state);
36
- * // returns {
37
- * // selectedTemplate: { isValid: true, message: '' },
38
- * // isFormValid: true
39
- * // }
40
- */
41
- export declare const validatePortfolioSelection: (state: PortfolioSelectionState) => PortfolioSelectionValidation;
42
- //# sourceMappingURL=portfolio-validation.d.ts.map