20 Commits
Author SHA1 Message Date
mohmdsdg d7a743ba09 feat(trade): separate gross price, fee and net payable into three colored rows 2026-10-11 22:44:10 +03:30
mohmdsdgandCursor 751d9a34e3 Reuse the live price stream for the product catalog and physical delivery list.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-10 22:11:55 +03:30
mohmdsdgandCursor 6facf5d72d Show greater price alerts above the product name and smaller ones below.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 20:09:45 +03:30
mohmdsdg da68f0a582 Reload wallet assets after a physical delivery request.
The kashkool balance updates with the same assets refresh as the other user apps.
2026-09-29 20:20:28 +03:30
mohmdsdg 9cb0979606 chore: sync price monitor updates 2026-09-28 18:04:49 +03:30
mohmdsdg f778064aef chore: sync latest updates 2026-09-28 14:52:43 +03:30
mohmdsdg 1ac5095177 chore: sync project updates 2026-09-28 14:12:30 +03:30
mohmdsdgandCursor bc64ff47b2 Open the price stream on the TV board with the TV key header.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 22:27:46 +03:30
mohmdsdgandCursor 8083c4f06d Match the TV header quote to the product list buy and sell prices.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 21:42:17 +03:30
mohmdsdgandCopilot 7770c763cc chore: sync graphify and UI updates
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-09-22 11:36:14 +03:30
mohmdsdgandCursor b4a8546ce6 Stop applying special pricing twice on live quotes so sell stays below buy.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 23:59:55 +03:30
mohmdsdgandCursor 3b83eac099 Keep gold quotes live from last and apply SSE catalog list so cards refresh without a page reload.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 18:20:06 +03:30
mohmdsdgandCursor c623a32bb5 fix: colleague price products use DealProduct, not indexGold
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 22:11:59 +03:30
mohmdsdgandCursor 03f509d83e Keep the TV MontZar credit logo small and load it from bundled assets.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 12:23:13 +03:30
mohmdsdgandCursor a33f130341 Prefer password login on the home screen with register and forgot-password actions.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 17:33:28 +03:30
mohmdsdgandCursor 7ab78bd550 Stop multiplying colleague prices by weight and fee from unit price.
Colleague quotes are per piece, and the settings service charge is a percent of that price times count.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 22:21:08 +03:30
mohmdsdg 71da064cab fix some things 2026-09-14 12:57:53 +03:30
mohmdsdgandCursor 569e62fef4 Hide redundant amount label between product title and price.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 20:43:45 +03:30
mohmdsdgandCursor fcc7c70310 Merge origin/kashkool into kashkool.
Keep the /gold trade product fix and bring in the remote catalog, account menu, and product-page updates.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 18:38:12 +03:30
mohmdsdg fdc24083cf fix price 2026-09-13 18:33:38 +03:30
51 changed files with 42960 additions and 290 deletions
+1
View File
@@ -0,0 +1 @@
graphify-out/graph.json merge=graphify
+12
View File
@@ -0,0 +1,12 @@
{
"0": "useTvMonitorPage",
"1": "ref_utils",
"2": "index.vue",
"3": "productPrice.ts",
"4": "useNewPhysicalRequestPage.ts",
"5": "api/products.ts",
"6": "priceSocket.ts",
"7": "priceSocketState.ts",
"8": "useProductsPageData.ts",
"9": "AuthPriceStream"
}
+1
View File
@@ -0,0 +1 @@
{"0": "d7734412cf0800ce", "1": "67d1701e4c6cea74", "2": "a1988eda2ebb6afe", "3": "18bc618fd6f328bb", "4": "b16e1aea09ac331f", "5": "8d51306eb7d0daf2", "6": "fe2bcdb916bbc9f9", "7": "ac69b3434e72782c", "8": "004ed482633014da", "9": "08b88f1fc8c91c56"}
+1
View File
@@ -0,0 +1 @@
.
@@ -0,0 +1,10 @@
{
"0": "useTvMonitorPage",
"1": "useTvMonitorPage.ts",
"2": "index.vue",
"3": "productPrice.ts",
"4": "getProductBaseBuyPrice",
"5": "ref_models",
"6": "isTvProductPriceInactive",
"7": "applyPriceOffsetPercent"
}
+140
View File
@@ -0,0 +1,140 @@
# Graph Report - ghatreh_user (2026-09-27)
## Corpus Check
- 598 files · ~506,745 words
- Verdict: corpus is large enough that graph structure adds value.
- Unclassified: 51 file(s) not represented in the graph (top: .less 25, .eot 6, .ttf 6)
## Summary
- 84 nodes · 154 edges · 8 communities
- Extraction: 91% EXTRACTED · 9% INFERRED · 0% AMBIGUOUS · INFERRED: 14 edges (avg confidence: 0.85)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `8083c4f0`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- useTvMonitorPage
- useTvMonitorPage.ts
- index.vue
- productPrice.ts
- getProductBaseBuyPrice
- ref_models
- isTvProductPriceInactive
- applyPriceOffsetPercent
## God Nodes (most connected - your core abstractions)
1. `useTvMonitorPage()` - 25 edges
2. `getProductBaseBuyPrice()` - 10 edges
3. `getProductBuyPrice()` - 7 edges
4. `getProductBaseSellPrice()` - 6 edges
5. `getProductSellPrice()` - 6 edges
6. `productUsesLastPriceIfZero()` - 5 edges
7. `applyPriceOffsetPercent()` - 5 edges
8. `isProductPriceInactive()` - 5 edges
9. `formatTvPrice()` - 5 edges
10. `cashFeeOptions()` - 4 edges
## Surprising Connections (you probably didn't know these)
- `useTvMonitorPage()` --indirect_call--> `isShowOnTv()` [INFERRED]
src/views/tv/composables/useTvMonitorPage.ts → src/views/tv/composables/useTvMonitorPage.ts _Bridges community 1 → community 0_
- `colleagueSideUnit()` --calls--> `getColleagueSourcedUnitPrice()` [EXTRACTED]
src/utils/productPrice.ts → src/utils/productPrice.ts _Bridges community 4 → community 7_
- `getProductBuyPrice()` --calls--> `getProductBaseBuyPrice()` [EXTRACTED]
src/utils/productPrice.ts → src/utils/productPrice.ts _Bridges community 4 → community 3_
- `getTvProductBuyPrice()` --calls--> `getProductBuyPrice()` [EXTRACTED]
src/utils/productPrice.ts → src/utils/productPrice.ts _Bridges community 3 → community 6_
- `isTvProductPriceInactive()` --calls--> `isProductPriceInactive()` [EXTRACTED]
src/utils/productPrice.ts → src/utils/productPrice.ts _Bridges community 4 → community 6_
## Import Cycles
- None detected.
## Communities (8 total, 0 thin omitted)
### Community 0 - "useTvMonitorPage"
Cohesion: 0.14
Nodes (17): floorTvToman(), formatTvPrice(), parseTvNews(), useTvMonitorPage(), hideCursorSoon(), isProductTvInactive(), liveQuoteLabel(), loadProducts() (+9 more)
### Community 1 - "useTvMonitorPage.ts"
Cohesion: 0.17
Nodes (15): ref_api, ref_assets, ref_moment, ref_moment_jalaali, ref_store, ref_utils, ref_vue, ref_vueuse_core (+7 more)
### Community 2 - "index.vue"
Cohesion: 0.19
Nodes (15): ref_components, ref_views, coinColumns, extraTickerLoop, loopNews(), loopTicker(), marqueeCopies(), newsDuration() (+7 more)
### Community 3 - "productPrice.ts"
Cohesion: 0.44
Nodes (9): buyCashFee(), cashFeeOptions(), getProductBuyPrice(), getProductSellPrice(), hasProductUnitWeight(), isProductWithoutDisplayPrice(), productPriceAmountFactor(), productUsesLiveBoardQuote() (+1 more)
### Community 4 - "getProductBaseBuyPrice"
Cohesion: 0.43
Nodes (8): colleagueSideUnit(), getProductBaseBuyPrice(), getProductBaseSellPrice(), getReferenceProductBaseBuyPrice(), hasReferenceReadingMethod(), isProductPriceInactive(), isProductVisible(), productUsesLastPriceIfZero()
### Community 5 - "ref_models"
Cohesion: 0.40
Nodes (4): ref_models, CountPInventory, PInventory, Product
### Community 6 - "isTvProductPriceInactive"
Cohesion: 0.50
Nodes (5): getTvProductBuyPrice(), getTvProductSellPrice(), isTvProductPriceInactive(), tvBuyUnitPrice(), tvSellUnitPrice()
### Community 7 - "applyPriceOffsetPercent"
Cohesion: 0.67
Nodes (3): applyPriceOffsetPercent(), getColleagueSourcedUnitPrice(), resolvePriceOffsetRatio()
## Knowledge Gaps
- **6 isolated node(s):** `Product`, `PInventory`, `CountPInventory`, `{ theme, themeVars, toggleTheme }`, `{
rootEl,
brandName,
brandLogo,
nowLabel,
dateLabel,
parsianCoins,
bankCoins,
hasCoinBoard,
hasBoardContent,
tickerProducts,
tickerTitle,
extraTickerProducts,
extraTickerTitle,
tvNewsItems,
newsTickerTitle,
statusBanner,
showMainQuote,
mainQuoteReady,
mainQuoteReady,
liveBuy,
liveSell,
isLive,
isFullscreen,
cursorHidden,
loading,
productWeightLabel,
tickerItemLabel,
isProductTvInactive,
productBuyLabel,
productSellLabel,
liveQuoteLabel,
toggleFullscreen,
}` (+1 more)
These have ≤1 connection - possible missing edges or undocumented components. (Counts symbols only; 18 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `useTvMonitorPage()` connect `useTvMonitorPage` to `useTvMonitorPage.ts`?**
_High betweenness centrality (0.342) - this node is a cross-community bridge._
- **Why does `formatTvPrice()` connect `useTvMonitorPage` to `useTvMonitorPage.ts`?**
_High betweenness centrality (0.026) - this node is a cross-community bridge._
- **Why does `getProductBaseBuyPrice()` connect `getProductBaseBuyPrice` to `productPrice.ts`, `applyPriceOffsetPercent`?**
_High betweenness centrality (0.004) - this node is a cross-community bridge._
- **Are the 13 inferred relationships involving `useTvMonitorPage()` (e.g. with `isBankCoin()` and `isGoldBar()`) actually correct?**
_`useTvMonitorPage()` has 13 INFERRED edges - model-reasoned connections that need verification._
- **What connects `Product`, `PInventory`, `CountPInventory` to the rest of the system?**
_6 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `useTvMonitorPage` be split into smaller, more focused modules?**
_Cohesion score 0.1380952380952381 - nodes in this community are weakly interconnected._
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,13 @@
{
"0": "useTvMonitorPage",
"1": "ref_utils",
"2": "index.vue",
"3": "productPrice.ts",
"4": "forceReconnect",
"5": "api/products.ts",
"6": "priceSocket.ts",
"7": "connect",
"8": "useProductsPageData.ts",
"9": "AuthPriceStream",
"10": "initPriceRealtimeChannel"
}
+119
View File
@@ -0,0 +1,119 @@
# Graph Report - ghatreh_user (2026-09-28)
## Corpus Check
- 598 files · ~506,942 words
- Verdict: corpus is large enough that graph structure adds value.
- Unclassified: 51 file(s) not represented in the graph (top: .less 25, .eot 6, .ttf 6)
## Summary
- 196 nodes · 413 edges · 11 communities (10 shown, 1 thin omitted)
- Extraction: 93% EXTRACTED · 7% INFERRED · 0% AMBIGUOUS · INFERRED: 27 edges (avg confidence: 0.85)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `1ac50951`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- useTvMonitorPage
- ref_utils
- index.vue
- productPrice.ts
- forceReconnect
- api/products.ts
- priceSocket.ts
- connect
- useProductsPageData.ts
- AuthPriceStream
- initPriceRealtimeChannel
## God Nodes (most connected - your core abstractions)
1. `useTvMonitorPage()` - 28 edges
2. `connect()` - 15 edges
3. `getProductBaseBuyPrice()` - 10 edges
4. `touchStreamActivity()` - 9 edges
5. `runFallbackPoll()` - 9 edges
6. `bindStreamEvents()` - 9 edges
7. `forceReconnect()` - 9 edges
8. `maybeShowNetworkAlert()` - 8 edges
9. `disconnect()` - 8 edges
10. `applyProductsList()` - 8 edges
## Surprising Connections (you probably didn't know these)
- `connect()` --calls--> `AuthPriceStream` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 9 → community 7_
- `connect()` --calls--> `resolveStreamUrl()` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 10 → community 7_
- `forceReconnect()` --calls--> `clearReconnectTimer()` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 7 → community 4_
- `connect()` --calls--> `touchStreamActivity()` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 1 → community 7_
- `connect()` --calls--> `stopFallbackPolling()` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 6 → community 7_
## Import Cycles
- None detected.
## Communities (11 total, 1 thin omitted)
### Community 0 - "useTvMonitorPage"
Cohesion: 0.09
Nodes (33): ref_api, ref_assets, ref_moment, ref_moment_jalaali, ref_vueuse_core, bankCoinRank(), floorTvToman(), formatTvPrice() (+25 more)
### Community 1 - "ref_utils"
Cohesion: 0.23
Nodes (15): ref_composables, ref_store, ref_utils, applyAppNotificationFromStream(), applyLastFromStream(), applySettingsFromStream(), applyUnreadCountFromStreamPayload(), bindStreamEvents() (+7 more)
### Community 2 - "index.vue"
Cohesion: 0.19
Nodes (15): ref_components, ref_vue, coinColumns, extraTickerLoop, loopNews(), loopTicker(), marqueeCopies(), newsDuration() (+7 more)
### Community 3 - "productPrice.ts"
Cohesion: 0.19
Nodes (25): applyPriceOffsetPercent(), buyCashFee(), cashFeeOptions(), colleagueSideUnit(), getColleagueSourcedUnitPrice(), getProductBaseBuyPrice(), getProductBaseSellPrice(), getProductBuyPrice() (+17 more)
### Community 4 - "forceReconnect"
Cohesion: 0.21
Nodes (16): bindBrowserNetworkListeners(), forceReconnect(), isPageVisible(), maybeShowNetworkAlert(), notifyPriceLastFetchFailed(), onBrowserOffline(), onBrowserOnline(), onPageShow() (+8 more)
### Community 5 - "api/products.ts"
Cohesion: 0.15
Nodes (5): ref_models, TvServerTime, CountPInventory, PInventory, Product
### Community 6 - "priceSocket.ts"
Cohesion: 0.16
Nodes (12): ref_ant_design_vue, ref_views, clearFallbackPollTimer(), clearPriceNetworkAlert(), getPriceSourceStaleMs(), isMobileDevice(), isRealPriceOutage(), onTvBoard() (+4 more)
### Community 7 - "connect"
Cohesion: 0.36
Nodes (10): clearConnectingLifecycle(), clearReconnectTimer(), connect(), disconnect(), disconnectSourceOnly(), handleStreamLost(), markConnectingLifecycle(), scheduleReconnect() (+2 more)
### Community 8 - "useProductsPageData.ts"
Cohesion: 0.12
Nodes (31): applyProductsList(), applyProductsListFromSocket(), applySocketProductList(), changeProductsTab(), flagOff(), flagOn(), initialized, initProductsPageData() (+23 more)
### Community 10 - "initPriceRealtimeChannel"
Cohesion: 0.60
Nodes (5): initPriceRealtimeChannel(), isPriceWebSocketEnabled(), isTruthySetting(), resolveStreamPath(), resolveStreamUrl()
## Knowledge Gaps
- **13 isolated node(s):** `initialized`, `productsActiveKey`, `productsTypeItems`, `productsFirstItems`, `productsItems` (+8 more)
These have ≤1 connection - possible missing edges or undocumented components. (Counts symbols only; 37 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
- **1 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `AuthPriceStream` connect `AuthPriceStream` to `priceSocket.ts`, `connect`?**
_High betweenness centrality (0.035) - this node is a cross-community bridge._
- **Why does `runFallbackPoll()` connect `priceSocket.ts` to `ref_utils`, `forceReconnect`?**
_High betweenness centrality (0.019) - this node is a cross-community bridge._
- **Are the 13 inferred relationships involving `useTvMonitorPage()` (e.g. with `isBankCoin()` and `isGoldBar()`) actually correct?**
_`useTvMonitorPage()` has 13 INFERRED edges - model-reasoned connections that need verification._
- **What connects `initialized`, `productsActiveKey`, `productsTypeItems` to the rest of the system?**
_13 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `useTvMonitorPage` be split into smaller, more focused modules?**
_Cohesion score 0.09309309309309309 - nodes in this community are weakly interconnected._
- **Should `useProductsPageData.ts` be split into smaller, more focused modules?**
_Cohesion score 0.11931818181818182 - nodes in this community are weakly interconnected._
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,10 @@
{
"0": "useTvMonitorPage",
"1": "ref_utils",
"2": "index.vue",
"3": "productPrice.ts",
"5": "api/products.ts",
"6": "priceSocket.ts",
"8": "useProductsPageData.ts",
"9": "AuthPriceStream"
}
+100
View File
@@ -0,0 +1,100 @@
# Graph Report - ghatreh_user (2026-09-28)
## Corpus Check
- 598 files · ~506,836 words
- Verdict: corpus is large enough that graph structure adds value.
- Unclassified: 51 file(s) not represented in the graph (top: .less 25, .eot 6, .ttf 6)
## Summary
- 198 nodes · 409 edges · 8 communities (7 shown, 1 thin omitted)
- Extraction: 93% EXTRACTED · 7% INFERRED · 0% AMBIGUOUS · INFERRED: 28 edges (avg confidence: 0.85)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `9cb09796`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- useTvMonitorPage
- ref_utils
- index.vue
- productPrice.ts
- api/products.ts
- priceSocket.ts
- useProductsPageData.ts
- AuthPriceStream
## God Nodes (most connected - your core abstractions)
1. `useTvMonitorPage()` - 25 edges
2. `connect()` - 15 edges
3. `getProductBaseBuyPrice()` - 10 edges
4. `touchStreamActivity()` - 9 edges
5. `bindStreamEvents()` - 9 edges
6. `forceReconnect()` - 9 edges
7. `runFallbackPoll()` - 8 edges
8. `maybeShowNetworkAlert()` - 8 edges
9. `disconnect()` - 8 edges
10. `applyProductsList()` - 8 edges
## Surprising Connections (you probably didn't know these)
- `connect()` --calls--> `AuthPriceStream` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 9 → community 6_
- `connect()` --calls--> `touchStreamActivity()` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 1 → community 6_
## Import Cycles
- None detected.
## Communities (8 total, 1 thin omitted)
### Community 0 - "useTvMonitorPage"
Cohesion: 0.10
Nodes (30): ref_api, ref_assets, ref_moment, ref_moment_jalaali, ref_vueuse_core, bankCoinRank(), floorTvToman(), formatTvPrice() (+22 more)
### Community 1 - "ref_utils"
Cohesion: 0.23
Nodes (15): ref_composables, ref_store, ref_utils, applyAppNotificationFromStream(), applyLastFromStream(), applySettingsFromStream(), applyUnreadCountFromStreamPayload(), bindStreamEvents() (+7 more)
### Community 2 - "index.vue"
Cohesion: 0.10
Nodes (23): ref_components, ref_views, ref_vue, priceSocketConnected, priceStreamConnectingSince, priceStreamLifecycle, priceStreamList, priceStreamProducts (+15 more)
### Community 3 - "productPrice.ts"
Cohesion: 0.20
Nodes (24): applyPriceOffsetPercent(), buyCashFee(), cashFeeOptions(), getColleagueSourcedUnitPrice(), getProductBaseBuyPrice(), getProductBaseSellPrice(), getProductBuyPrice(), getProductSellPrice() (+16 more)
### Community 5 - "api/products.ts"
Cohesion: 0.15
Nodes (5): ref_models, TvServerTime, CountPInventory, PInventory, Product
### Community 6 - "priceSocket.ts"
Cohesion: 0.11
Nodes (41): ref_ant_design_vue, bindBrowserNetworkListeners(), clearConnectingLifecycle(), clearFallbackPollTimer(), clearPriceNetworkAlert(), clearReconnectTimer(), connect(), disconnect() (+33 more)
### Community 8 - "useProductsPageData.ts"
Cohesion: 0.12
Nodes (31): applyProductsList(), applyProductsListFromSocket(), applySocketProductList(), changeProductsTab(), flagOff(), flagOn(), initialized, initProductsPageData() (+23 more)
## Knowledge Gaps
- **20 isolated node(s):** `Product`, `PInventory`, `CountPInventory`, `priceSocketConnected`, `priceWssEnabled` (+15 more)
These have ≤1 connection - possible missing edges or undocumented components. (Counts symbols only; 43 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
- **1 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `AuthPriceStream` connect `AuthPriceStream` to `priceSocket.ts`?**
_High betweenness centrality (0.035) - this node is a cross-community bridge._
- **Why does `runFallbackPoll()` connect `priceSocket.ts` to `ref_utils`, `index.vue`?**
_High betweenness centrality (0.016) - this node is a cross-community bridge._
- **Are the 14 inferred relationships involving `useTvMonitorPage()` (e.g. with `isBankCoin()` and `isGoldBar()`) actually correct?**
_`useTvMonitorPage()` has 14 INFERRED edges - model-reasoned connections that need verification._
- **What connects `Product`, `PInventory`, `CountPInventory` to the rest of the system?**
_20 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `useTvMonitorPage` be split into smaller, more focused modules?**
_Cohesion score 0.09982174688057041 - nodes in this community are weakly interconnected._
- **Should `index.vue` be split into smaller, more focused modules?**
_Cohesion score 0.10153846153846154 - nodes in this community are weakly interconnected._
- **Should `priceSocket.ts` be split into smaller, more focused modules?**
_Cohesion score 0.10638297872340426 - nodes in this community are weakly interconnected._
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+110
View File
@@ -0,0 +1,110 @@
# Graph Report - ghatreh_user (2026-09-29)
## Corpus Check
- 598 files · ~506,875 words
- Verdict: corpus is large enough that graph structure adds value.
- Unclassified: 51 file(s) not represented in the graph (top: .less 25, .eot 6, .ttf 6)
## Summary
- 208 nodes · 426 edges · 10 communities (9 shown, 1 thin omitted)
- Extraction: 92% EXTRACTED · 8% INFERRED · 0% AMBIGUOUS · INFERRED: 33 edges (avg confidence: 0.85)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `da68f0a5`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- useTvMonitorPage
- ref_utils
- index.vue
- productPrice.ts
- useNewPhysicalRequestPage.ts
- api/products.ts
- priceSocket.ts
- priceSocketState.ts
- useProductsPageData.ts
- AuthPriceStream
## God Nodes (most connected - your core abstractions)
1. `useTvMonitorPage()` - 25 edges
2. `connect()` - 15 edges
3. `getProductBaseBuyPrice()` - 10 edges
4. `bindStreamEvents()` - 9 edges
5. `touchStreamActivity()` - 9 edges
6. `forceReconnect()` - 9 edges
7. `useNewPhysicalRequestPage()` - 8 edges
8. `applyProductsList()` - 8 edges
9. `applySocketProductList()` - 8 edges
10. `disconnect()` - 8 edges
## Surprising Connections (you probably didn't know these)
- `connect()` --calls--> `AuthPriceStream` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 9 → community 6_
- `connect()` --calls--> `bindStreamEvents()` [EXTRACTED]
src/utils/priceSocket.ts → src/utils/priceSocket.ts _Bridges community 1 → community 6_
## Import Cycles
- None detected.
## Communities (10 total, 1 thin omitted)
### Community 0 - "useTvMonitorPage"
Cohesion: 0.10
Nodes (29): ref_assets, ref_moment, ref_moment_jalaali, ref_vueuse_core, bankCoinRank(), floorTvToman(), formatTvPrice(), isBankCoin() (+21 more)
### Community 1 - "ref_utils"
Cohesion: 0.23
Nodes (15): ref_composables, ref_store, ref_utils, applyAppNotificationFromStream(), applyLastFromStream(), applySettingsFromStream(), applyUnreadCountFromStreamPayload(), bindStreamEvents() (+7 more)
### Community 2 - "index.vue"
Cohesion: 0.19
Nodes (15): ref_components, ref_views, coinColumns, extraTickerLoop, loopNews(), loopTicker(), marqueeCopies(), newsDuration() (+7 more)
### Community 3 - "productPrice.ts"
Cohesion: 0.20
Nodes (24): applyPriceOffsetPercent(), buyCashFee(), cashFeeOptions(), getColleagueSourcedUnitPrice(), getProductBaseBuyPrice(), getProductBaseSellPrice(), getProductBuyPrice(), getProductSellPrice() (+16 more)
### Community 4 - "useNewPhysicalRequestPage.ts"
Cohesion: 0.12
Nodes (13): ref_ant_design_vue, ref_api, ref_lodash, ref_router, NEW_PHYSICAL_REQUEST_KEY, NewPhysicalRequestContext, useNewPhysicalRequestPage(), getAddress() (+5 more)
### Community 5 - "api/products.ts"
Cohesion: 0.15
Nodes (5): ref_models, TvServerTime, CountPInventory, PInventory, Product
### Community 6 - "priceSocket.ts"
Cohesion: 0.14
Nodes (40): bindBrowserNetworkListeners(), clearConnectingLifecycle(), clearFallbackPollTimer(), clearPriceNetworkAlert(), clearReconnectTimer(), connect(), disconnect(), disconnectSourceOnly() (+32 more)
### Community 7 - "priceSocketState.ts"
Cohesion: 0.20
Nodes (8): ref_vue, priceSocketConnected, priceStreamConnectingSince, priceStreamLifecycle, priceStreamList, priceStreamProducts, priceStreamServerUnix, priceWssEnabled
### Community 8 - "useProductsPageData.ts"
Cohesion: 0.12
Nodes (31): applyProductsList(), applyProductsListFromSocket(), applySocketProductList(), changeProductsTab(), flagOff(), flagOn(), initialized, initProductsPageData() (+23 more)
## Knowledge Gaps
- **22 isolated node(s):** `NewPhysicalRequestContext`, `NEW_PHYSICAL_REQUEST_KEY`, `initialized`, `productsActiveKey`, `productsTypeItems` (+17 more)
These have ≤1 connection - possible missing edges or undocumented components. (Counts symbols only; 45 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
- **1 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `AuthPriceStream` connect `AuthPriceStream` to `priceSocket.ts`?**
_High betweenness centrality (0.033) - this node is a cross-community bridge._
- **Are the 14 inferred relationships involving `useTvMonitorPage()` (e.g. with `isBankCoin()` and `isGoldBar()`) actually correct?**
_`useTvMonitorPage()` has 14 INFERRED edges - model-reasoned connections that need verification._
- **What connects `NewPhysicalRequestContext`, `NEW_PHYSICAL_REQUEST_KEY`, `initialized` to the rest of the system?**
_22 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `useTvMonitorPage` be split into smaller, more focused modules?**
_Cohesion score 0.10416666666666667 - nodes in this community are weakly interconnected._
- **Should `useNewPhysicalRequestPage.ts` be split into smaller, more focused modules?**
_Cohesion score 0.12418300653594772 - nodes in this community are weakly interconnected._
- **Should `priceSocket.ts` be split into smaller, more focused modules?**
_Cohesion score 0.1378048780487805 - nodes in this community are weakly interconnected._
- **Should `useProductsPageData.ts` be split into smaller, more focused modules?**
_Cohesion score 0.125 - nodes in this community are weakly interconnected._
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+27 -3
View File
@@ -1,15 +1,39 @@
import useAxios from "@/utils/useAxios"; import useAxios from "@/utils/useAxios";
import type {PInventory, Product} from "@/models/products"; import type {PInventory, Product} from "@/models/products";
import type { PWallet, Wallet } from '@/models/wallet' import { priceStreamList } from "@/utils/priceSocketState";
export const getProducts = async (): Promise<any> => { export const getProducts = async (force = false): Promise<Product[]> => {
return await useAxios.get<Product[]>(`/customer/product/list`, { timeout: 15000 }) if (!force && Array.isArray(priceStreamList.value) && priceStreamList.value.length > 0) {
return priceStreamList.value as unknown as Product[]
}
const response = await useAxios.get<Product[]>(`/customer/product/list`, { timeout: 15000 })
return Array.isArray(response) ? response : []
} }
export const getTvProducts = async (): Promise<Product[]> => { export const getTvProducts = async (): Promise<Product[]> => {
const response = await useAxios.get<unknown>(`/customer/tv/products`, { timeout: 15000 }) const response = await useAxios.get<unknown>(`/customer/tv/products`, { timeout: 15000 })
return Array.isArray(response) ? (response as Product[]) : [] return Array.isArray(response) ? (response as Product[]) : []
} }
export type TvServerTime = {
unix: number
iso: string
timezone: string
stream_key?: string
}
export const getTvServerTime = async (): Promise<TvServerTime | null> => {
try {
const response = await useAxios.get<TvServerTime>(`/customer/tv/time`, { timeout: 10000 })
if (response && typeof (response as TvServerTime).unix === 'number') {
return response as TvServerTime
}
} catch {
/* ignore */
}
return null
}
export const getProductById = async ( id:number|null): Promise<any> => { export const getProductById = async ( id:number|null): Promise<any> => {
return await useAxios.get<Product[]>(`/customer/product/list/${id}`, { timeout: 15000 }) return await useAxios.get<Product[]>(`/customer/product/list/${id}`, { timeout: 15000 })
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+78 -1
View File
@@ -7,11 +7,13 @@
:class="`app-credit-link--${variant}`" :class="`app-credit-link--${variant}`"
> >
<span class="app-credit-link__text">توسعه و طراحی توسط</span> <span class="app-credit-link__text">توسعه و طراحی توسط</span>
<img src="/logo-montzar.png" alt="montzar" class="app-credit-link__logo" /> <img :src="logoMontzarUrl" alt="montzar" class="app-credit-link__logo" />
</a> </a>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import logoMontzarUrl from '@/assets/img/logo-montzar.png'
withDefaults( withDefaults(
defineProps<{ defineProps<{
variant?: 'mobile' | 'sidebar' | 'float' | 'tv' variant?: 'mobile' | 'sidebar' | 'float' | 'tv'
@@ -19,3 +21,78 @@ withDefaults(
{ variant: 'mobile' }, { variant: 'mobile' },
) )
</script> </script>
<style lang="less">
.app-credit-link {
display: inline-flex;
align-items: center;
text-decoration: none;
color: inherit;
transition: opacity 0.15s ease;
&:hover {
opacity: 0.85;
}
&__text {
font-weight: 500;
white-space: nowrap;
}
&__logo {
width: auto;
max-width: 140px;
object-fit: contain;
}
&--mobile {
gap: 4px;
padding: 4px 0;
color: inherit;
.app-credit-link__logo {
height: 12px;
}
}
&--sidebar {
flex-direction: column;
gap: 6px;
padding: 4px;
color: #9ca3af;
font-size: 10px;
.app-credit-link__logo {
height: 15px;
opacity: 0.85;
}
}
&--float {
gap: 6px;
padding: 7px 14px;
font-size: 10px;
color: #6b7280;
background: #fff;
border-radius: 999px;
border: 1px solid rgba(15, 23, 42, 0.08);
box-shadow: 0 2px 10px rgba(15, 23, 42, 0.06);
.app-credit-link__logo {
height: 13px;
}
}
&--tv {
gap: 8px;
padding: 6px 0;
font-size: 12px;
color: #6b7280;
.app-credit-link__logo {
height: 16px;
max-width: 120px;
}
}
}
</style>
+861
View File
@@ -0,0 +1,861 @@
<template>
<div
ref="containerRef"
class="product-picker-root"
:class="{
'product-picker-root--compact': compact,
'product-picker-root--open': isOpen,
}"
>
<label v-if="label" class="product-picker__label">{{ label }}</label>
<!-- سلکتور جمع‌وجور -->
<div
class="product-picker__control"
:class="{
'product-picker__control--clickable': !disabled && !isEdit,
'product-picker__control--disabled': disabled,
'product-picker__control--locked': isEdit,
'product-picker__control--active': isOpen,
}"
role="button"
:tabindex="disabled ? -1 : 0"
:aria-label="label || placeholder"
@click="toggleOpen"
@keydown.enter.prevent="toggleOpen"
>
<div class="product-picker__value">
<span class="product-picker__icon" aria-hidden="true">
<BasicIcon
:icon="isEdit ? 'vuesax-linear:lock' : 'vuesax-linear:box-1'"
:size="compact ? 16 : 18"
:color="selectedItem ? 'var(--App-secondary-color, #e0be7f)' : 'var(--app-text-soft, #9ca3af)'"
/>
</span>
<span
class="product-picker__text"
:class="{ 'product-picker__text--placeholder': !selectedItem && !lockedTitle }"
>
{{ displayTitle }}
</span>
<span v-if="displayUnit" class="product-picker__unit">({{ displayUnit }})</span>
<span v-if="displaySubtitle" class="product-picker__subtitle">{{ displaySubtitle }}</span>
</div>
<div class="product-picker__trailing">
<button
v-if="allowClear && selectedItem && !disabled && !isEdit"
type="button"
class="product-picker__clear-btn"
aria-label="پاک کردن"
@click.stop="handleClear"
>
<BasicIcon icon="vuesax-linear:close-circle" size="16" color="var(--app-text-soft, #9ca3af)" />
</button>
<span class="product-picker__arrow" aria-hidden="true">
<BasicIcon
v-if="!isEdit"
:icon="isOpen ? 'vuesax-linear:arrow-up-1' : 'vuesax-linear:arrow-down-1'"
size="16"
color="var(--app-text-soft, #9ca3af)"
/>
<BasicIcon v-else icon="vuesax-linear:lock" size="14" color="var(--app-text-soft, #9ca3af)" />
</span>
</div>
</div>
<!-- دراپ‌داون دسکتاپ -->
<div
v-if="isDesktop && isOpen && !disabled && !isEdit"
class="product-picker__dropdown"
:style="dropdownStyle"
>
<div class="product-picker__search">
<span class="product-picker__search-icon" aria-hidden="true">
<BasicIcon icon="vuesax-linear:search-normal" size="16" color="var(--app-text-soft, #9ca3af)" />
</span>
<input
ref="desktopSearchInputRef"
v-model="searchQuery"
type="text"
class="product-picker__search-input"
placeholder="جستجوی محصول..."
autocomplete="off"
/>
<button
v-if="searchQuery"
type="button"
class="product-picker__clear-query-btn"
aria-label="پاک کردن جستجو"
@click="searchQuery = ''"
>
<BasicIcon icon="vuesax-linear:close-circle" size="15" color="var(--app-text-soft, #9ca3af)" />
</button>
</div>
<div class="product-picker__list" role="listbox">
<button
v-for="p in filteredList"
:key="getItemKey(p)"
type="button"
role="option"
class="product-picker__item"
:class="{ 'product-picker__item--selected': isSelected(p) }"
:aria-selected="isSelected(p)"
@click="selectItem(p)"
>
<div class="product-picker__item-info">
<span class="product-picker__item-icon">
<BasicIcon
icon="vuesax-linear:box-1"
size="16"
:color="isSelected(p) ? 'var(--App-secondary-color, #e0be7f)' : 'inherit'"
/>
</span>
<span class="product-picker__item-title">{{ getItemTitle(p) }}</span>
<span v-if="getItemUnit(p)" class="product-picker__item-unit">({{ getItemUnit(p) }})</span>
<span v-if="getItemSubtitle(p)" class="product-picker__item-subtitle">{{ getItemSubtitle(p) }}</span>
</div>
<span v-if="isSelected(p)" class="product-picker__item-check">
<BasicIcon icon="vuesax-linear:tick-circle" size="18" color="var(--App-secondary-color, #e0be7f)" />
</span>
</button>
<div v-if="loading" class="product-picker__loading">
<BasicIcon icon="vuesax-linear:box-time" size="20" class="animate-spin" color="var(--App-secondary-color, #e0be7f)" />
<span>در حال دریافت محصولات...</span>
</div>
<div v-else-if="filteredList.length === 0" class="product-picker__empty">
<BasicIcon icon="vuesax-linear:info-circle" size="20" color="var(--app-text-soft, #9ca3af)" />
<span>{{ emptyText }}</span>
</div>
</div>
</div>
<!-- اکشن‌شیت موبایل -->
<BasicActionSheet
v-if="!isDesktop"
v-model:show="isSheetOpen"
:title="sheetTitle"
:closable="true"
@closed="onSheetClosed"
>
<div class="product-picker-sheet">
<div class="product-picker-sheet__search">
<span class="product-picker-sheet__search-icon" aria-hidden="true">
<BasicIcon icon="vuesax-linear:search-normal" size="18" color="var(--app-text-soft, #9ca3af)" />
</span>
<input
ref="mobileSearchInputRef"
v-model="searchQuery"
type="text"
class="product-picker-sheet__search-input"
placeholder="جستجوی نام یا کد محصول..."
autocomplete="off"
/>
<button
v-if="searchQuery"
type="button"
class="product-picker-sheet__clear-btn"
aria-label="پاک کردن جستجو"
@click="searchQuery = ''"
>
<BasicIcon icon="vuesax-linear:close-circle" size="18" color="var(--app-text-soft, #9ca3af)" />
</button>
</div>
<div class="product-picker-sheet__list" role="listbox">
<button
v-for="p in filteredList"
:key="getItemKey(p)"
type="button"
role="option"
class="product-picker-sheet__item"
:class="{ 'product-picker-sheet__item--selected': isSelected(p) }"
:aria-selected="isSelected(p)"
@click="selectItem(p)"
>
<div class="product-picker-sheet__item-info">
<span class="product-picker-sheet__item-icon">
<BasicIcon
icon="vuesax-linear:box-1"
size="18"
:color="isSelected(p) ? 'var(--App-secondary-color, #e0be7f)' : 'inherit'"
/>
</span>
<div class="product-picker-sheet__item-texts">
<span class="product-picker-sheet__item-title">{{ getItemTitle(p) }}</span>
<span
v-if="getItemSubtitle(p) || getItemUnit(p)"
class="product-picker-sheet__item-meta"
>
{{ getItemSubtitle(p) || `واحد: ${getItemUnit(p)}` }}
</span>
</div>
</div>
<span v-if="isSelected(p)" class="product-picker-sheet__item-check">
<BasicIcon icon="vuesax-linear:tick-circle" size="20" color="var(--App-secondary-color, #e0be7f)" />
</span>
</button>
<div v-if="loading" class="product-picker-sheet__loading">
<BasicIcon icon="vuesax-linear:box-time" size="26" class="animate-spin" color="var(--App-secondary-color, #e0be7f)" />
<span class="mt-2 text-sm text-gray-400">در حال دریافت محصولات...</span>
</div>
<div v-else-if="filteredList.length === 0" class="product-picker-sheet__empty">
<BasicIcon icon="vuesax-linear:info-circle" size="24" color="var(--app-text-soft, #9ca3af)" />
<span>{{ emptyText }}</span>
</div>
</div>
</div>
</BasicActionSheet>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import BasicIcon from '@/components/BasicPacks/BasicIcon.vue'
import BasicActionSheet from '@/components/BasicPacks/BasicActionSheet.vue'
import { useDesktopBreakpoint } from '@/layouts/composables/useAppLayout'
interface Props {
modelValue?: number | string | null
value?: number | string | null
items?: any[]
products?: any[]
keyName?: string
valueName?: string
unitName?: string
subtitleName?: string
placeholder?: string
sheetTitle?: string
label?: string
disabled?: boolean
loading?: boolean
isEdit?: boolean
lockedTitle?: string
allowClear?: boolean
compact?: boolean
emptyText?: string
dropdownStyle?: Record<string, any>
}
const props = withDefaults(defineProps<Props>(), {
modelValue: undefined,
value: undefined,
items: undefined,
products: undefined,
keyName: 'id',
valueName: 'title',
unitName: 'unit',
subtitleName: 'subtitle',
placeholder: 'انتخاب محصول...',
sheetTitle: 'انتخاب محصول',
label: '',
disabled: false,
loading: false,
isEdit: false,
lockedTitle: '',
allowClear: false,
compact: false,
emptyText: 'محصولی یافت نشد',
dropdownStyle: undefined,
})
const emit = defineEmits<{
'update:modelValue': [val: any]
'update:value': [val: any]
'change': [item: any]
'clear': []
}>()
const isDesktop = useDesktopBreakpoint()
const containerRef = ref<HTMLElement>()
const desktopSearchInputRef = ref<HTMLInputElement>()
const mobileSearchInputRef = ref<HTMLInputElement>()
const isOpen = ref(false)
const isSheetOpen = ref(false)
const searchQuery = ref('')
const effectiveList = computed(() => {
if (Array.isArray(props.items)) return props.items
if (Array.isArray(props.products)) return props.products
return []
})
const currentValue = computed(() => {
if (props.modelValue !== undefined) return props.modelValue
return props.value
})
function getItemKey(item: any): any {
if (!item) return ''
return item[props.keyName] !== undefined ? item[props.keyName] : item.id
}
function getItemTitle(item: any): string {
if (!item) return ''
return String(item[props.valueName] || item.title || item.name || `محصول ${getItemKey(item)}`)
}
function getItemUnit(item: any): string {
if (!item) return ''
return item[props.unitName] || item.unit || ''
}
function getItemSubtitle(item: any): string {
if (!item) return ''
return item[props.subtitleName] || item.subtitle || ''
}
const selectedItem = computed(() => {
const val = currentValue.value
if (val === undefined || val === null || val === '') return null
return effectiveList.value.find((p) => String(getItemKey(p)) === String(val)) ?? null
})
const displayTitle = computed(() => {
if (props.isEdit && props.lockedTitle) return props.lockedTitle
if (selectedItem.value) return getItemTitle(selectedItem.value)
const val = currentValue.value
if (val !== undefined && val !== null && val !== '') return `محصول ${val}`
return props.placeholder
})
const displayUnit = computed(() => {
if (props.isEdit) return ''
return selectedItem.value ? getItemUnit(selectedItem.value) : ''
})
const displaySubtitle = computed(() => {
if (props.isEdit) return ''
return selectedItem.value ? getItemSubtitle(selectedItem.value) : ''
})
function isSelected(item: any): boolean {
const val = currentValue.value
if (val === undefined || val === null || val === '') return false
return String(getItemKey(item)) === String(val)
}
function normalizeText(text: string): string {
return (text || '')
.toLowerCase()
.replace(/ي/g, 'ی')
.replace(/ك/g, 'ک')
.replace(/[\u200B-\u200D\uFEFF]/g, '')
.trim()
}
const filteredList = computed(() => {
const q = normalizeText(searchQuery.value)
if (!q) return effectiveList.value
return effectiveList.value.filter((p) => {
const title = normalizeText(getItemTitle(p))
const unit = normalizeText(getItemUnit(p))
const subtitle = normalizeText(getItemSubtitle(p))
const key = String(getItemKey(p))
return title.includes(q) || unit.includes(q) || subtitle.includes(q) || key.includes(q)
})
})
function toggleOpen() {
if (props.disabled || props.isEdit) return
if (isDesktop.value) {
isOpen.value = !isOpen.value
if (isOpen.value) {
nextTick(() => {
desktopSearchInputRef.value?.focus()
})
} else {
searchQuery.value = ''
}
} else {
isSheetOpen.value = true
nextTick(() => {
mobileSearchInputRef.value?.focus()
})
}
}
function selectItem(item: any) {
const key = getItemKey(item)
emit('update:modelValue', key)
emit('update:value', key)
emit('change', item)
isOpen.value = false
isSheetOpen.value = false
searchQuery.value = ''
}
function handleClear() {
emit('update:modelValue', undefined)
emit('update:value', undefined)
emit('change', undefined)
emit('clear')
}
function onSheetClosed() {
searchQuery.value = ''
}
function handleClickOutside(e: MouseEvent) {
if (containerRef.value && !containerRef.value.contains(e.target as Node)) {
isOpen.value = false
searchQuery.value = ''
}
}
onMounted(() => {
window.addEventListener('click', handleClickOutside)
})
onBeforeUnmount(() => {
window.removeEventListener('click', handleClickOutside)
})
</script>
<style scoped lang="less">
.product-picker-root {
position: relative;
display: flex;
flex-direction: column;
gap: 0.375rem;
width: 100%;
direction: rtl;
text-align: right;
z-index: 1;
&--open {
z-index: 50;
}
--picker-bg: var(--app-surface, var(--admin-bg-surface, #ffffff));
--picker-border: var(--app-border, var(--admin-border, #e2e8f0));
--picker-border-focus: var(--app-border-strong, var(--App-secondary-color, #e0be7f));
--picker-text: var(--app-text-primary, var(--admin-text, #0f172a));
--picker-text-soft: var(--app-text-muted, var(--admin-text-secondary, #64748b));
--picker-inset: var(--app-surface-inset, rgba(15, 23, 42, 0.03));
}
:global(html[data-theme='dark']) .product-picker-root,
:global(html.dark) .product-picker-root {
--picker-bg: var(--app-surface, #1e2026);
--picker-border: var(--app-border, rgba(255, 255, 255, 0.12));
--picker-border-focus: var(--app-border-strong, rgba(255, 255, 255, 0.28));
--picker-text: var(--app-text-primary, #ffffff);
--picker-text-soft: var(--app-text-muted, rgba(255, 255, 255, 0.55));
--picker-inset: var(--app-surface-inset, rgba(255, 255, 255, 0.04));
}
.product-picker__label {
font-size: 0.8125rem;
font-weight: 700;
color: var(--picker-text);
}
.product-picker__control {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 2.65rem;
padding: 0 0.75rem;
border-radius: 0.65rem;
border: 1px solid var(--picker-border);
background: var(--picker-bg);
color: var(--picker-text);
direction: rtl;
transition: all 0.18s ease;
user-select: none;
.product-picker-root--compact & {
min-height: 2.35rem;
padding: 0 0.6rem;
border-radius: 0.5rem;
}
&--clickable {
cursor: pointer;
&:hover {
border-color: var(--picker-border-focus);
}
}
&--active {
border-color: var(--picker-border-focus);
box-shadow: 0 0 0 2px rgba(227, 176, 86, 0.15);
}
&--disabled {
opacity: 0.6;
cursor: not-allowed;
background: var(--picker-inset);
}
&--locked {
background: var(--picker-inset);
cursor: default;
}
}
.product-picker__value {
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
flex: 1;
}
.product-picker__icon {
display: inline-flex;
align-items: center;
flex-shrink: 0;
}
.product-picker__text {
font-size: 0.875rem;
font-weight: 600;
color: var(--picker-text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
.product-picker-root--compact & {
font-size: 0.8125rem;
}
&--placeholder {
color: var(--picker-text-soft);
font-weight: 400;
}
}
.product-picker__unit {
font-size: 0.75rem;
color: var(--picker-text-soft);
flex-shrink: 0;
}
.product-picker__subtitle {
font-size: 0.72rem;
color: var(--App-secondary-color, #e0be7f);
font-weight: 600;
flex-shrink: 0;
}
.product-picker__trailing {
display: flex;
align-items: center;
gap: 0.35rem;
flex-shrink: 0;
}
.product-picker__clear-btn {
display: inline-flex;
align-items: center;
justify-content: center;
border: none;
background: transparent;
padding: 2px;
cursor: pointer;
border-radius: 9999px;
transition: opacity 0.15s ease;
&:hover {
opacity: 0.8;
}
}
.product-picker__arrow {
display: inline-flex;
align-items: center;
justify-content: center;
}
/* دراپ‌داون دسکتاپ */
.product-picker__dropdown {
position: absolute;
top: calc(100% + 4px);
right: 0;
left: 0;
z-index: 1050;
padding: 0.5rem;
border-radius: 0.75rem;
border: 1px solid var(--picker-border);
background: var(--picker-bg);
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.product-picker__search {
display: flex;
align-items: center;
gap: 0.5rem;
height: 2.25rem;
padding: 0 0.6rem;
border-radius: 0.5rem;
background: var(--picker-inset);
border: 1px solid var(--picker-border);
}
.product-picker__search-icon {
display: inline-flex;
flex-shrink: 0;
}
.product-picker__search-input {
flex: 1;
min-width: 0;
border: none;
outline: none;
background: transparent;
color: var(--picker-text);
font-size: 0.8125rem;
text-align: right;
direction: rtl;
&::placeholder {
color: var(--picker-text-soft);
}
}
.product-picker__clear-query-btn {
border: none;
background: transparent;
padding: 0;
cursor: pointer;
display: inline-flex;
}
.product-picker__list {
display: flex;
flex-direction: column;
gap: 0.2rem;
max-height: 14rem;
overflow-y: auto;
}
.product-picker__item {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
padding: 0.5rem 0.65rem;
border-radius: 0.5rem;
border: 1px solid transparent;
background: transparent;
cursor: pointer;
transition: all 0.15s ease;
outline: none;
text-align: right;
&:hover {
background: var(--picker-inset);
border-color: var(--picker-border);
}
&--selected {
background: rgba(224, 190, 127, 0.12);
border-color: var(--App-secondary-color, #e0be7f);
}
}
.product-picker__item-info {
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
}
.product-picker__item-icon {
display: inline-flex;
align-items: center;
flex-shrink: 0;
}
.product-picker__item-title {
font-size: 0.8125rem;
font-weight: 600;
color: var(--picker-text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-picker__item-unit {
font-size: 0.72rem;
color: var(--picker-text-soft);
}
.product-picker__item-subtitle {
font-size: 0.72rem;
color: var(--App-secondary-color, #e0be7f);
font-weight: 600;
}
.product-picker__item-check {
display: inline-flex;
align-items: center;
flex-shrink: 0;
}
.product-picker__empty {
display: flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
padding: 1.25rem 0.5rem;
color: var(--picker-text-soft);
font-size: 0.8125rem;
}
/* شیت موبایل */
.product-picker-sheet {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding-bottom: 1.5rem;
direction: rtl;
text-align: right;
}
.product-picker-sheet__search {
display: flex;
align-items: center;
gap: 0.5rem;
height: 2.75rem;
padding: 0 0.85rem;
border-radius: 0.75rem;
background: var(--picker-inset);
border: 1px solid var(--picker-border);
}
.product-picker-sheet__search-icon {
display: inline-flex;
flex-shrink: 0;
}
.product-picker-sheet__search-input {
flex: 1;
min-width: 0;
border: none;
outline: none;
background: transparent;
color: var(--picker-text);
font-size: 0.875rem;
font-weight: 500;
text-align: right;
direction: rtl;
&::placeholder {
color: var(--picker-text-soft);
}
}
.product-picker-sheet__clear-btn {
border: none;
background: transparent;
padding: 0;
cursor: pointer;
display: inline-flex;
}
.product-picker-sheet__list {
display: flex;
flex-direction: column;
gap: 0.35rem;
max-height: 55vh;
overflow-y: auto;
}
.product-picker-sheet__item {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
padding: 0.65rem 0.75rem;
border-radius: 0.65rem;
border: 1px solid var(--picker-border);
background: var(--picker-bg);
cursor: pointer;
transition: all 0.15s ease;
outline: none;
text-align: right;
&:hover {
border-color: var(--App-secondary-color, #e0be7f);
}
&--selected {
border-color: var(--App-secondary-color, #e0be7f);
background: rgba(224, 190, 127, 0.1);
}
}
.product-picker-sheet__item-info {
display: flex;
align-items: center;
gap: 0.65rem;
min-width: 0;
}
.product-picker-sheet__item-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2.1rem;
height: 2.1rem;
border-radius: 0.5rem;
background: var(--picker-inset);
flex-shrink: 0;
.product-picker-sheet__item--selected & {
background: var(--App-secondary-color, #e0be7f);
color: #fff;
}
}
.product-picker-sheet__item-texts {
display: flex;
flex-direction: column;
align-items: flex-start;
min-width: 0;
}
.product-picker-sheet__item-title {
font-size: 0.85rem;
font-weight: 700;
color: var(--picker-text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-picker-sheet__item-meta {
font-size: 0.7rem;
color: var(--picker-text-soft);
font-weight: 500;
}
.product-picker-sheet__item-check {
display: inline-flex;
align-items: center;
flex-shrink: 0;
}
.product-picker-sheet__empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.4rem;
padding: 2rem 1rem;
color: var(--picker-text-soft);
font-size: 0.8125rem;
text-align: center;
}
</style>
+42 -2
View File
@@ -1,15 +1,38 @@
import { ref } from 'vue' import { ref } from 'vue'
import { getProducts } from '@/api/products' import { getProducts } from '@/api/products'
import type { Product } from '@/models/products' import type { Product } from '@/models/products'
import { priceStreamList } from '@/utils/priceSocketState'
/** کش مشترک لیست محصولات — dedupe درخواست‌های polling */ /** کش مشترک لیست محصولات — dedupe درخواست‌های polling */
const catalogProducts = ref<Product[]>([]) const catalogProducts = ref<Product[]>([])
let catalogPromise: Promise<Product[]> | null = null let catalogPromise: Promise<Product[]> | null = null
export function getProductsCatalogRef() { export function getProductsCatalogRef() {
if (catalogProducts.value.length === 0 && Array.isArray(priceStreamList.value) && priceStreamList.value.length > 0) {
catalogProducts.value = priceStreamList.value as unknown as Product[]
}
return catalogProducts return catalogProducts
} }
export function syncCatalogFromStream(streamProducts: Product[]) {
if (!Array.isArray(streamProducts) || streamProducts.length === 0) return
if (catalogProducts.value.length === 0) {
catalogProducts.value = streamProducts
} else {
const map = new Map(streamProducts.map((p) => [p.id, p]))
catalogProducts.value.forEach((p) => {
const incoming = map.get(p.id)
if (incoming) {
if (incoming.price !== undefined) p.price = incoming.price
if (incoming.price_buy !== undefined) p.price_buy = incoming.price_buy
if (incoming.price_sell !== undefined) p.price_sell = incoming.price_sell
if (incoming.trade_open !== undefined) p.trade_open = incoming.trade_open
if (incoming.show !== undefined) p.show = incoming.show
}
})
}
}
export function findProductInCatalog(id: number): Product | undefined { export function findProductInCatalog(id: number): Product | undefined {
return catalogProducts.value.find((p) => p.id === id) return catalogProducts.value.find((p) => p.id === id)
} }
@@ -19,17 +42,34 @@ export function getProductsCatalog(force = false): Promise<Product[]> {
if (catalogProducts.value.length > 0) { if (catalogProducts.value.length > 0) {
return Promise.resolve(catalogProducts.value) return Promise.resolve(catalogProducts.value)
} }
if (Array.isArray(priceStreamList.value) && priceStreamList.value.length > 0) {
catalogProducts.value = priceStreamList.value as unknown as Product[]
return Promise.resolve(catalogProducts.value)
}
} }
if (!force && catalogPromise) { if (!force && catalogPromise) {
return catalogPromise return catalogPromise
} }
catalogPromise = getProducts() catalogPromise = getProducts(force)
.then((products) => { .then((products) => {
catalogProducts.value = products ?? [] const list = Array.isArray(products) ? products : []
if (list.length > 0) {
catalogProducts.value = list
}
return catalogProducts.value return catalogProducts.value
}) })
.catch((err) => {
if (catalogProducts.value.length > 0) {
return catalogProducts.value
}
if (Array.isArray(priceStreamList.value) && priceStreamList.value.length > 0) {
catalogProducts.value = priceStreamList.value as unknown as Product[]
return catalogProducts.value
}
throw err
})
.finally(() => { .finally(() => {
catalogPromise = null catalogPromise = null
}) })
+6
View File
@@ -35,4 +35,10 @@ export interface Price {
/** montzar | zaarbox | main_product | store = مظنه زنده، database_last = آخرین قیمت ذخیره‌شده */ /** montzar | zaarbox | main_product | store = مظنه زنده، database_last = آخرین قیمت ذخیره‌شده */
price_source?: string | null price_source?: string | null
last_historical?: number last_historical?: number
special_pricing?: {
package_id?: number
title?: string
profit_buy?: number
profit_sell?: number
} | null
} }
+5
View File
@@ -3,6 +3,7 @@ import type {Wallet} from "@/models/wallet";
export interface Product { export interface Product {
id: number id: number
img: string | undefined img: string | undefined
image?: string | null
title: string title: string
amount: any amount: any
metal_id: any metal_id: any
@@ -22,6 +23,8 @@ export interface Product {
cash_fee_sell: number | undefined cash_fee_sell: number | undefined
cash_fee_buy_is_percent?: boolean | null cash_fee_buy_is_percent?: boolean | null
cash_fee_sell_is_percent?: boolean | null cash_fee_sell_is_percent?: boolean | null
special_profit_buy?: number | null
special_profit_sell?: number | null
order_limit_enabled?: boolean order_limit_enabled?: boolean
min_order_cash?: number | null min_order_cash?: number | null
max_order_cash?: number | null max_order_cash?: number | null
@@ -40,6 +43,8 @@ export interface Product {
similar?:Product[] similar?:Product[]
inventory:number inventory:number
app_price?: boolean | number | null app_price?: boolean | number | null
colleague_price?: boolean | number | null
colleague_price_product_id?: string | number | null
tv_price?: number | null tv_price?: number | null
tv_sell_price?: number | null tv_sell_price?: number | null
direct_price?: number | null direct_price?: number | null
+83 -8
View File
@@ -3,10 +3,14 @@ import type { Product } from '@/models/products'
import { Modal } from 'ant-design-vue' import { Modal } from 'ant-design-vue'
import { getConfigApp } from '@/utils/config' import { getConfigApp } from '@/utils/config'
import { applyProductsListFromStream } from '@/utils/productStreamBridge' import { applyProductsListFromStream } from '@/utils/productStreamBridge'
import { syncCatalogFromStream } from '@/composables/useProductsCatalog'
import { import {
priceSocketConnected, priceSocketConnected,
priceStreamConnectingSince, priceStreamConnectingSince,
priceStreamLifecycle, priceStreamLifecycle,
priceStreamList,
priceStreamProducts,
priceStreamServerUnix,
priceWssEnabled, priceWssEnabled,
} from '@/utils/priceSocketState' } from '@/utils/priceSocketState'
import { import {
@@ -44,9 +48,9 @@ class AuthPriceStream extends EventTarget {
onmessage: (() => void) | null = null onmessage: (() => void) | null = null
private abort = new AbortController() private abort = new AbortController()
constructor(url: string) { constructor(url: string, tvKey = '') {
super() super()
void this.start(url) void this.start(url, tvKey)
} }
close() { close() {
@@ -54,10 +58,12 @@ class AuthPriceStream extends EventTarget {
this.abort.abort() this.abort.abort()
} }
private async start(url: string) { private async start(url: string, tvKey = '') {
try { try {
const headers: Record<string, string> = { Accept: 'text/event-stream' }
if (tvKey) headers['X-Tv-Key'] = tvKey
const response = await fetch(url, { const response = await fetch(url, {
headers: { Accept: 'text/event-stream' }, headers,
cache: 'no-store', cache: 'no-store',
signal: this.abort.signal, signal: this.abort.signal,
}) })
@@ -119,6 +125,7 @@ class AuthPriceStream extends EventTarget {
let eventSource: AuthPriceStream | null = null let eventSource: AuthPriceStream | null = null
let subscribers = 0 let subscribers = 0
let tvStreamKey: string | null = null
let stopped = false let stopped = false
let getSetting: ((key: string) => unknown) | null = null let getSetting: ((key: string) => unknown) | null = null
let reconnectTimer: ReturnType<typeof setTimeout> | undefined let reconnectTimer: ReturnType<typeof setTimeout> | undefined
@@ -280,7 +287,7 @@ export function notifyPriceLastFetchFailed() {
} }
async function runFallbackPoll() { async function runFallbackPoll() {
if (!priceWssEnabled.value || priceSocketConnected.value) { if (tvStreamKey || !priceWssEnabled.value || priceSocketConnected.value) {
return return
} }
@@ -467,13 +474,40 @@ function handleSettingsPayload(payload: unknown) {
void applySettingsFromStream(payload) void applySettingsFromStream(payload)
} }
function coerceStreamProductList(payload: unknown): Product[] {
if (Array.isArray(payload)) {
return payload as Product[]
}
if (!payload || typeof payload !== 'object') {
return []
}
const root = payload as Record<string, unknown>
if (Array.isArray(root.data)) return root.data as Product[]
if (Array.isArray(root.products)) return root.products as Product[]
if (Array.isArray(root.items)) return root.items as Product[]
if (root.id != null && ('price' in root || 'title' in root || 'group_type' in root)) {
return [payload as Product]
}
const values = Object.values(root)
if (
values.length > 0 &&
values.every((item) => item && typeof item === 'object' && 'id' in (item as object))
) {
return values as Product[]
}
return []
}
function handleListPayload(payload: unknown) { function handleListPayload(payload: unknown) {
if (!Array.isArray(payload) || !payload.length) { const products = coerceStreamProductList(payload)
if (!products.length) {
return return
} }
touchStreamActivity() touchStreamActivity()
applyProductsListFromStream(payload as Product[]) priceStreamList.value = products as Array<Record<string, unknown>>
syncCatalogFromStream(products)
applyProductsListFromStream(products)
} }
function handleAppNotificationPayload(payload: unknown) { function handleAppNotificationPayload(payload: unknown) {
@@ -537,6 +571,31 @@ function bindStreamEvents(source: AuthPriceStream) {
} }
}) })
source.addEventListener('products', (event) => {
try {
const rows = JSON.parse(event.data)
if (Array.isArray(rows) && rows.length) {
touchStreamActivity()
priceStreamProducts.value = rows
}
} catch (error) {
console.warn('Price SSE products parse failed', error)
}
})
source.addEventListener('time', (event) => {
try {
const payload = JSON.parse(event.data) as { unix?: number }
const unix = Number(payload?.unix)
if (unix > 0) {
touchStreamActivity()
priceStreamServerUnix.value = unix
}
} catch (error) {
console.warn('Price SSE time parse failed', error)
}
})
source.addEventListener('app_notification', (event) => { source.addEventListener('app_notification', (event) => {
try { try {
handleAppNotificationPayload(JSON.parse(event.data)) handleAppNotificationPayload(JSON.parse(event.data))
@@ -630,7 +689,7 @@ function connect() {
markConnectingLifecycle() markConnectingLifecycle()
try { try {
eventSource = new AuthPriceStream(url) eventSource = new AuthPriceStream(url, tvStreamKey || '')
} catch (error) { } catch (error) {
console.warn('Price SSE connect failed', error) console.warn('Price SSE connect failed', error)
handleStreamLost() handleStreamLost()
@@ -715,6 +774,22 @@ function unbindBrowserNetworkListeners() {
window.removeEventListener('offline', onBrowserOffline) window.removeEventListener('offline', onBrowserOffline)
} }
export function startTvPriceStream(
settingGetter: (key: string) => unknown,
key: string,
) {
const secret = key.trim()
if (!secret) return
tvStreamKey = secret
startPriceSocket(settingGetter)
}
export function stopTvPriceStream() {
if (!tvStreamKey) return
tvStreamKey = null
stopPriceSocket()
}
export function startPriceSocket(settingGetter: (key: string) => unknown) { export function startPriceSocket(settingGetter: (key: string) => unknown) {
getSetting = settingGetter getSetting = settingGetter
subscribers += 1 subscribers += 1
+9
View File
@@ -9,6 +9,15 @@ export const priceStreamLifecycle = ref<PriceStreamLifecycle>('idle')
export const priceStreamConnectingSince = ref(0) export const priceStreamConnectingSince = ref(0)
/** آخرین رویداد list استریم */
export const priceStreamList = ref<Array<Record<string, unknown>>>([])
/** آخرین بدنهٔ tv/products که از SSE آمده */
export const priceStreamProducts = ref<Array<Record<string, unknown>>>([])
/** unix ساعت سرور از رویداد time استریم */
export const priceStreamServerUnix = ref(0)
const CONNECTING_POLL_AFTER_MS = 8000 const CONNECTING_POLL_AFTER_MS = 8000
export function shouldUsePricePolling(): boolean { export function shouldUsePricePolling(): boolean {
+25 -4
View File
@@ -3,6 +3,13 @@ export type ProductCashFeeSource = {
cash_fee_sell?: number | null cash_fee_sell?: number | null
cash_fee_buy_is_percent?: boolean | null cash_fee_buy_is_percent?: boolean | null
cash_fee_sell_is_percent?: boolean | null cash_fee_sell_is_percent?: boolean | null
special_profit_buy?: number | null
special_profit_sell?: number | null
}
export type ProductCashFeeOptions = {
/** پیش‌فرض true. اگر مظنهٔ last از قبل special_pricing دارد باید false باشد. */
includeSpecial?: boolean
} }
/** 0.5 => 0.5% ، 5 => 5% — همیشه عدد درصد */ /** 0.5 => 0.5% ، 5 => 5% — همیشه عدد درصد */
@@ -42,23 +49,37 @@ export function resolveProductCashFeeRial(
return Math.round(Math.abs(base * resolveCashFeePercentRatio(raw))) return Math.round(Math.abs(base * resolveCashFeePercentRatio(raw)))
} }
export function resolveProductCashFeeBuyRial(product: ProductCashFeeSource, basePriceRial: number) { export function resolveProductCashFeeBuyRial(
product: ProductCashFeeSource,
basePriceRial: number,
options?: ProductCashFeeOptions,
) {
const baseFee = resolveProductCashFeeRial( const baseFee = resolveProductCashFeeRial(
product.cash_fee_buy, product.cash_fee_buy,
product.cash_fee_buy_is_percent, product.cash_fee_buy_is_percent,
basePriceRial, basePriceRial,
) )
const special = Number((product as any).special_profit_buy ?? 0) if (options?.includeSpecial === false) {
return baseFee
}
const special = Number(product.special_profit_buy ?? 0)
return baseFee + (Number.isFinite(special) ? Math.round(special) : 0) return baseFee + (Number.isFinite(special) ? Math.round(special) : 0)
} }
export function resolveProductCashFeeSellRial(product: ProductCashFeeSource, basePriceRial: number) { export function resolveProductCashFeeSellRial(
product: ProductCashFeeSource,
basePriceRial: number,
options?: ProductCashFeeOptions,
) {
const baseFee = resolveProductCashFeeRial( const baseFee = resolveProductCashFeeRial(
product.cash_fee_sell, product.cash_fee_sell,
product.cash_fee_sell_is_percent, product.cash_fee_sell_is_percent,
basePriceRial, basePriceRial,
) )
const special = Number((product as any).special_profit_sell ?? 0) if (options?.includeSpecial === false) {
return baseFee
}
const special = Number(product.special_profit_sell ?? 0)
return baseFee + (Number.isFinite(special) ? Math.round(special) : 0) return baseFee + (Number.isFinite(special) ? Math.round(special) : 0)
} }
+22 -2
View File
@@ -51,12 +51,31 @@ export function resolveMeltedPriceSource(product?: {
return 'app' return 'app'
} }
/** قیمت از همکار: قیمت هر عدد، نه هر گرم */
export function isColleaguePriceProduct(product?: {
colleague_price?: boolean | number | null
colleague_price_product_id?: string | number | null
} | null) {
if (!product) {
return false
}
const flagged = product.colleague_price === true || Number(product.colleague_price) === 1
if (!flagged) {
return false
}
if (product.colleague_price_product_id === undefined) {
return true
}
return Number(product.colleague_price_product_id) > 0
}
/** محصول با پرچم صریح «قیمت اپ» */ /** محصول با پرچم صریح «قیمت اپ» */
export function isAppPriceProduct(product?: { export function isAppPriceProduct(product?: {
app_price?: boolean | number | null app_price?: boolean | number | null
reading_method?: string | null reading_method?: string | null
colleague_price?: boolean | number | null
} | null) { } | null) {
if (!product || product.reading_method) { if (!product || product.reading_method || isColleaguePriceProduct(product)) {
return false return false
} }
return product.app_price === true || Number(product.app_price) === 1 return product.app_price === true || Number(product.app_price) === 1
@@ -68,8 +87,9 @@ export function isMeltedProductUsingAppPrice(product?: {
direct_price?: number | null direct_price?: number | null
trade_by_quantity?: boolean | number | null trade_by_quantity?: boolean | number | null
price?: number | null price?: number | null
colleague_price?: boolean | number | null
} | null) { } | null) {
if (!product || resolveMeltedPriceSource(product) !== 'app') { if (!product || isColleaguePriceProduct(product) || resolveMeltedPriceSource(product) !== 'app') {
return false return false
} }
+2 -1
View File
@@ -10,6 +10,7 @@ export type ProductImageSource = {
file?: { id?: number | null; src?: string | null; full_src?: string | null; url?: string | null } | null file?: { id?: number | null; src?: string | null; full_src?: string | null; url?: string | null } | null
file_id?: number | string | null file_id?: number | string | null
img?: string | null img?: string | null
image?: string | null
group_type?: string | null group_type?: string | null
} | null | undefined } | null | undefined
@@ -103,7 +104,7 @@ export function getProductFallbackImage(product?: ProductImageSource): string {
} }
export function resolveProductImageSrc(product?: ProductImageSource): string { export function resolveProductImageSrc(product?: ProductImageSource): string {
const remoteSrc = product?.file?.full_src || product?.file?.url || product?.file?.src const remoteSrc = product?.file?.full_src || product?.file?.url || product?.file?.src || product?.image || product?.img
if (isUsableImageSrc(remoteSrc)) { if (isUsableImageSrc(remoteSrc)) {
const url = absolutizeImageUrl(remoteSrc!.trim()) const url = absolutizeImageUrl(remoteSrc!.trim())
const version = product?.file_id ?? product?.file?.id const version = product?.file_id ?? product?.file?.id
+84 -56
View File
@@ -3,12 +3,14 @@ import { getTradeBuyPrice, getTradeSellPrice, lastPrice } from '@/utils/price'
import { resolveProductCashFeeBuyRial, resolveProductCashFeeSellRial } from '@/utils/productCashFee' import { resolveProductCashFeeBuyRial, resolveProductCashFeeSellRial } from '@/utils/productCashFee'
import { import {
isAppPriceProduct, isAppPriceProduct,
isColleaguePriceProduct,
isMeltedProductUsingAppPrice, isMeltedProductUsingAppPrice,
isMeltedTradeGroup, isMeltedTradeGroup,
isMetalCommodityGroup, isMetalCommodityGroup,
usesQuantityTrade, usesQuantityTrade,
} from '@/utils/productCategories' } from '@/utils/productCategories'
import { isProductTradingHoursOpen } from '@/utils/productTradeOpen' import { isProductTradingHoursOpen } from '@/utils/productTradeOpen'
import { lastPriceIncludesSpecial } from '@/utils/specialPricing'
/** /**
* قیمت‌گیری محصول — هم‌تراز با khaneghi_user: * قیمت‌گیری محصول — هم‌تراز با khaneghi_user:
@@ -23,6 +25,53 @@ function hasReferenceReadingMethod(product: Product): boolean {
return Boolean(product.reading_method) return Boolean(product.reading_method)
} }
/** پایه از buy/sell مظنه آمده — special همان‌جا اعمال شده و نباید دوباره جمع شود */
function productUsesLiveBoardQuote(product: Product, side: 'buy' | 'sell'): boolean {
if (isColleaguePriceProduct(product)) {
const stored = side === 'sell'
? Number(product.sellPrice ?? product.price ?? 0)
: Number(product.price ?? 0)
if (stored > 0) {
return false
}
const live = side === 'buy' ? getTradeBuyPrice(lastPrice.value) : getTradeSellPrice(lastPrice.value)
return isMeltedTradeGroup(product.group_type) && live > 0
}
if (isMeltedProductUsingAppPrice(product) || isAppPriceProduct(product)) {
const live = side === 'buy' ? getTradeBuyPrice(lastPrice.value) : getTradeSellPrice(lastPrice.value)
return live > 0
}
return false
}
function cashFeeOptions(product: Product, side: 'buy' | 'sell') {
if (lastPriceIncludesSpecial(lastPrice.value) && productUsesLiveBoardQuote(product, side)) {
return { includeSpecial: false as const }
}
return undefined
}
function buyCashFee(product: Product, base: number) {
return resolveProductCashFeeBuyRial(product, base, cashFeeOptions(product, 'buy'))
}
function sellCashFee(product: Product, base: number) {
return resolveProductCashFeeSellRial(product, base, cashFeeOptions(product, 'sell'))
}
/** قیمت منبع همکار؛ اگر خالی بود آبشده همان مظنهٔ صفحه اصلی را می‌گیرد */
function getColleagueSourcedUnitPrice(product: Product, live: number, apiPrice = Number(product.price ?? 0)): number {
if (apiPrice > 0) {
return apiPrice
}
if (isMeltedTradeGroup(product.group_type) && live > 0) {
return applyPriceOffsetPercent(live, product.price_offset_percent)
}
return 0
}
function hasProductUnitWeight(product?: Product | null) { function hasProductUnitWeight(product?: Product | null) {
if (!product || isMeltedTradeGroup(product.group_type)) { if (!product || isMeltedTradeGroup(product.group_type)) {
return false return false
@@ -31,7 +80,7 @@ function hasProductUnitWeight(product?: Product | null) {
} }
function productPriceAmountFactor(product?: Product | null) { function productPriceAmountFactor(product?: Product | null) {
if (!product || product.reading_method) { if (!product || product.reading_method || isColleaguePriceProduct(product)) {
return 1 return 1
} }
if (isAppPriceProduct(product)) { if (isAppPriceProduct(product)) {
@@ -84,27 +133,18 @@ export function getProductBaseBuyPrice(product?: Product | null): number {
return 0 return 0
} }
if (isColleaguePriceProduct(product)) {
return getColleagueSourcedUnitPrice(product, getTradeBuyPrice(lastPrice.value))
}
if (isMeltedProductUsingAppPrice(product) || isAppPriceProduct(product)) { if (isMeltedProductUsingAppPrice(product) || isAppPriceProduct(product)) {
const apiPrice = Number(product.price ?? 0)
const useLast = productUsesLastPriceIfZero(product)
if (!useLast) {
const liveBuy = getTradeBuyPrice(lastPrice.value) const liveBuy = getTradeBuyPrice(lastPrice.value)
if (liveBuy > 0) { if (liveBuy > 0) {
return applyPriceOffsetPercent(liveBuy, product.price_offset_percent) return applyPriceOffsetPercent(liveBuy, product.price_offset_percent)
} }
return 0 if (productUsesLastPriceIfZero(product) && Number(product.price ?? 0) > 0) {
return Number(product.price ?? 0)
} }
if (apiPrice > 0) {
return apiPrice
}
const liveBuy = getTradeBuyPrice(lastPrice.value)
if (liveBuy > 0) {
return applyPriceOffsetPercent(liveBuy, product.price_offset_percent)
}
return 0 return 0
} }
@@ -134,9 +174,13 @@ export function getProductBuyPrice(product?: Product | null): number {
return 0 return 0
} }
const fee = resolveProductCashFeeBuyRial(product, base) const fee = buyCashFee(product, base)
const withFee = base + fee const withFee = base + fee
if (isColleaguePriceProduct(product)) {
return withFee
}
if (isAppPriceProduct(product)) { if (isAppPriceProduct(product)) {
return withFee * productPriceAmountFactor(product) return withFee * productPriceAmountFactor(product)
} }
@@ -166,27 +210,22 @@ export function getProductBaseSellPrice(product?: Product | null): number {
return 0 return 0
} }
if (isColleaguePriceProduct(product)) {
return getColleagueSourcedUnitPrice(
product,
getTradeSellPrice(lastPrice.value),
Number(product.sellPrice ?? product.price ?? 0),
)
}
if (isMeltedProductUsingAppPrice(product) || isAppPriceProduct(product)) { if (isMeltedProductUsingAppPrice(product) || isAppPriceProduct(product)) {
const apiPrice = Number(product.price ?? 0)
const useLast = productUsesLastPriceIfZero(product)
if (!useLast) {
const liveSell = getTradeSellPrice(lastPrice.value) const liveSell = getTradeSellPrice(lastPrice.value)
if (liveSell > 0) { if (liveSell > 0) {
return applyPriceOffsetPercent(liveSell, product.price_offset_percent) return applyPriceOffsetPercent(liveSell, product.price_offset_percent)
} }
return 0 if (productUsesLastPriceIfZero(product) && Number(product.price ?? 0) > 0) {
return Number(product.price ?? 0)
} }
if (apiPrice > 0) {
return apiPrice
}
const liveSell = getTradeSellPrice(lastPrice.value)
if (liveSell > 0) {
return applyPriceOffsetPercent(liveSell, product.price_offset_percent)
}
return 0 return 0
} }
@@ -213,25 +252,29 @@ export function getProductSellPrice(product?: Product | null): number {
return 0 return 0
} }
if (isColleaguePriceProduct(product)) {
return base - sellCashFee(product, base)
}
if (isAppPriceProduct(product)) { if (isAppPriceProduct(product)) {
const withFee = base - resolveProductCashFeeSellRial(product, base) const withFee = base - sellCashFee(product, base)
return withFee * productPriceAmountFactor(product) return withFee * productPriceAmountFactor(product)
} }
if (isMeltedProductUsingAppPrice(product) || isMeltedTradeGroup(product.group_type)) { if (isMeltedProductUsingAppPrice(product) || isMeltedTradeGroup(product.group_type)) {
return base - resolveProductCashFeeSellRial(product, base) return base - sellCashFee(product, base)
} }
if (usesQuantityTrade(product) && hasProductUnitWeight(product)) { if (usesQuantityTrade(product) && hasProductUnitWeight(product)) {
const withFee = base - resolveProductCashFeeSellRial(product, base) const withFee = base - sellCashFee(product, base)
return withFee * productPriceAmountFactor(product) return withFee * productPriceAmountFactor(product)
} }
if (usesQuantityTrade(product)) { if (usesQuantityTrade(product)) {
return base - resolveProductCashFeeSellRial(product, base) return base - sellCashFee(product, base)
} }
return base - resolveProductCashFeeSellRial(product, base) return base - sellCashFee(product, base)
} }
/** کارت فروشگاه: قیمت نمایشی صفر → «بدون قیمت» */ /** کارت فروشگاه: قیمت نمایشی صفر → «بدون قیمت» */
@@ -264,43 +307,28 @@ function tvBuyUnitPrice(product: Product): number {
} }
function tvSellUnitPrice(product: Product): number { function tvSellUnitPrice(product: Product): number {
const sell = Number(product.tv_sell_price ?? 0) return Number(product.tv_sell_price ?? 0)
if (sell > 0) {
return sell
}
return tvBuyUnitPrice(product)
} }
export function getTvProductBuyPrice(product?: Product | null): number { export function getTvProductBuyPrice(product?: Product | null): number {
if (!product) { if (!product) {
return 0 return 0
} }
const unit = tvBuyUnitPrice(product) return tvBuyUnitPrice(product)
if (unit > 0) {
return unit + resolveProductCashFeeBuyRial(product, unit)
}
return getProductBuyPrice(product)
} }
export function getTvProductSellPrice(product?: Product | null): number { export function getTvProductSellPrice(product?: Product | null): number {
if (!product) { if (!product) {
return 0 return 0
} }
const unit = tvSellUnitPrice(product) return tvSellUnitPrice(product)
if (unit > 0) {
return unit - resolveProductCashFeeSellRial(product, unit)
}
return getProductSellPrice(product)
} }
export function isTvProductPriceInactive(product?: Product | null): boolean { export function isTvProductPriceInactive(product?: Product | null): boolean {
if (!product) { if (!product) {
return true return true
} }
if (tvBuyUnitPrice(product) > 0 || tvSellUnitPrice(product) > 0) { return tvBuyUnitPrice(product) <= 0 && tvSellUnitPrice(product) <= 0
return false
}
return isProductPriceInactive(product)
} }
/** /**
+2 -1
View File
@@ -36,7 +36,8 @@ export function isProductTradingHoursOpen(
auto_close_at?: string | null auto_close_at?: string | null
} | null, } | null,
) { ) {
if (!product) return false // روت /gold محصول را prop نمی‌گیرد؛ نبود محصول یعنی ساعت محصول اعمال نشود (مثل open_buy)
if (!product) return true
if (isOutsideProductActivationWindow(product)) return false if (isOutsideProductActivationWindow(product)) return false
if (typeof product.trade_open === 'boolean') return product.trade_open if (typeof product.trade_open === 'boolean') return product.trade_open
return product.show === true return product.show === true
+7
View File
@@ -48,6 +48,13 @@ export function getSpecialPricingState() {
return state return state
} }
/** مظنهٔ last از قبل اختلاف ویژه دارد (سرور یا applyBoardSpecial) */
export function lastPriceIncludesSpecial(
payload?: { special_pricing?: unknown } | null,
): boolean {
return Boolean(payload && typeof payload === 'object' && payload.special_pricing)
}
/** اگر سرور قبلاً special_pricing نزده، اختلاف تابلو را روی last اعمال کن */ /** اگر سرور قبلاً special_pricing نزده، اختلاف تابلو را روی last اعمال کن */
export function applyBoardSpecialToLastPayload<T extends Record<string, any>>(payload: T): T { export function applyBoardSpecialToLastPayload<T extends Record<string, any>>(payload: T): T {
if (!payload || typeof payload !== 'object') return payload if (!payload || typeof payload !== 'object') return payload
+140 -34
View File
@@ -27,7 +27,7 @@
class="w-full h-10 flex items-center justify-center font-bold rounded-full transition-all" class="w-full h-10 flex items-center justify-center font-bold rounded-full transition-all"
:class="isBuy ? 'bg-green-600 text-white shadow-sm' : 'text-green-600'" :class="isBuy ? 'bg-green-600 text-white shadow-sm' : 'text-green-600'"
@click.stop="setIsBuy(true)" @click.stop="setIsBuy(true)"
:style="!isProductBuyOpen(props?.ProductItem) ? 'pointer-events: none; opacity: 0.35;' : ''" :style="!isProductBuyOpen(tradeProduct) ? 'pointer-events: none; opacity: 0.35;' : ''"
> >
خرید خرید
</div> </div>
@@ -35,7 +35,7 @@
class="w-full h-10 flex items-center justify-center font-bold rounded-full transition-all" class="w-full h-10 flex items-center justify-center font-bold rounded-full transition-all"
:class="!isBuy ? 'bg-red-600 text-white shadow-sm' : 'text-red-600'" :class="!isBuy ? 'bg-red-600 text-white shadow-sm' : 'text-red-600'"
@click.stop="setIsBuy(false)" @click.stop="setIsBuy(false)"
:style="!isProductSellOpen(props?.ProductItem) ? 'pointer-events: none; opacity: 0.35;' : ''" :style="!isProductSellOpen(tradeProduct) ? 'pointer-events: none; opacity: 0.35;' : ''"
> >
فروش فروش
</div> </div>
@@ -98,7 +98,7 @@
</div>--> </div>-->
</div> </div>
<div v-else class="font-bold text-xs"> <div v-else class="font-bold text-xs">
{{ formatCashWalletBalanceText(usePriceWithoutType(cashWalletBalance), props?.ProductItem?.group_type) }} {{ formatCashWalletBalanceText(usePriceWithoutType(cashWalletBalance), tradeProduct?.group_type) }}
</div> </div>
</Transition> </Transition>
<Transition mode="out-in" name="fade"> <Transition mode="out-in" name="fade">
@@ -147,15 +147,33 @@
موجودی کیف پول ناکافی می باشد. موجودی کیف پول ناکافی می باشد.
</div> </div>
</a-form-item> </a-form-item>
<div class="w-full px-4 rounded-2xl py-2 border-1 bg-white gold-fee-box"> <div class="w-full px-4 rounded-2xl py-3 border-1 bg-white gold-fee-box flex flex-col gap-2 mt-2">
<div class="flex justify-between items-center"> <!-- سطر اول: مبلغ اصل معامله (رنگ مشکی/پایه) -->
<div>کارمزد ({{ feeDeductsFromGold ? `از طلا` : `از ریال` }}):</div> <div class="flex justify-between items-center text-xs sm:text-sm">
<div class="flex gap-2 items-center font-bold"> <span class="text-gray-600 font-medium">مبلغ اصل معامله:</span>
<div>{{ feeDisplayText }}</div> <strong class="font-bold text-gray-800 number-ltr" dir="ltr">
{{ usePriceWithoutType(Math.round(finalPrice ?? 0)) }} ریال
</strong>
</div> </div>
<!-- سطر دوم: کارمزد معامله (رنگ قرمز) -->
<div class="flex justify-between items-center text-xs sm:text-sm">
<span class="text-red-500 font-medium">
{{ isBuy ? `کارمزد خرید (${feePercentLabel}):` : `کسر ${feePercentLabel} کارمزد از فروش:` }}
</span>
<strong class="font-bold text-red-600 number-ltr" dir="ltr">
{{ isBuy ? `+ ${feeDisplayText}` : `− ${feeDisplayText}` }}
</strong>
</div> </div>
<div class="text-xs text-gray-600 mt-1">
{{ feeFormHint }} <!-- سطر سوم: مبلغ نهایی قابل پرداخت / قابل واریز (رنگ سبز برجسته) -->
<div class="flex justify-between items-center text-xs sm:text-sm pt-2 border-t border-gray-100">
<span class="text-green-700 font-bold">
{{ isBuy ? 'مبلغ قابل پرداخت:' : 'مبلغ قابل واریز (دریافتی):' }}
</span>
<strong class="font-bold text-green-600 text-sm sm:text-base number-ltr" dir="ltr">
{{ usePriceWithoutType(Math.round(payablePrice ?? 0)) }} ریال
</strong>
</div> </div>
</div> </div>
</a-form> </a-form>
@@ -241,7 +259,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, nextTick, onMounted, ref, watch } from 'vue' import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import img1 from '@/assets/img/home_ly2.svg' import img1 from '@/assets/img/home_ly2.svg'
import { usePrice, usePriceWithoutType } from '@/utils/usePrice' import { usePrice, usePriceWithoutType } from '@/utils/usePrice'
import BasicInput from '@/components/BasicPacks/BasicInput.vue' import BasicInput from '@/components/BasicPacks/BasicInput.vue'
@@ -313,7 +331,12 @@ import {
import { formatCashWalletBalanceText, getWeightUnit } from '@/utils/productDealMethod' import { formatCashWalletBalanceText, getWeightUnit } from '@/utils/productDealMethod'
import { formatProductWalletBalanceText, getCashWalletBalance } from '@/utils/productAssets' import { formatProductWalletBalanceText, getCashWalletBalance } from '@/utils/productAssets'
import { useWalletAssets } from '@/composables/useWalletAssets' import { useWalletAssets } from '@/composables/useWalletAssets'
import { usesQuantityTrade } from '@/utils/productCategories' import {
findProductInCatalog,
getProductsCatalog,
getProductsCatalogRef,
} from '@/composables/useProductsCatalog'
import { subscribeProductListStream } from '@/utils/productStreamBridge'
import { useSettingsStore } from '@/store/settingsStore' import { useSettingsStore } from '@/store/settingsStore'
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { import {
@@ -365,8 +388,54 @@ const contentClass = computed(() => {
const isBuy = ref<boolean>(true) const isBuy = ref<boolean>(true)
const inputLock = ref<TradeInputLock>(null) const inputLock = ref<TradeInputLock>(null)
const catalogProducts = getProductsCatalogRef()
const standaloneProductId = ref<number>()
let unsubscribeProductStream: (() => void) | undefined
/** شناسه محصول آبشده از استریم last / تنظیمات — مثل مسیر خرید محصول */
function resolveMeltedTradeProductId(): number | undefined {
const fromPrice = Number(lastPrice.value?.main_product ?? 0)
if (Number.isFinite(fromPrice) && fromPrice > 0) return fromPrice
const mainProduct = Number(settingsStore.getSettingByKey('main_product') ?? 0)
if (Number.isFinite(mainProduct) && mainProduct > 0) return mainProduct
const raw = String(settingsStore.getSettingByKey('main_wallet_products') ?? '').trim()
if (!raw) return undefined
let parts: unknown[] = []
try {
const decoded = JSON.parse(raw)
parts = Array.isArray(decoded) ? decoded : raw.split(',')
} catch {
parts = raw.split(',')
}
for (const part of parts) {
const id = Number(String(part).trim())
if (Number.isFinite(id) && id > 0) return id
}
return undefined
}
function pickStandaloneMeltedProduct(): Product | undefined {
void catalogProducts.value
const id = standaloneProductId.value ?? resolveMeltedTradeProductId()
if (id) {
const match = findProductInCatalog(id)
?? catalogProducts.value.find((product) => Number(product.id) === Number(id))
if (match) return match
}
return catalogProducts.value.find((product) => product.title === 'آبشده نقدی')
?? catalogProducts.value.find((product) => product.group_type === 'آبشده')
}
const tradeProduct = computed(() => props.ProductItem ?? pickStandaloneMeltedProduct())
const tradeProductLabel = computed(() => { const tradeProductLabel = computed(() => {
const title = props.ProductItem?.title?.trim() const title = tradeProduct.value?.title?.trim()
return title || meltedGoldLabel.value return title || meltedGoldLabel.value
}) })
const amountFieldLabel = computed(() => `مقدار ${tradeProductLabel.value}`) const amountFieldLabel = computed(() => `مقدار ${tradeProductLabel.value}`)
@@ -377,7 +446,7 @@ const productWalletBalance = computed(() =>
const productWalletBalanceText = computed(() => const productWalletBalanceText = computed(() =>
formatProductWalletBalanceText( formatProductWalletBalanceText(
props.ProductItem, tradeProduct.value,
assetsSummary.value?.inventory_cards ?? [], assetsSummary.value?.inventory_cards ?? [],
walletStore?.walletInfo?.gold walletStore?.walletInfo?.gold
) )
@@ -403,9 +472,9 @@ const sellPagination = ref<TableEngineInput>({
}) })
const unitPrice = computed(() => { const unitPrice = computed(() => {
const product = props.ProductItem const product = tradeProduct.value
if (usesQuantityTrade(product)) { if (product) {
return isBuy.value ? getProductBuyPrice(product!) : getProductSellPrice(product!) return isBuy.value ? getProductBuyPrice(product) : getProductSellPrice(product)
} }
return isBuy.value ? getTradeBuyPrice(lastPrice.value) : getTradeSellPrice(lastPrice.value) return isBuy.value ? getTradeBuyPrice(lastPrice.value) : getTradeSellPrice(lastPrice.value)
}) })
@@ -440,6 +509,10 @@ const feeDisplayText = computed(() =>
: `${usePriceWithoutType(Math.round(feeInRial.value))} ریال` : `${usePriceWithoutType(Math.round(feeInRial.value))} ریال`
) )
const feePercentLabel = computed(() =>
feeInGrams.value > 0 ? `${formatFixed(serviceFeePercentage.value * 100, 2)}%` : 'رایگان'
)
const displayTradeGoldAmount = computed(() => const displayTradeGoldAmount = computed(() =>
formatTradeGramDisplay(orderGoldAmount.value) formatTradeGramDisplay(orderGoldAmount.value)
) )
@@ -498,10 +571,10 @@ const feeFormHint = computed(() =>
}).formHint }).formHint
) )
const minOrderCash = computed(() => productMinOrderCash(props.ProductItem, isBuy.value)) const minOrderCash = computed(() => productMinOrderCash(tradeProduct.value, isBuy.value))
const maxOrderCash = computed(() => productMaxOrderCash(props.ProductItem)) const maxOrderCash = computed(() => productMaxOrderCash(tradeProduct.value))
const cashValidationMessage = computed(() => const cashValidationMessage = computed(() =>
productCashValidationMessage(props.ProductItem, form.value?.goldCash, isBuy.value, usePriceWithoutType) productCashValidationMessage(tradeProduct.value, form.value?.goldCash, isBuy.value, usePriceWithoutType)
) )
const priceUnavailable = computed(() => { const priceUnavailable = computed(() => {
@@ -512,15 +585,15 @@ const priceUnavailable = computed(() => {
const disableTransaction = computed(() => const disableTransaction = computed(() =>
loading.value || loading.value ||
isStoreClosed() || isStoreClosed() ||
!isProductTradingHoursOpen(props.ProductItem) || !isProductTradingHoursOpen(tradeProduct.value) ||
!isProductTradeOpen(props.ProductItem, isBuy.value) || !isProductTradeOpen(tradeProduct.value, isBuy.value) ||
form.value?.goldValue === undefined || form.value?.goldValue === undefined ||
form.value?.goldValue === '' || form.value?.goldValue === '' ||
form.value?.goldCash === '' || form.value?.goldCash === '' ||
form.value?.goldCash === undefined || form.value?.goldCash === undefined ||
(isBuy.value (isBuy.value
? (form.value?.goldCash ?? 0) < minOrderCash.value ? (form.value?.goldCash ?? 0) < minOrderCash.value
: (productMinOrderCash(props.ProductItem, false) > 0 || productMaxOrderCash(props.ProductItem) != null : (productMinOrderCash(tradeProduct.value, false) > 0 || productMaxOrderCash(tradeProduct.value) != null
? ((form.value?.goldCash ?? 0) < minOrderCash.value || (maxOrderCash.value != null && (form.value?.goldCash ?? 0) > maxOrderCash.value)) ? ((form.value?.goldCash ?? 0) < minOrderCash.value || (maxOrderCash.value != null && (form.value?.goldCash ?? 0) > maxOrderCash.value))
: (form.value?.goldValue ?? 0) < 0.001)) || : (form.value?.goldValue ?? 0) < 0.001)) ||
(maxOrderCash.value != null && (form.value?.goldCash ?? 0) > maxOrderCash.value) || (maxOrderCash.value != null && (form.value?.goldCash ?? 0) > maxOrderCash.value) ||
@@ -620,8 +693,25 @@ async function initSellTable() {
// } // }
onMounted(async () => { onMounted(async () => {
if (!props.ProductItem) {
try {
await getProductsCatalog()
} catch (error) {
console.log(error)
}
unsubscribeProductStream = subscribeProductListStream((products) => {
if (Array.isArray(products) && products.length) {
catalogProducts.value = products
}
})
standaloneProductId.value = resolveMeltedTradeProductId()
const picked = pickStandaloneMeltedProduct()
if (picked?.id) {
standaloneProductId.value = Number(picked.id)
}
}
isBuy.value = resolveProductTradeIsBuy( isBuy.value = resolveProductTradeIsBuy(
props?.ProductItem, tradeProduct.value,
router.currentRoute.value.query.state?.toString(), router.currentRoute.value.query.state?.toString(),
) )
await initPrice() await initPrice()
@@ -630,10 +720,26 @@ onMounted(async () => {
await initBuyTable()*/ await initBuyTable()*/
}) })
onUnmounted(() => {
unsubscribeProductStream?.()
unsubscribeProductStream = undefined
})
watch( watch(
() => [props?.ProductItem?.id, props?.ProductItem?.open_buy, props?.ProductItem?.open_sell], () => [tradeProduct.value?.id, tradeProduct.value?.open_buy, tradeProduct.value?.open_sell],
() => { () => {
isBuy.value = resolveProductTradeIsBuy(props?.ProductItem, isBuy.value ? 'buy' : 'sell') isBuy.value = resolveProductTradeIsBuy(tradeProduct.value, isBuy.value ? 'buy' : 'sell')
},
)
watch(
() => lastPrice.value?.main_product,
(id) => {
if (props.ProductItem) return
const next = Number(id)
if (Number.isFinite(next) && next > 0) {
standaloneProductId.value = next
}
}, },
) )
@@ -713,7 +819,7 @@ function syncFormWithLatestPrice() {
} }
watch( watch(
() => [unitPrice.value, isBuy.value, props.ProductItem?.id], () => [unitPrice.value, isBuy.value, tradeProduct.value?.id],
() => { () => {
syncFormWithLatestPrice() syncFormWithLatestPrice()
} }
@@ -769,8 +875,8 @@ function useStyle() {
function setIsBuy(val: boolean) { function setIsBuy(val: boolean) {
if (val && !isProductBuyOpen(props?.ProductItem)) return if (val && !isProductBuyOpen(tradeProduct.value)) return
if (!val && !isProductSellOpen(props?.ProductItem)) return if (!val && !isProductSellOpen(tradeProduct.value)) return
isBuy.value = val isBuy.value = val
form.value.goldValue = undefined form.value.goldValue = undefined
form.value.goldCash = undefined form.value.goldCash = undefined
@@ -811,11 +917,11 @@ function okConfirm() {
message.warning(getStoreClosedMessage()) message.warning(getStoreClosedMessage())
return return
} }
if (!isProductTradingHoursOpen(props.ProductItem)) { if (!isProductTradingHoursOpen(tradeProduct.value)) {
message.warning(productHoursClosedMessage()) message.warning(productHoursClosedMessage())
return return
} }
if (!isProductTradeOpen(props.ProductItem, isBuy.value)) { if (!isProductTradeOpen(tradeProduct.value, isBuy.value)) {
message.warning(productTradeClosedMessage(isBuy.value)) message.warning(productTradeClosedMessage(isBuy.value))
return return
} }
@@ -834,11 +940,11 @@ async function ok() {
message.warning(getStoreClosedMessage()) message.warning(getStoreClosedMessage())
return return
} }
if (!isProductTradingHoursOpen(props.ProductItem)) { if (!isProductTradingHoursOpen(tradeProduct.value)) {
message.warning(productHoursClosedMessage()) message.warning(productHoursClosedMessage())
return return
} }
if (!isProductTradeOpen(props.ProductItem, isBuy.value)) { if (!isProductTradeOpen(tradeProduct.value, isBuy.value)) {
message.warning(productTradeClosedMessage(isBuy.value)) message.warning(productTradeClosedMessage(isBuy.value))
return return
} }
@@ -853,7 +959,7 @@ async function ok() {
amount: normalizeOrderGoldAmount(orderGoldAmount.value), amount: normalizeOrderGoldAmount(orderGoldAmount.value),
// ریال قفل → مبلغ دقیق به سرور می‌رود (کارمزد از طلا). گرم قفل → target_cash خالی، وزن دقیق معامله می‌شود. // ریال قفل → مبلغ دقیق به سرور می‌رود (کارمزد از طلا). گرم قفل → target_cash خالی، وزن دقیق معامله می‌شود.
target_cash: calcTradeTargetCash(form.value.goldCash, inputLock.value), target_cash: calcTradeTargetCash(form.value.goldCash, inputLock.value),
abshode_id: props.ProductItem?.id, abshode_id: tradeProduct.value?.id,
}) })
const result = await afterCreateOrder(res) const result = await afterCreateOrder(res)
if (result !== 'success') { if (result !== 'success') {
@@ -1,13 +1,15 @@
import { inject, nextTick, onMounted, provide, ref, type InjectionKey, type Ref } from 'vue' import { inject, nextTick, onMounted, provide, ref, watch, type InjectionKey, type Ref } from 'vue'
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
import { message } from 'ant-design-vue' import { message } from 'ant-design-vue'
import router from '@/router' import router from '@/router'
import { getProductInventory } from '@/api/products' import { getProductInventory } from '@/api/products'
import { physicalReceiveApi } from '@/api/physicalreceive' import { physicalReceiveApi } from '@/api/physicalreceive'
import { tableAddress } from '@/api/address' import { tableAddress } from '@/api/address'
import type { CountPInventory, PInventory } from '@/models/products' import type { CountPInventory, PInventory, Product } from '@/models/products'
import type { Address } from '@/models/address' import type { Address } from '@/models/address'
import { loading } from '@/utils' import { loading } from '@/utils'
import { priceStreamList } from '@/utils/priceSocketState'
import { useWalletAssets } from '@/composables/useWalletAssets'
import { usePhysicalReceiveShellContext } from './usePhysicalReceiveShell' import { usePhysicalReceiveShellContext } from './usePhysicalReceiveShell'
export interface NewPhysicalRequestContext { export interface NewPhysicalRequestContext {
@@ -31,6 +33,7 @@ export const NEW_PHYSICAL_REQUEST_KEY: InjectionKey<NewPhysicalRequestContext> =
export function useNewPhysicalRequestPage() { export function useNewPhysicalRequestPage() {
const { isDesktop } = usePhysicalReceiveShellContext() const { isDesktop } = usePhysicalReceiveShellContext()
const { loadWalletAssets } = useWalletAssets()
const items = ref<PInventory[]>() const items = ref<PInventory[]>()
const baseItems = ref<PInventory[]>() const baseItems = ref<PInventory[]>()
@@ -71,18 +74,63 @@ export function useNewPhysicalRequestPage() {
) )
} }
async function initProductWallet() { let cachedInventoryRows: PInventory[] = []
try {
loading.value = true function buildPhysicalDeliveryItems(inventoryRows: PInventory[] = []): PInventory[] {
const inventory = (await getProductInventory()).rows.filter( const streamList = Array.isArray(priceStreamList.value)
(x) => x.title !== 'آبشده نقدی' && x.wallet?.gold && x.wallet.gold > 0, ? (priceStreamList.value as unknown as Product[])
: []
const inventoryMap = new Map((inventoryRows || []).map((r) => [r.id, r]))
const physicalStream = streamList.filter(
(p) => Boolean(p.has_physical_delivery) && p.title !== 'آبشده نقدی'
) )
items.value = inventory
baseItems.value = cloneDeep(inventory) const list: PInventory[] = physicalStream.map((p) => {
const inv = inventoryMap.get(p.id)
return {
...p,
...(inv || {}),
id: p.id,
title: p.title,
unit: p.unit || inv?.unit || 'عدد',
has_physical_delivery: true,
min_physical_delivery_quantity: Number(
p.min_physical_delivery_quantity ?? inv?.min_physical_delivery_quantity ?? 0
),
wallet: inv?.wallet ?? {
id: p.id,
gold: 0,
},
} as PInventory
})
return list
}
function syncItemsFromStream() {
const selectedIds = new Set(selectedProducts.value.map((sp) => sp.product.id))
const fresh = buildPhysicalDeliveryItems(cachedInventoryRows)
baseItems.value = cloneDeep(fresh)
items.value = fresh.filter((item) => !selectedIds.has(item.id))
}
watch(
() => priceStreamList.value,
() => {
syncItemsFromStream()
},
{ deep: true }
)
async function initProductWallet() {
syncItemsFromStream()
try {
const invRes = await getProductInventory()
cachedInventoryRows = invRes?.rows || []
syncItemsFromStream()
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} finally {
loading.value = false
} }
} }
@@ -122,6 +170,7 @@ export function useNewPhysicalRequestPage() {
await nextTick() await nextTick()
message.success('درخواست شما با موفقیت ارسال شد') message.success('درخواست شما با موفقیت ارسال شد')
await loadWalletAssets(true)
await initProductWallet() await initProductWallet()
await router.push({ name: 'list' }) await router.push({ name: 'list' })
} catch (e) { } catch (e) {
@@ -137,7 +186,8 @@ export function useNewPhysicalRequestPage() {
} }
onMounted(async () => { onMounted(async () => {
await initProductWallet() syncItemsFromStream()
void initProductWallet()
await getAddress() await getAddress()
}) })
@@ -6,15 +6,12 @@
<div class="dinner-surface p-5 space-y-4"> <div class="dinner-surface p-5 space-y-4">
<div class="physical-new-request__picker-row"> <div class="physical-new-request__picker-row">
<div class="physical-new-request__select"> <div class="physical-new-request__select">
<BasicSelect <ProductPicker
v-model:value="selectedProduct" v-model:value="selectedProduct"
:items="items" :items="items"
key-name="id" placeholder="لطفاً محصول را انتخاب کنید"
:show-search="false" sheet-title="انتخاب محصول تحویل فیزیکی"
value-name="title" allow-clear
size="large"
placeholder="لطفا محصول را انتخاب کنید"
:has-tooltip="false"
/> />
</div> </div>
<BasicButton <BasicButton
@@ -85,7 +82,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import BasicButton from '@/components/BasicPacks/BasicButton.vue' import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import BasicSelect from '@/components/BasicPacks/BasicSelect.vue' import ProductPicker from '@/components/BasicPacks/ProductPicker.vue'
import BasicModal from '@/components/BasicPacks/BasicModal.vue' import BasicModal from '@/components/BasicPacks/BasicModal.vue'
import DesktopPageTopbar from '@/layouts/components/DesktopPageTopbar.vue' import DesktopPageTopbar from '@/layouts/components/DesktopPageTopbar.vue'
import New_EditAddress from '@/views/base/address/components/New_EditAddress.vue' import New_EditAddress from '@/views/base/address/components/New_EditAddress.vue'
@@ -3,15 +3,12 @@
<div class="physical-new-request__toolbar mpage-content"> <div class="physical-new-request__toolbar mpage-content">
<div class="physical-new-request__picker-row px-3"> <div class="physical-new-request__picker-row px-3">
<div class="physical-new-request__select"> <div class="physical-new-request__select">
<BasicSelect <ProductPicker
v-model:value="selectedProduct" v-model:value="selectedProduct"
:items="items" :items="items"
key-name="id" placeholder="لطفاً محصول را انتخاب کنید"
:show-search="false" sheet-title="انتخاب محصول تحویل فیزیکی"
value-name="title" allow-clear
size="large"
placeholder="لطفا محصول را انتخاب کنید"
:has-tooltip="false"
/> />
</div> </div>
<BasicButton <BasicButton
@@ -64,7 +61,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import BasicButton from '@/components/BasicPacks/BasicButton.vue' import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import BasicSelect from '@/components/BasicPacks/BasicSelect.vue' import ProductPicker from '@/components/BasicPacks/ProductPicker.vue'
import BasicActionSheet from '@/components/BasicPacks/BasicActionSheet.vue' import BasicActionSheet from '@/components/BasicPacks/BasicActionSheet.vue'
import New_EditAddress from '@/views/base/address/components/New_EditAddress.vue' import New_EditAddress from '@/views/base/address/components/New_EditAddress.vue'
import PhysicalReceiveCartRow from '../components/PhysicalReceiveCartRow.vue' import PhysicalReceiveCartRow from '../components/PhysicalReceiveCartRow.vue'
+14 -16
View File
@@ -24,18 +24,13 @@
<BasicIcon icon="vuesax-linear:box-1" size="18" /> <BasicIcon icon="vuesax-linear:box-1" size="18" />
<span class="truncate">{{ lockedProductTitle || 'محصول ثابت' }}</span> <span class="truncate">{{ lockedProductTitle || 'محصول ثابت' }}</span>
</div> </div>
<div v-else class="piggy-create__products"> <div v-else>
<button <ProductPicker
v-for="p in products" v-model:value="productId"
:key="p.id" :items="products"
type="button" placeholder="انتخاب محصول قلک..."
class="piggy-create__product" sheet-title="انتخاب محصول قلک"
:class="{ 'piggy-create__product--on': productId === p.id }" />
@click="productId = p.id"
>
<BasicIcon icon="vuesax-linear:box-1" size="18" />
<span class="min-w-0 truncate">{{ p.title || `محصول ${p.id}` }}</span>
</button>
</div> </div>
</section> </section>
@@ -82,7 +77,8 @@
import { computed, onMounted, ref } from 'vue' import { computed, onMounted, ref } from 'vue'
import router from '@/router' import router from '@/router'
import { createFund, editFund, getFundById } from '@/api/fund' import { createFund, editFund, getFundById } from '@/api/fund'
import { getProducts } from '@/api/products' import { getProductsCatalog, getProductsCatalogRef } from '@/composables/useProductsCatalog'
import ProductPicker from '@/components/BasicPacks/ProductPicker.vue'
import { useFundUserStore } from '@/store/fundStore' import { useFundUserStore } from '@/store/fundStore'
import { useSettingsStore } from '@/store/settingsStore' import { useSettingsStore } from '@/store/settingsStore'
import { message } from 'ant-design-vue' import { message } from 'ant-design-vue'
@@ -94,7 +90,7 @@ const settingsStore = useSettingsStore()
const busy = ref(false) const busy = ref(false)
const title = ref('پس انداز') const title = ref('پس انداز')
const productId = ref<number | undefined>() const productId = ref<number | undefined>()
const products = ref<Product[]>([]) const products = ref<Product[]>(getProductsCatalogRef().value || [])
const lockedProductTitle = ref('') const lockedProductTitle = ref('')
const presets = [...PIGGY_PRESETS] const presets = [...PIGGY_PRESETS]
@@ -142,15 +138,17 @@ onMounted(async () => {
return return
} }
try { try {
if (!products.value.length || editId.value) {
busy.value = true busy.value = true
const list = await getProducts() }
const list = await getProductsCatalog()
products.value = Array.isArray(list) ? list : ((list as any)?.rows ?? (list as any)?.data ?? []) products.value = Array.isArray(list) ? list : ((list as any)?.rows ?? (list as any)?.data ?? [])
if (editId.value) { if (editId.value) {
const fund = await getFundById(editId.value) const fund = await getFundById(editId.value)
title.value = fund?.title ?? '' title.value = fund?.title ?? ''
productId.value = fund?.product_id productId.value = fund?.product_id
lockedProductTitle.value = fund?.product?.title || '' lockedProductTitle.value = fund?.product?.title || ''
} else if (products.value.length === 1) { } else if (!productId.value && products.value.length > 0) {
productId.value = products.value[0]?.id productId.value = products.value[0]?.id
} }
} catch (e) { } catch (e) {
@@ -3,11 +3,15 @@
<p class="dptr-card__price">{{ usePrice(item.target_price) }}</p> <p class="dptr-card__price">{{ usePrice(item.target_price) }}</p>
<div class="dptr-card__meta"> <div class="dptr-card__meta">
<div v-if="isGreater" class="dptr-card__row">
<span class="dptr-card__label">جهت قیمت:</span>
<span class="dptr-card__value">بزرگتر</span>
</div>
<div class="dptr-card__row"> <div class="dptr-card__row">
<span class="dptr-card__label">محصول:</span> <span class="dptr-card__label">محصول:</span>
<span class="dptr-card__value">{{ productTitle }}</span> <span class="dptr-card__value">{{ productTitle }}</span>
</div> </div>
<div class="dptr-card__row"> <div v-if="!isGreater" class="dptr-card__row">
<span class="dptr-card__label">جهت قیمت:</span> <span class="dptr-card__label">جهت قیمت:</span>
<span class="dptr-card__value">{{ returnPriceCondition(item.price_condition) }}</span> <span class="dptr-card__value">{{ returnPriceCondition(item.price_condition) }}</span>
</div> </div>
@@ -76,8 +80,14 @@
</div> </div>
</div> </div>
<div class="flex flex-col gap-2 mt-2"> <div class="flex flex-col gap-2 mt-2">
<BasicInfoItem v-if="isGreater" is-line title="جهت قیمت" value="بزرگتر" />
<BasicInfoItem is-line title="محصول" :value="productTitle" /> <BasicInfoItem is-line title="محصول" :value="productTitle" />
<BasicInfoItem is-line title="جهت قیمت" :value="returnPriceCondition(item.price_condition)" /> <BasicInfoItem
v-if="!isGreater"
is-line
title="جهت قیمت"
:value="returnPriceCondition(item.price_condition)"
/>
</div> </div>
<a-divider class="!my-3" /> <a-divider class="!my-3" />
<div class="flex justify-between mt-1"> <div class="flex justify-between mt-1">
@@ -133,6 +143,7 @@ const props = withDefaults(
const emits = defineEmits(['edit', 'refresh']) const emits = defineEmits(['edit', 'refresh'])
const productTitle = computed(() => props.item.product?.title || 'طلا') const productTitle = computed(() => props.item.product?.title || 'طلا')
const isGreater = computed(() => props.item.price_condition === '>')
onMounted(() => { onMounted(() => {
isActive.value = props.item.is_active isActive.value = props.item.is_active
@@ -8,13 +8,12 @@
> >
<div class="flex flex-col gap-4 w-full"> <div class="flex flex-col gap-4 w-full">
<a-form-item :rules="[required()]" label="محصول" name="product_id"> <a-form-item :rules="[required()]" label="محصول" name="product_id">
<BasicSelect <ProductPicker
v-model:value="form.product_id" v-model:value="form.product_id"
:items="products" :items="products"
key-name="id"
placeholder="آبشده، سکه، نقره و ..." placeholder="آبشده، سکه، نقره و ..."
size="large" sheet-title="انتخاب محصول هشدار"
value-name="title" allow-clear
/> />
</a-form-item> </a-form-item>
<a-form-item :rules="[required()]" label="جهت قیمت" name="price_condition"> <a-form-item :rules="[required()]" label="جهت قیمت" name="price_condition">
@@ -53,6 +52,7 @@
import BasicButton from '@/components/BasicPacks/BasicButton.vue' import BasicButton from '@/components/BasicPacks/BasicButton.vue'
import BasicInput from '@/components/BasicPacks/BasicInput.vue' import BasicInput from '@/components/BasicPacks/BasicInput.vue'
import BasicSelect from '@/components/BasicPacks/BasicSelect.vue' import BasicSelect from '@/components/BasicPacks/BasicSelect.vue'
import ProductPicker from '@/components/BasicPacks/ProductPicker.vue'
import { required } from '@/utils/inputRules' import { required } from '@/utils/inputRules'
import { usePriceTriggerPageContext } from '../composables/usePriceTriggerPage' import { usePriceTriggerPageContext } from '../composables/usePriceTriggerPage'
@@ -276,6 +276,7 @@ import { useWalletAssets } from '@/composables/useWalletAssets'
import { useCartStore } from '@/store/cartStore' import { useCartStore } from '@/store/cartStore'
import { getStoreClosedMessage, isStoreClosed } from '@/utils/storeHours' import { getStoreClosedMessage, isStoreClosed } from '@/utils/storeHours'
import { isProductTradingHoursOpen, productHoursClosedMessage } from '@/utils/productTradeOpen' import { isProductTradingHoursOpen, productHoursClosedMessage } from '@/utils/productTradeOpen'
import { loadServiceFeeFromSettings, serviceFeePercentage } from '@/utils/serviceFee'
const typeDeal: SelectItem[] = [ const typeDeal: SelectItem[] = [
{ {
@@ -313,8 +314,14 @@ interface Prop {
const props = withDefaults(defineProps<Prop>(), {}) const props = withDefaults(defineProps<Prop>(), {})
const isBuy = ref<boolean>(true) const isBuy = ref<boolean>(true)
const buyFee = computed(() => ((props?.ProductItem?.amount * (props?.ProductItem?.percent_fee_buy ?? 0) * (props?.ProductItem?.price ?? 0)).toFixed(0)))
const sellFee = computed(() => ((props?.ProductItem?.amount * (props?.ProductItem?.percent_fee_sell ?? 0) * (props?.ProductItem?.sellPrice ?? 0)).toFixed(0))) /** کارمزد از fee_service_charge_percentage نسبت به قیمت واحد × تعداد — نه وزن گرم */
function countDealFeeRial(unitPrice?: number | null, count = Number(form.value?.goldValue ?? 0)) {
return count * Number(unitPrice ?? 0) * Number(serviceFeePercentage.value)
}
const buyFee = computed(() => countDealFeeRial(props?.ProductItem?.price).toFixed(0))
const sellFee = computed(() => countDealFeeRial(props?.ProductItem?.sellPrice).toFixed(0))
const sellFeeGeram = computed(() => { const sellFeeGeram = computed(() => {
if (form.value.goldVazn) if (form.value.goldVazn)
return (form.value.goldVazn * props.ProductItem?.percent_fee_sell).toFixed(3) return (form.value.goldVazn * props.ProductItem?.percent_fee_sell).toFixed(3)
@@ -344,8 +351,10 @@ const sellPagination = ref<TableEngineInput>({
}) })
const finalPrice = computed(() => (form.value?.goldValue * (isBuy.value ? props.ProductItem?.price ?? 0 : props.ProductItem?.sellPrice ?? 0))) const finalPrice = computed(() => (form.value?.goldValue * (isBuy.value ? props.ProductItem?.price ?? 0 : props.ProductItem?.sellPrice ?? 0)))
// const payablePrice = computed(() => finalPrice.value + finalPrice.value * 0.007) const payablePrice = computed(() => {
const payablePrice = computed(() => finalPrice.value) const fee = countDealFeeRial(isBuy.value ? props.ProductItem?.price : props.ProductItem?.sellPrice)
return isBuy.value ? finalPrice.value + fee : Math.max(0, finalPrice.value - fee)
})
const disableTransaction = computed(() => { const disableTransaction = computed(() => {
if (isStoreClosed() || !isProductTradingHoursOpen(props.ProductItem)) { if (isStoreClosed() || !isProductTradingHoursOpen(props.ProductItem)) {
@@ -466,6 +475,7 @@ async function initSellTable() {
// } // }
onMounted(async () => { onMounted(async () => {
await loadServiceFeeFromSettings()
switch (router.currentRoute.value.query.state) { switch (router.currentRoute.value.query.state) {
case 'sell': case 'sell':
isBuy.value = false isBuy.value = false
@@ -570,7 +580,10 @@ function calculateCash(val: number) {
console.log(val,props?.ProductItem?.price,props?.ProductItem?.cash_fee_buy,lastPrice.value?.buy) console.log(val,props?.ProductItem?.price,props?.ProductItem?.cash_fee_buy,lastPrice.value?.buy)
if (isBuy.value) { if (isBuy.value) {
if (val){ if (val){
form.value.goldCash = parseFloat(val * (( props?.ProductItem?.price) + (props?.ProductItem?.cash_fee_buy))).toFixed(0) const base = Number(props?.ProductItem?.price ?? 0)
const goods = val * (base + Number(props?.ProductItem?.cash_fee_buy ?? 0))
const fee = countDealFeeRial(base, val)
form.value.goldCash = parseFloat(String(goods + fee)).toFixed(0)
} }
else { else {
form.value.goldCash = 0 form.value.goldCash = 0
@@ -578,8 +591,12 @@ console.log(val,props?.ProductItem?.price,props?.ProductItem?.cash_fee_buy,lastP
} }
} }
else { else {
if (val) if (val) {
form.value.goldCash = parseFloat((val * props?.ProductItem?.price) + (props?.ProductItem?.cash_fee_sell)).toFixed(0) const base = Number(props?.ProductItem?.price ?? 0)
const goods = val * base + Number(props?.ProductItem?.cash_fee_sell ?? 0)
const fee = countDealFeeRial(base, val)
form.value.goldCash = parseFloat(String(Math.max(0, goods - fee))).toFixed(0)
}
else{ else{
form.value.goldCash = 0 form.value.goldCash = 0
form.value.goldVazn = 0 form.value.goldVazn = 0
@@ -90,9 +90,9 @@
{{ props.ProductItem.title }} {{ props.ProductItem.title }}
</div> </div>
<div class="text-xs text-gray-500"> <!-- <div class="text-xs text-gray-500">
{{ amountProduct }} {{ amountProduct }}
</div> </div> -->
</div> </div>
<div <div
@@ -14,6 +14,7 @@ import { getLastStreamProductsList, subscribeProductListStream } from '@/utils/p
let initPromise: Promise<void> | null = null let initPromise: Promise<void> | null = null
let productListInterval: ReturnType<typeof setInterval> | undefined let productListInterval: ReturnType<typeof setInterval> | undefined
let catalogStreamRefreshTimer: ReturnType<typeof setTimeout> | undefined
let providerMountCount = 0 let providerMountCount = 0
let pricePollingMountCount = 0 let pricePollingMountCount = 0
let unsubscribeProductStream: (() => void) | undefined let unsubscribeProductStream: (() => void) | undefined
@@ -72,6 +73,10 @@ function pruneEmptyTypeItems() {
productsTypeItems.value = productsTypeItems.value.filter((key) => present.has(key)) productsTypeItems.value = productsTypeItems.value.filter((key) => present.has(key))
} }
function productRowId(product: Product): number {
return Number(product.id)
}
function productFileId(product: Product): number { function productFileId(product: Product): number {
return Number(product.file_id ?? (product.file as { id?: number } | undefined)?.id ?? 0) return Number(product.file_id ?? (product.file as { id?: number } | undefined)?.id ?? 0)
} }
@@ -85,43 +90,47 @@ function productHasDisplayImage(product: Product): boolean {
} }
/** استریم گاهی file خالی با همان file_id می‌فرستد — عکس خوب HTTP را پاک نکن. */ /** استریم گاهی file خالی با همان file_id می‌فرستد — عکس خوب HTTP را پاک نکن. */
function mergeLiveProduct(prev: Product, incoming: Product): Product {
const next: Product = {
...prev,
...incoming,
open_buy: 'open_buy' in incoming ? incoming.open_buy : prev.open_buy,
open_sell: 'open_sell' in incoming ? incoming.open_sell : prev.open_sell,
}
if (!productHasDisplayImage(incoming) && productHasDisplayImage(prev)) {
next.file = prev.file
next.file_id = prev.file_id ?? (prev.file as { id?: number } | undefined)?.id ?? incoming.file_id
next.img = prev.img
} else if (productFileId(prev) > productFileId(incoming)) {
next.file = prev.file
next.file_id = prev.file_id
next.img = prev.img
}
return next
}
function mergeLiveProductList(incoming: Product[], current?: Product[]): Product[] { function mergeLiveProductList(incoming: Product[], current?: Product[]): Product[] {
if (!current?.length) return incoming if (!current?.length) return incoming
const currentById = new Map(current.map((item) => [item.id, item])) const currentById = new Map(current.map((item) => [productRowId(item), item]))
const incomingById = new Map(incoming.map((item) => [productRowId(item), item]))
const incomingIds = incoming.map(productRowId)
const isPatch =
incoming.length < current.length &&
incomingIds.every((id) => currentById.has(id))
if (isPatch) {
return current.map((item) => {
const updated = incomingById.get(productRowId(item))
return updated ? mergeLiveProduct(item, updated) : item
})
}
return incoming.map((item) => { return incoming.map((item) => {
const prev = currentById.get(item.id) const prev = currentById.get(productRowId(item))
if (!prev) return item return prev ? mergeLiveProduct(prev, item) : item
const prevId = productFileId(prev)
const nextId = productFileId(item)
const keepTradeFlags = {
open_buy: 'open_buy' in item ? item.open_buy : prev.open_buy,
open_sell: 'open_sell' in item ? item.open_sell : prev.open_sell,
}
if (!productHasDisplayImage(item) && productHasDisplayImage(prev)) {
return {
...item,
...keepTradeFlags,
file: prev.file,
file_id: prev.file_id ?? (prev.file as { id?: number } | undefined)?.id ?? item.file_id,
img: prev.img,
}
}
if (prevId > nextId) {
return {
...item,
...keepTradeFlags,
file: prev.file,
file_id: prev.file_id,
img: prev.img,
}
}
return { ...item, ...keepTradeFlags }
}) })
} }
@@ -141,16 +150,18 @@ function isListedProduct(product: Product): boolean {
return flagOn(product.active) return flagOn(product.active)
} }
/** لیست SSE فروشگاه دیگر را روی این صفحه ننشان */ /** لیست SSE فروشگاه دیگر را روی این صفحه ننشان؛ پچ یک‌محصوله همین فروشگاه را بپذیر */
function isSameShopCatalog(incoming: Product[], current?: Product[]): boolean { function isSameShopCatalog(incoming: Product[], current?: Product[]): boolean {
if (!current?.length) return true if (!current?.length) return true
const incomingIds = new Set(incoming.map((item) => item.id)) const incomingIds = incoming.map((item) => productRowId(item))
const currentIds = new Set(current.map((item) => item.id)) const currentIds = new Set(current.map((item) => productRowId(item)))
let overlap = 0 let overlap = 0
incomingIds.forEach((id) => { incomingIds.forEach((id) => {
if (currentIds.has(id)) overlap += 1 if (currentIds.has(id)) overlap += 1
}) })
return overlap / Math.max(incomingIds.size, currentIds.size) >= 0.5 if (overlap === 0) return false
if (overlap === incomingIds.length) return true
return overlap / Math.max(incomingIds.length, currentIds.size) >= 0.5
} }
function applyProductsList(products: Product[]) { function applyProductsList(products: Product[]) {
@@ -171,10 +182,33 @@ function applyProductsList(products: Product[]) {
productsPageLoading.value = false productsPageLoading.value = false
} }
/** قیمت enrich شده فقط در HTTP کامل است؛ slim SSE برای پرچم‌هاست */
function onTvBoard() {
if (typeof window === 'undefined') return false
const path = window.location.pathname.replace(/\/+$/, '') || '/'
return path === '/tv' || path.endsWith('/tv') || path === '/monitor' || path.endsWith('/monitor')
}
function scheduleCatalogRefreshFromStream() {
if (priceStreamLifecycle.value === 'open' || !shouldUsePricePolling() || onTvBoard()) {
if (catalogStreamRefreshTimer) {
clearTimeout(catalogStreamRefreshTimer)
catalogStreamRefreshTimer = undefined
}
return
}
if (catalogStreamRefreshTimer) {
clearTimeout(catalogStreamRefreshTimer)
}
catalogStreamRefreshTimer = setTimeout(() => {
catalogStreamRefreshTimer = undefined
void refreshProductsPageData()
}, 150)
}
/** /**
* SSE همیشه لیست کامل محصولات فعال را می‌فرستد. * SSE لیست کامل یا پچ می‌فرستد.
* عضو جدید/حذف‌شده را از همان لیست بگیر؛ فقط عکس را از نسخهٔ قبلی نگه دار. * slim فوری برای open_buy/show؛ قیمت کارت مثل رفرش از /customer/product/list.
* آپدیت قیمت روی همان آبجکت‌ها تا گرید نپرد.
*/ */
function applySocketProductList(incoming: Product[], current?: Product[]) { function applySocketProductList(incoming: Product[], current?: Product[]) {
if (!isSameShopCatalog(incoming, current)) { if (!isSameShopCatalog(incoming, current)) {
@@ -184,38 +218,19 @@ function applySocketProductList(incoming: Product[], current?: Product[]) {
const next = sortProductsByInventory( const next = sortProductsByInventory(
mergeLiveProductList(incoming, current).filter(isListedProduct), mergeLiveProductList(incoming, current).filter(isListedProduct),
) )
if (next.length) {
if (!current?.length) {
applyProductsList(next) applyProductsList(next)
return } else {
}
const nextById = new Map(next.map((item) => [item.id, item]))
const currentIds = new Set(current.map((item) => item.id))
const nextIds = new Set(next.map((item) => item.id))
const membershipChanged =
next.length !== current.length ||
next.some((item) => !currentIds.has(item.id)) ||
current.some((item) => !nextIds.has(item.id))
if (membershipChanged) {
applyProductsList(next)
return
}
current.forEach((item) => {
const updated = nextById.get(item.id)
if (updated) {
Object.assign(item, updated)
}
})
getProductsCatalogRef().value = current
changeProductsTab()
productsPageLoading.value = false productsPageLoading.value = false
}
scheduleCatalogRefreshFromStream()
} }
export async function refreshProductsPageData() { export async function refreshProductsPageData() {
if (priceStreamLifecycle.value === 'open' || !shouldUsePricePolling()) {
return
}
try { try {
const fresh = await getProductsCatalog(true) const fresh = await getProductsCatalog(true)
if (!fresh?.length) return if (!fresh?.length) return
@@ -305,6 +320,11 @@ export function onProductsPageProviderUnmounted() {
if (providerMountCount === 0) { if (providerMountCount === 0) {
stopProductListPolling() stopProductListPolling()
initialized.value = false
if (catalogStreamRefreshTimer) {
clearTimeout(catalogStreamRefreshTimer)
catalogStreamRefreshTimer = undefined
}
} }
} }
+2 -1
View File
@@ -59,7 +59,7 @@
<BasicActionSheet placement="bottom" v-model:show="showFilter"> <BasicActionSheet placement="bottom" v-model:show="showFilter">
<div> <div>
<indexGold v-if="selectedProduct?.group_type == 'آبشده'" :ProductItem="selectedProduct" /> <indexGold v-if="isMeltedProductUsingAppPrice(selectedProduct)" :ProductItem="selectedProduct" />
<DealProduct v-else :ProductItem="selectedProduct" @close="showFilter = false" /> <DealProduct v-else :ProductItem="selectedProduct" @close="showFilter = false" />
</div> </div>
</BasicActionSheet> </BasicActionSheet>
@@ -75,6 +75,7 @@ import type { Product } from '@/models/products'
import BasicActionSheet from '@/components/BasicPacks/BasicActionSheet.vue' import BasicActionSheet from '@/components/BasicPacks/BasicActionSheet.vue'
import indexGold from '@/views/base/gold/index.vue' import indexGold from '@/views/base/gold/index.vue'
import DealProduct from '@/views/base/products/components/DealProduct.vue' import DealProduct from '@/views/base/products/components/DealProduct.vue'
import { isMeltedProductUsingAppPrice } from '@/utils/productCategories'
import img from '@/assets/img/user_ly1.svg' import img from '@/assets/img/user_ly1.svg'
import BasicIcon from '@/components/BasicPacks/BasicIcon.vue' import BasicIcon from '@/components/BasicPacks/BasicIcon.vue'
import ProductItemVertical from '@/views/base/products/components/ProductItemVertical.vue' import ProductItemVertical from '@/views/base/products/components/ProductItemVertical.vue'
+26 -4
View File
@@ -32,7 +32,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref } from 'vue' import { computed, onMounted, onUnmounted, ref } from 'vue'
import BasicIcon from '@/components/BasicPacks/BasicIcon.vue' import BasicIcon from '@/components/BasicPacks/BasicIcon.vue'
import { getTvProducts } from '@/api/products' import { getTvProducts, getTvServerTime } from '@/api/products'
import type { Product } from '@/models/products' import type { Product } from '@/models/products'
import { getConfigApp } from '@/utils/config' import { getConfigApp } from '@/utils/config'
import { getTvProductBuyPrice, getTvProductSellPrice, isTvProductPriceInactive } from '@/utils/productPrice' import { getTvProductBuyPrice, getTvProductSellPrice, isTvProductPriceInactive } from '@/utils/productPrice'
@@ -47,6 +47,7 @@ const REFRESH_MS = 15000
const loading = ref(true) const loading = ref(true)
const products = ref<Product[]>([]) const products = ref<Product[]>([])
const now = ref(Date.now()) const now = ref(Date.now())
let serverOffsetMs = 0
let clockTimer: ReturnType<typeof setInterval> | undefined let clockTimer: ReturnType<typeof setInterval> | undefined
let listTimer: ReturnType<typeof setInterval> | undefined let listTimer: ReturnType<typeof setInterval> | undefined
@@ -57,6 +58,7 @@ const shopName = computed(
const clockText = computed(() => const clockText = computed(() =>
new Date(now.value).toLocaleTimeString('fa-IR', { new Date(now.value).toLocaleTimeString('fa-IR', {
timeZone: 'Asia/Tehran',
hour: '2-digit', hour: '2-digit',
minute: '2-digit', minute: '2-digit',
second: '2-digit', second: '2-digit',
@@ -99,10 +101,27 @@ const rows = computed(() => {
}) })
}) })
function normalizeTvProduct(raw: Product): Product {
const image = (raw as Product & { image?: string | null }).image
if (image && !raw.img) {
return { ...raw, img: image }
}
return raw
}
async function syncServerClock() {
const t0 = Date.now()
const payload = await getTvServerTime()
const t1 = Date.now()
if (!payload?.unix) return
const rttHalf = (t1 - t0) / 2
serverOffsetMs = payload.unix * 1000 + rttHalf - t1
}
async function loadProducts() { async function loadProducts() {
try { try {
const list = await getTvProducts() const list = await getTvProducts()
products.value = Array.isArray(list) ? list : [] products.value = (Array.isArray(list) ? list : []).map(normalizeTvProduct)
} catch { } catch {
if (!products.value.length) { if (!products.value.length) {
products.value = [] products.value = []
@@ -112,17 +131,20 @@ async function loadProducts() {
} }
} }
onMounted(() => { onMounted(async () => {
const settingsStore = useSettingsStore() const settingsStore = useSettingsStore()
initPriceRealtimeChannel((key) => settingsStore.getSettingByKey(key)) initPriceRealtimeChannel((key) => settingsStore.getSettingByKey(key))
startLastPricePolling() startLastPricePolling()
void getLastPrices() void getLastPrices()
await syncServerClock()
now.value = Date.now() + serverOffsetMs
void loadProducts() void loadProducts()
clockTimer = setInterval(() => { clockTimer = setInterval(() => {
now.value = Date.now() now.value = Date.now() + serverOffsetMs
}, 1000) }, 1000)
listTimer = setInterval(() => { listTimer = setInterval(() => {
void loadProducts() void loadProducts()
void syncServerClock()
}, REFRESH_MS) }, REFRESH_MS)
}) })
+25 -35
View File
@@ -6,36 +6,16 @@
<!-- <div v-if="URLUserType() === 'single'" class="font-bold text-center text-xl">ورود</div>--> <!-- <div v-if="URLUserType() === 'single'" class="font-bold text-center text-xl">ورود</div>-->
<!-- <div v-else class="font-bold text-center text-xl">ورود همکار</div>--> <!-- <div v-else class="font-bold text-center text-xl">ورود همکار</div>-->
<a-form ref="formRef" :model="userFormState" class="!mt-5" name="basic" @finish="phoneVerification"> <a-form ref="formRef" :model="userFormState" class="!mt-5" name="basic" @finish="phoneVerification">
<!-- <a-segmented v-model:value="value" :options="data" />-->
<div class="flex justify-evenly w-full px-2 h-11 items-center bg-gray-50 relative rounded mb-5">
<div :class="isSMS?'text-primary':'text-gray-400'" class="w-full text-center z-2"
@click.stop="setIsSMS(true) ">
ورود با پیامک
</div>
<div :class="!isSMS?'text-primary':'text-gray-400'" class="w-full text-center z-2"
@click.stop="setIsSMS(false) ">
ورود با کلمه عبور
</div>
<!-- <div ref="bganim" class="absolute bg-white h-8 w-1/2 rounded-lg " :style="`transform: translateX(${isDeposit? '0':'-100%'}); left: ${isDeposit? '0':'100%'}`"></div>-->
<div ref="bganim" :style="useStyle()"
class="absolute bg-white h-8 w-1/2 rounded-lg animate right"></div>
</div>
<!-- <transition name="fade" mode="out-in">-->
<a-form-item v-if="!stepTwoVerify" :rules="[required('شماره تلفن'),mobileValidation()]" <a-form-item v-if="!stepTwoVerify" :rules="[required('شماره تلفن'),mobileValidation()]"
class="home_appear_fade_in_down" label="شماره تلفن" class="home_appear_fade_in_down" label="شماره تلفن"
name="mobile"> name="mobile">
<BasicInput v-model:value="userFormState.mobile" place-holder="شماره تلفن" size="large" inputmode="numeric"/> <BasicInput v-model:value="userFormState.mobile" place-holder="شماره تلفن" size="large" inputmode="numeric"/>
</a-form-item> </a-form-item>
<!-- </transition>-->
<!-- <transition name="fade" mode="out-in">-->
<a-form-item v-if="!isSMS" :rules="[required('کلمه عبور')]" class="home_appear_fade_in_down" label="کلمه عبور" <a-form-item v-if="!isSMS" :rules="[required('کلمه عبور')]" class="home_appear_fade_in_down" label="کلمه عبور"
name="password"> name="password">
<!-- <BasicInput v-model:value="userFormState.password" size="large" place-holder="کلمه عبور"/>-->
<AInputPassword v-model:value="userFormState.password" place-holder="کلمه عبور" size="large" inputmode="decimal"/> <AInputPassword v-model:value="userFormState.password" place-holder="کلمه عبور" size="large" inputmode="decimal"/>
</a-form-item> </a-form-item>
<div v-else-if="!stepTwoVerify" class="h-[90px]"></div> <div v-else-if="stepTwoVerify">
<div v-else>
<AFormItem <AFormItem
:rules="[ :rules="[
{ {
@@ -107,23 +87,42 @@
<div v-else>{{ !isSMS ? 'ورود' : stepTwoVerify ? 'ورود' : 'ارسال کد' }}</div> <div v-else>{{ !isSMS ? 'ورود' : stepTwoVerify ? 'ورود' : 'ارسال کد' }}</div>
</div> </div>
</BasicButton> </BasicButton>
<BasicButton
v-if="isSMS"
class="mt-2 w-full"
html-type="button"
@click="setIsSMS(false)"
>
ورود با رمز عبور
</BasicButton>
<InstallButton /> <InstallButton />
<BasicButton class="mt-2 w-full" @click="goToAboutSoftware"> <BasicButton
class="mt-2 w-full"
html-type="button"
@click="$emit('register', true)"
>
ثبت نام
</BasicButton>
<BasicButton class="mt-2 w-full" html-type="button" @click="goToAboutSoftware">
<div>درباره نرم‌افزار</div> <div>درباره نرم‌افزار</div>
</BasicButton> </BasicButton>
<BasicButton <BasicButton
v-if="getToken() && userStore.userInfo?.finger_print" v-if="getToken() && userStore.userInfo?.finger_print"
:disabled="loading" :disabled="loading"
class=" w-full py-2 mt-2" class=" w-full py-2 mt-2"
html-type="button"
@click="enterFingerPrint" @click="enterFingerPrint"
> >
<div> <div>
ورود با اثر انگشت ورود با اثر انگشت
</div> </div>
</BasicButton> </BasicButton>
<div class="flex gap-1 justify-center mt-5 text-xs" @click="$emit('register',true)">اگر حساب کاربری ندارید <div
<div class="font-bold text-primary">از این قسمت</div> v-if="!isSMS"
ثبت نام کنید. class="w-full text-center mt-3 text-sm font-bold text-gray-600 cursor-pointer"
@click="setIsSMS(true)"
>
فراموشی رمز عبور
</div> </div>
</a-form-item> </a-form-item>
</a-form> </a-form>
@@ -168,8 +167,6 @@ const formRef = ref<FormInstance>()
const userStore = useUserStore() const userStore = useUserStore()
const walletStore = useWalletStore() const walletStore = useWalletStore()
const data = reactive(['ورود با پیامک', 'ورود با کلمه عبور'])
const value = ref(data[0])
const refOtpInput = ref<InstanceType<typeof OtpInput> | null>(null) const refOtpInput = ref<InstanceType<typeof OtpInput> | null>(null)
const userFormState = reactive<Login>({ const userFormState = reactive<Login>({
@@ -189,7 +186,7 @@ async function reSendCode() {
reset() reset()
} }
const isSMS = ref<boolean>(true) const isSMS = ref<boolean>(false)
function setIsSMS(val: boolean) { function setIsSMS(val: boolean) {
isSMS.value = val isSMS.value = val
@@ -212,13 +209,6 @@ function goToAboutSoftware() {
router.push({ name: 'aboutSoftware' }) router.push({ name: 'aboutSoftware' })
} }
function useStyle() {
if (isSMS.value) return 'right: 2%;'
// if (isDeposit.value) return 'animation-direction: normal'
// else return 'animation-direction: reverse'
else return ' right: 98%; transform: translate(100%, 0);'
}
function handleOnChange(value: string) { function handleOnChange(value: string) {
userFormState.token = persianToEnglishDigits(String(value ?? '')) userFormState.token = persianToEnglishDigits(String(value ?? ''))
// formRef.value?.validateFields() // formRef.value?.validateFields()
+66 -6
View File
@@ -1,7 +1,7 @@
import { computed, onMounted, onUnmounted, ref } from 'vue' import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useFullscreen } from '@vueuse/core' import { useFullscreen } from '@vueuse/core'
import type { Product } from '@/models/products' import type { Product } from '@/models/products'
import { getTvProducts } from '@/api/products' import { getTvProducts, getTvServerTime } from '@/api/products'
import { getConfigApp } from '@/utils/config' import { getConfigApp } from '@/utils/config'
import { useSettingsStore } from '@/store/settingsStore' import { useSettingsStore } from '@/store/settingsStore'
import { getTvProductBuyPrice, getTvProductSellPrice, isTvProductPriceInactive } from '@/utils/productPrice' import { getTvProductBuyPrice, getTvProductSellPrice, isTvProductPriceInactive } from '@/utils/productPrice'
@@ -9,7 +9,8 @@ import { getLastPrices, getTradeBuyPrice, getTradeSellPrice, lastPrice, startLas
import { usePriceWithoutType } from '@/utils/usePrice' import { usePriceWithoutType } from '@/utils/usePrice'
import { getPriceDisplayMessage, getPriceDisplayState, NO_QUOTE_MESSAGE } from '@/utils/storeHours' import { getPriceDisplayMessage, getPriceDisplayState, NO_QUOTE_MESSAGE } from '@/utils/storeHours'
import { isMeltedTradeGroup, isMetalCommodityGroup } from '@/utils/productCategories' import { isMeltedTradeGroup, isMetalCommodityGroup } from '@/utils/productCategories'
import { priceSocketConnected, priceStreamLifecycle } from '@/utils/priceSocketState' import { priceSocketConnected, priceStreamLifecycle, priceStreamProducts, priceStreamServerUnix } from '@/utils/priceSocketState'
import { startTvPriceStream, stopTvPriceStream } from '@/utils/priceSocket'
import logoFallback from '@/assets/img/logo_full_.png' import logoFallback from '@/assets/img/logo_full_.png'
//@ts-ignore //@ts-ignore
import moment from 'moment-jalaali' import moment from 'moment-jalaali'
@@ -73,7 +74,10 @@ function isBankCoin(product: Product) {
const title = (product.title ?? '').trim() const title = (product.title ?? '').trim()
if (group === 'سکه' || group === 'سکه بانکی') return true if (group === 'سکه' || group === 'سکه بانکی') return true
if (group.includes('سکه') && !group.includes('پارسیان')) return true if (group.includes('سکه') && !group.includes('پارسیان')) return true
return title.includes('بانکی') if (title.includes('بانکی')) return true
// API سبک TV ممکن است group_type نداشته باشد
if (title.includes('سکه') && !title.includes('پارسیان')) return true
return false
} }
function bankCoinRank(product: Product) { function bankCoinRank(product: Product) {
@@ -116,6 +120,26 @@ export function useTvMonitorPage() {
let clockTimer: ReturnType<typeof setInterval> | undefined let clockTimer: ReturnType<typeof setInterval> | undefined
let cursorTimer: ReturnType<typeof setTimeout> | undefined let cursorTimer: ReturnType<typeof setTimeout> | undefined
let listTimer: ReturnType<typeof setInterval> | undefined let listTimer: ReturnType<typeof setInterval> | undefined
/** اختلاف میلی‌ثانیهٔ ساعت سرور (Asia/Tehran) با Date.now محلی */
let serverOffsetMs = 0
let tvStreamReady = false
function openTvStream(key: string) {
const secret = key.trim()
if (!secret || tvStreamReady) return
tvStreamReady = true
startTvPriceStream((settingKey) => settingsStore.getSettingByKey(settingKey), secret)
}
watch(priceStreamProducts, (rows) => {
if (!rows.length) return
products.value = (rows as Product[]).map(normalizeTvProduct)
})
watch(priceStreamServerUnix, (unix) => {
if (!unix) return
serverOffsetMs = unix * 1000 - Date.now()
})
const brandName = computed( const brandName = computed(
() => String(getConfigApp('name_fa') || getConfigApp('name') || 'تابلو قیمت'), () => String(getConfigApp('name_fa') || getConfigApp('name') || 'تابلو قیمت'),
@@ -130,6 +154,24 @@ export function useTvMonitorPage() {
return marked.length ? marked : list return marked.length ? marked : list
}) })
function normalizeTvProduct(raw: Product): Product {
const image = (raw as Product & { image?: string | null }).image
if (image && !raw.img) {
return { ...raw, img: image }
}
return raw
}
async function syncServerClock() {
const t0 = Date.now()
const payload = await getTvServerTime()
const t1 = Date.now()
if (!payload?.unix) return
const rttHalf = (t1 - t0) / 2
serverOffsetMs = payload.unix * 1000 + rttHalf - t1
if (payload.stream_key) openTvStream(payload.stream_key)
}
const parsianCoins = computed(() => const parsianCoins = computed(() =>
catalogProducts.value catalogProducts.value
.filter(isParsianCoin) .filter(isParsianCoin)
@@ -205,9 +247,11 @@ export function useTvMonitorPage() {
) )
async function loadProducts() { async function loadProducts() {
if (priceStreamProducts.value.length) return
try { try {
const list = await getTvProducts() const list = await getTvProducts()
products.value = Array.isArray(list) ? list : [] if (priceStreamProducts.value.length) return
products.value = (Array.isArray(list) ? list : []).map(normalizeTvProduct)
} catch { } catch {
if (!products.value.length) { if (!products.value.length) {
products.value = [] products.value = []
@@ -218,7 +262,7 @@ export function useTvMonitorPage() {
} }
function updateClock() { function updateClock() {
const now = moment() const now = moment(Date.now() + serverOffsetMs).utcOffset(210)
nowLabel.value = now.format('HH:mm:ss') nowLabel.value = now.format('HH:mm:ss')
dateLabel.value = now.format('dddd jD jMMMM jYYYY') dateLabel.value = now.format('dddd jD jMMMM jYYYY')
} }
@@ -297,13 +341,23 @@ export function useTvMonitorPage() {
return isTvProductPriceInactive(product) return isTvProductPriceInactive(product)
} }
function isProductTvBuyInactive(product: Product) {
return Number(product.tv_price ?? 0) <= 0
}
function isProductTvSellInactive(product: Product) {
return Number(product.tv_sell_price ?? 0) <= 0
}
function productBuyLabel(product: Product) { function productBuyLabel(product: Product) {
if (isProductTvInactive(product)) return NO_QUOTE_MESSAGE if (isProductTvInactive(product)) return NO_QUOTE_MESSAGE
if (isProductTvBuyInactive(product)) return '—'
return formatTvPrice(getTvProductBuyPrice(product)) return formatTvPrice(getTvProductBuyPrice(product))
} }
function productSellLabel(product: Product) { function productSellLabel(product: Product) {
if (isProductTvInactive(product)) return NO_QUOTE_MESSAGE if (isProductTvInactive(product)) return NO_QUOTE_MESSAGE
if (isProductTvSellInactive(product)) return '—'
return formatTvPrice(getTvProductSellPrice(product)) return formatTvPrice(getTvProductSellPrice(product))
} }
@@ -313,6 +367,7 @@ export function useTvMonitorPage() {
onMounted(async () => { onMounted(async () => {
document.documentElement.classList.add(TV_HTML_CLASS) document.documentElement.classList.add(TV_HTML_CLASS)
await syncServerClock()
updateClock() updateClock()
hideCursorSoon() hideCursorSoon()
clockTimer = setInterval(updateClock, 1000) clockTimer = setInterval(updateClock, 1000)
@@ -324,7 +379,9 @@ export function useTvMonitorPage() {
void getLastPrices() void getLastPrices()
void loadProducts() void loadProducts()
listTimer = setInterval(() => { listTimer = setInterval(() => {
if (isLive.value) return
void loadProducts() void loadProducts()
void syncServerClock()
}, REFRESH_MS) }, REFRESH_MS)
document.title = `${brandName.value} | تابلو قیمت` document.title = `${brandName.value} | تابلو قیمت`
@@ -340,6 +397,7 @@ export function useTvMonitorPage() {
document.removeEventListener('visibilitychange', onVisibilityChange) document.removeEventListener('visibilitychange', onVisibilityChange)
void releaseWakeLock() void releaseWakeLock()
stopLastPricePolling() stopLastPricePolling()
stopTvPriceStream()
}) })
return { return {
@@ -369,6 +427,8 @@ export function useTvMonitorPage() {
productWeightLabel, productWeightLabel,
tickerItemLabel, tickerItemLabel,
isProductTvInactive, isProductTvInactive,
isProductTvBuyInactive,
isProductTvSellInactive,
productBuyLabel, productBuyLabel,
productSellLabel, productSellLabel,
liveQuoteLabel, liveQuoteLabel,
+12 -4
View File
@@ -118,17 +118,17 @@
<div class="tv-row__prices"> <div class="tv-row__prices">
<div <div
class="tv-row__price tv-row__price--sell" class="tv-row__price tv-row__price--sell"
:class="{ 'tv-row__price--empty': isProductTvInactive(item) }" :class="{ 'tv-row__price--empty': isProductTvBuyInactive(item) }"
> >
<strong>{{ productBuyLabel(item) }}</strong> <strong>{{ productBuyLabel(item) }}</strong>
<em v-if="!isProductTvInactive(item) && productBuyLabel(item) !== '—'">تومان</em> <em v-if="!isProductTvBuyInactive(item) && productBuyLabel(item) !== '—'">تومان</em>
</div> </div>
<div <div
class="tv-row__price tv-row__price--buy" class="tv-row__price tv-row__price--buy"
:class="{ 'tv-row__price--empty': isProductTvInactive(item) }" :class="{ 'tv-row__price--empty': isProductTvSellInactive(item) }"
> >
<strong>{{ productSellLabel(item) }}</strong> <strong>{{ productSellLabel(item) }}</strong>
<em v-if="!isProductTvInactive(item) && productSellLabel(item) !== '—'">تومان</em> <em v-if="!isProductTvSellInactive(item) && productSellLabel(item) !== '—'">تومان</em>
</div> </div>
</div> </div>
</article> </article>
@@ -276,6 +276,8 @@ const {
productWeightLabel, productWeightLabel,
tickerItemLabel, tickerItemLabel,
isProductTvInactive, isProductTvInactive,
isProductTvBuyInactive,
isProductTvSellInactive,
productBuyLabel, productBuyLabel,
productSellLabel, productSellLabel,
liveQuoteLabel, liveQuoteLabel,
@@ -900,6 +902,12 @@ const coinColumns = computed(() => [
padding: 8px 16px calc(8px + env(safe-area-inset-bottom, 0px)); padding: 8px 16px calc(8px + env(safe-area-inset-bottom, 0px));
background: #fff; background: #fff;
box-shadow: 0 -2px 4px -2px #0000001a; box-shadow: 0 -2px 4px -2px #0000001a;
:deep(.app-credit-link__logo) {
height: 16px;
max-width: 120px;
width: auto;
}
} }
.tv-ticker { .tv-ticker {