product_to_sku_c1 #5

Closed
shafi wants to merge 43 commits from product_to_sku_c1 into master
273 changed files with 41855 additions and 11854 deletions

View file

@ -0,0 +1,40 @@
{
"permissions": {
"allow": [
"Shell(npx tsc --noEmit --skipLibCheck src/trpc/apis/common-apis/common.ts 2 >& 1)",
"Shell(npx tsc --noEmit 2 >& 1)",
"Shell(grep:*)",
"Shell(npx tsc --noEmit -p packages/shared/tsconfig.json 2 >& 1)",
"Shell(cp:*)",
"Shell(rm:*)",
"Shell(ls:*)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/admin-ui && ls \"app/(drawer)\" 2>/dev/null; echo \"---\"; find app -name \"create.tsx\" -path \"*coupon*\" 2>/dev/null)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/user-ui && echo \"=== verify zero external refs for each dead file ===\" && for f in \"ProfileChecker\" \"UserAddressHeader\" \"AddressSelector\" \"OrderAgainIcon\" \"usePhonepeSdk\" \"useHideDrawerHeader\" \"useCurrentUserId\" \"useThemeColor\" \"IconSymbol\" \"TabBarBackground\" \"axios-user-ui\"; do refs=$(grep -rn \"$f\" --include=\"*.tsx\" --include=\"*.ts\" . 2>/dev/null | grep -v node_modules | grep -vE \"components/ProfileChecker|components/UserAddressHeader|components/AddressSelector|icons/OrderAgainIcon|hooks/usePhonepeSdk|hooks/useHideDrawerHeader|hooks/useCurrentUserId|hooks/useThemeColor|components/ui/IconSymbol|components/ui/TabBarBackground|services/axios-user-ui\" | wc -l | tr -d ' '); echo \"$f: $refs external refs\"; done)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && echo \"=== usage count per export across apps (excluding packages/ui itself) ===\" && for name in RolesDropdown StorageService ROLE_NAMES ROLE_DISPLAY_NAMES ROLE_OPTIONS BUSINESS_ROLE_OPTIONS REFUND_STATUS MyButton MyTextButton MyTextInput BottomDialog LoadingDialog MyText MyTouchableOpacity ConfirmationDialog RawBottomDialog DatePicker BottomDropdown ImageViewerURI ImageCarousel ImageGallery ImageGalleryWithDelete ImageUploader ImageUploaderNeo ProfileImage Checkbox AppContainer SearchBar DataTable Quantifier MiniQuantifier TabViewWrapper MyFlatList useFocusCallback useManualRefresh useDrawerTitle useMarkDataFetchers useIsDevMode usePagination DateTimePickerMod RefreshProvider useRefresh MyStatusBar updateStatusBarColor useStatusBarStore; do count=$(grep -rn \"\\b$name\\b\" apps/user-ui apps/admin-ui apps/web-ui apps/fallback-ui --include=\"*.tsx\" --include=\"*.ts\" 2>/dev/null | grep -v node_modules | wc -l | tr -d ' '); echo \"$name: $count\"; done)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && echo \"=== check usage inside packages/ui (internal use) ===\" && for name in RolesDropdown ROLE_DISPLAY_NAMES ROLE_OPTIONS BUSINESS_ROLE_OPTIONS MyTextButton ImageGallery ImageGalleryWithDelete DataTable TabViewWrapper useIsDevMode usePagination useRefresh useStatusBarStore; do count=$(grep -rn \"\\b$name\\b\" packages/ui --include=\"*.tsx\" --include=\"*.ts\" 2>/dev/null | grep -v node_modules | grep -v \"index.ts\" | wc -l | tr -d ' '); echo \"$name: $count internal\"; done)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/backend/dumps && echo \"=== lines 7890-7910 (product_skus start) ===\" && sed -n '7890,7910p' local_8_aug.sql && echo \"=== lines 8330-8345 (product_info start) ===\" && sed -n '8330,8345p' local_8_aug.sql && echo \"=== total lines ===\" && wc -l local_8_aug.sql && echo \"=== where does product_info block end? next CREATE/other marker ===\" && grep -nE \"CREATE TABLE|^INSERT INTO \\\"product_info\\\"|^INSERT INTO \\`product_info\\`|^INSERT INTO product_info\" local_8_aug.sql | sed -n '25,40p')",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/backend/dumps && echo \"=== product_info block: from 8334 to next CREATE TABLE after it ===\" && awk 'NR>=8334 && /^CREATE TABLE/ {print NR\": \"$0; exit}' local_8_aug.sql && echo \"=== where do product_skus INSERTs start/end ===\" && grep -nE \"^INSERT INTO \\`?product_skus\\`?|^INSERT INTO \\\"product_skus\\\"\" local_8_aug.sql | head && echo \"=== where do sku_features/product_market_stats/product_info INSERTs start ===\" && grep -nE \"^INSERT INTO \\`?(product_skus|sku_features|product_market_stats|product_info)\\`?\" local_8_aug.sql | head && echo \"=== what comes right after product_info INSERTs (next table or marker) ===\" && awk 'NR>8334 && /^CREATE TABLE/ {print NR\": \"$0}' local_8_aug.sql | head)",
"Shell(awk:*)",
"Shell(echo:*)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/backend/dumps && python3 - <<'PY' # Move the product_info block (CREATE + INSERTs) above product_skus. with open('local_8_aug.sql', 'r') as f: lines = f.readlines() # 1-indexed boundaries pi_start = 8334 - 1 # CREATE TABLE product_info pi_end = 8478 # exclusive (up to line 8478 inclusive) -> slice [8333:8478] sku_start = 7900 - 1 # line where product_skus CREATE begins block = lines[pi_start:pi_end] # Remove the product_info block new_lines = lines[:pi_start] + lines[pi_end:] # Re-insert before product_skus (its index may have shifted by -len(block)) insert_at = sku_start new_lines = new_lines[:insert_at] + block + new_lines[insert_at:] with open('local_8_aug.sql', 'w') as f: f.writelines(new_lines) print(f\"Moved product_info block (lines {pi_start+1}-{pi_end}) to before line {sku_start+1}\") PY echo \"=== verify new order ===\" && grep -nE 'CREATE TABLE .(product_info|product_skus|sku_features|product_market_stats|cart_items).' local_8_aug.sql)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/backend/dumps && echo \"=== order: product_info BEFORE product_skus? ===\" && grep -nE '^CREATE TABLE' local_8_aug.sql | grep -E \"product_info|product_skus|sku_features|product_market_stats|cart_items\" && echo \"=== doc check: every REFERENCES has parent CREATE before it ===\" && grep -nE '^CREATE TABLE|REFERENCES' local_8_aug.sql | grep -E \"REFERENCES\" | grep -oE \"REFERENCES \\`?[a-z_]+\" | sort | uniq -c)",
"Shell(sqlite3:*)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/backend/dumps && sqlite3 :memory: <<'EOF' PRAGMA foreign_keys=ON; BEGIN; .read local_8_aug.sql COMMIT; EOF echo \"exit: $?\")",
"Shell(cd:*)",
"Shell(mv:*)",
"Shell(npm:*)",
"Shell(curl -s http://localhost:4174/home 2 >& 1)",
"Shell(curl -s https://assets.freshyo.in/api-cache/v-690/products.json 2 >& 1)",
"Shell(python3 -c import sys,json; d=json.load(sys.stdin); print('products:', len(d.get('products',[]))); print('tags:', [t['tagName'] for t in d.get('tags',[])][:10]) 2 >& 1)",
"Shell(lsof:*)",
"Shell(curl -s http://localhost:8787/api/trpc/common.essentialConsts 2 >& 1)",
"Shell(curl -s https://assets2.freshyo.in/api-cache-dev/v-684/products.json 2 >& 1)",
"Shell(python3 -c import sys,json; d=json.load(sys.stdin); print('products:', len(d.get('products',[]))); print('tags:', [t['tagName'] for t in d.get('tags',[])][:12]) 2 >& 1)",
"Shell(curl -s http://localhost:4174/src/styles.css 2 > /dev/null)",
"Shell(printf:*)",
"Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo/apps/backend && python3 - <<'EOF' import re with open('dumps/local_8_aug.sql') as f: content = f.read() # Find all CREATE TABLE positions and all REFERENCES target tables create_positions = {} # table name -> line for m in re.finditer(r'CREATE TABLE(?: IF NOT EXISTS)? \"?([A-Za-z_]+)\"? \\(', content): create_positions[m.group(1)] = content.count('\\n', 0, m.start()) + 1 # Verify each REFERENCES target is defined before the referencing CREATE errors = [] for m in re.finditer(r'CREATE TABLE(?: IF NOT EXISTS)? \"?([A-Za-z_]+)\"? \\(([^;]*?)\\)', content, re.S): table = m.group(1) table_line = content.count('\\n', 0, m.start()) + 1 body = m.group(2) for ref in re.findall(r'REFERENCES `?([A-Za-z_]+)`?\\(', body): if ref in create_positions and create_positions[ref] > table_line: errors.append(f\"{table} (line {table_line}) references {ref} (defined line {create_positions[ref]})\") if errors: print(\"FAIL - out of order:\") for e in errors: print(\" \", e) else: print(\"PASS - all REFERENCES resolve to tables defined earlier\") EOF)"
],
"deny": [],
"defaultMode": "default"
}
}

View file

@ -0,0 +1,2 @@
# Taste
See [taste/taste.md](taste/taste.md)

View file

@ -0,0 +1,102 @@
# Taste
- Prefers that the agent not run typechecks; instead, read the project's AGENTS.md for instructions on what to do/not do before finalizing work. Confidence: 0.9
- Judges completion by seeing the feature live in the running app ("I still don't see it on the /home route page"), so for data-driven features the agent must verify the app's actual runtime data source (API base URL, cache/backend) has the required data — not just that code builds and typechecks. Confirmed when the user signaled success only after the fix (pointing web-ui at the local backend with the tags data) made the section visible in the running app, and reconfirmed with the admin-ui product selector showing no products because it points at the production worker. Confidence: 0.9
- Prefers detailed analysis and explicit error/mistake checking before executing destructive operations, rather than just performing the action — e.g., before a git merge, or before deleting a row directly from the DB (asked "Can I simply delete the row from db. Will it cause any problems" about an unclaimed reserved coupon, expecting the agent to trace all referencing tables/FKs — couponUsages, couponApplicableUsers/Products — before answering). Confidence: 0.7
- Do not run `git stash` or other destructive git operations that would discard or modify working-tree changes without explicit permission. Confidence: 0.9
- When removing unused code (e.g., an unused tRPC procedure), prefers a complete cleanup: also remove internal helper methods used only by it, associated types, re-exports, orphaned hook/API files and their shared types, and even commented-out imports, leaving zero remaining references. Confidence: 0.9
- Before removing or deciding on code, likes to first verify where it is actually used across the codebase (asks questions like "where is X used"), rather than removing based on assumption. Confidence: 0.4
- Prefers light/pastel colors for randomized or accent UI elements (e.g., tabs, chips). Confidence: 0.7
- Prefers minimal, flat tab/navigation UI: active state shown with a thick underline, no pill/chip backgrounds or rounded fills; communicates desired visual styles by sharing reference images/screenshots. Confidence: 0.8
- Wants the agent to come up with a plan first before implementing code changes. Confidence: 0.9
- Appreciates being asked clarifying design questions with concrete options during planning. Confidence: 0.7
- Prefers embedding related data into existing cache files over creating or calling separate API endpoints. Confidence: 0.9
- Prefers using icons from Hicons (rather than custom/hand-authored SVGs or other icon libraries). Confidence: 0.9
- When a feature or page is repurposed, wants file names, route names, and code references renamed to match the new purpose (not just UI content/icons). Confidence: 0.8
- When replicating a UI pattern (e.g., home page tabs) onto a different page/context, adapt the copied colors to that page's own brand accent (e.g., the flash page's tabs use the flash pink `text-flash-600`/`bg-flash-500` instead of the home page's brand blue) while keeping the layout and styling identical. Confidence: 0.6
- Wants analysis findings and plans persisted in a markdown file before any implementation begins, with explicit confirmation that implementation is paused until instructed. Confidence: 0.8
- When changing cache or storage keys, wants both the read and write paths verified to use the same single source of truth (e.g., a shared `CACHE_STORAGE_KEYS` constant). Confidence: 0.8
- In React Native with react-native-paper's `Text` component (wrapped as `MyText`), prefers avoiding mixed string/expression children; use template literals to produce a single string child to prevent "Text strings must be rendered within a <Text> component" warnings. Confidence: 0.8
- When requesting test plans, expects exhaustive coverage across all relevant apps/screens/routes, including every functionality and every edge case. Confidence: 0.9
- Verifies that changed code introduces no NEW type errors beyond a project's pre-existing baseline (e.g., by temporarily stashing changes to compare typecheck output), and fixes even pre-existing type errors in files he heavily edits. Confidence: 0.8
- Prefers test case documentation to be structured with preconditions, steps, explicit "things to test" checklist, and expected results. Confidence: 0.7
- Prefers test plans written for a non-technical audience, using plain-language, click-by-click instructions ("tap this", "type that", "check there") rather than technical terms or API names. Confidence: 0.9
- When updating or creating a document, prefers the agent first compare it against existing source documents, identify missing items or gaps, and add them in the same established format. Confidence: 0.9
- Dislikes nested headers in mobile/drawer navigation; prefers a single, shared header (e.g., the drawer header) and relies on device back buttons or gestures for returning to previous screens. Confidence: 0.9
- After reviewing a presented plan, prefers brief, action-oriented approval (e.g., "nice. go ahead", "go ahead and implement") before implementation proceeds, expecting the agent to autonomously execute the already-presented plan. Confidence: 0.85
- Wants feature parity maintained between the web-ui and user-ui apps (port logic/data patterns, rebuild UI per platform) — e.g., when he asks for a link in the cart page "at the coupons section" of @apps/user-ui/components/cart-page.tsx, he means mirror user-ui's coupons section (card, header, icon) in web-ui and add the requested link there; and conversely asks for features added in one app to be added to the sibling app "too" (e.g., "add the coupon redirection on the user-ui cart-page too"), expecting the agent to locate the equivalent component/route and replicate it. Confidence: 0.98
- Wants the web-ui home page section/component order to match the reference user-ui home page exactly (e.g., "on the home page have the order same as that of @apps/user-ui/.../home/index.tsx"), including when deciding placement of sections like Explore, Stores, Slots, and All Products. Confidence: 0.7
- Wants brand/logo spots to use the single real brand logo asset (shared across apps, e.g., the Freshyo splash logo) displayed as an image, not a generic/decorative icon (e.g., a "meat piece" Meat/Beef icon) — web-ui should be on par with user-ui and show the same logo; applies to favicon, PWA icons, and every in-UI branding spot (sidebar, topbar, login, home banner). Confidence: 0.85
- Prefers dead-code audits to be documented in a markdown file. Confidence: 0.8
- Prefers detailed technical documentation of system architecture, data models, flows, and integrations in markdown format. Confidence: 0.8
- Wants edge cases explicitly enumerated when documenting or analyzing existing code/systems. Confidence: 0.8
- Values end-to-end analysis of features (architecture, data model, flows, integrations, and edge cases) when asked to explain how something works. Confidence: 0.7
- Prefers unifying parallel data structures into a single instance rather than maintaining separate ones (e.g., one cart for flash and regular items instead of separate flash/regular carts). Confidence: 0.9
- Prefers using sentinel values in existing fields (e.g., slotId = 0) to distinguish special-case items rather than creating separate fields or structures. Confidence: 0.9
- Prefers handling special-case logic locally in the relevant component/file rather than globally or via parallel flows. Confidence: 0.85
- Prefers lazy/virtualized list rendering (e.g., FlatList) for long lists, rather than rendering all items at once. Confidence: 0.8
- Wants true responsive web design for desktop, not just color/theme changes or mobile layouts stretched to desktop. Confidence: 0.95
- Specifies layout proportions in relative terms rather than fixed pixel sizes — e.g., the left sidebar/menu should be 20% of the viewport width at most ("the left menu should be 20% of width at max"), implemented as a viewport-relative track (20vw) rather than a hard-coded px column. Confidence: 0.7
- On the web-ui, wants the topbar (logo/search/cart) hidden on mobile screens and only rendered from the tablet breakpoint (`md`, 768px) upward, since mobile gets its own bottom navigation; when hiding it, the surrounding grid layout must be cleaned up so no empty reserved space remains. Confidence: 0.8
- The search bar must be independent of the topbar and always visible on every screen size; decoupling it from the topbar's tablet-only visibility — hiding the topbar must not hide search ("the search bar... should be independent of the top bar. I want it visible always"). When a page already has its own search UI (e.g., the search route's sticky header), the global always-visible search row should be suppressed there to avoid stacked duplicate bars. Confidence: 0.8
- Wants the search bar (and other persistent page-level UI like the topbar) to be sticky, pinning to the top of the viewport while the page scrolls ("I see it's not sticky. I want it sticky"); to make sticky actually work, the header group should live in a full-height flex column rather than a bounded grid row that scrolls away. Confidence: 0.9
- Does not want color/theme changes during redesigns — keep colors and theme consistent with the existing apps (e.g., @apps/user-ui): reuse the shared theme tokens (Untitled UI blue brand scale, flash pink accent, gray neutrals) rather than introducing new brand palettes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95
roducing new brand palettes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95
er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the agent to mirror that pattern exactly, including details like item counts and container styling. Confidence: 0.95
- Combo-only SKUs (`isComboOnly` on `product_skus`) must be hidden from all user-facing product surfaces — home page, offers page, and any other list where they could appear ("Don't display them. We're hiding them from home page too"). Confidence: 0.75
- Expects a filter/business rule already applied on one page to be applied consistently on every other page showing the same data, not just the page he happened to notice ("we need to hide them here too"). Confidence: 0.85
- Debugs by adding temporary console.log debug prints to inspect runtime data (e.g., `console.log({skusData})` to check a query result) and reports the observed values to the agent as ground truth (e.g., "the database is same. I've checked"). Confidence: 0.75
- When a bug reproduces only on a deployed API (e.g., devapi) but not against the local backend, expects the agent to investigate the environment difference — which API base URL the app actually points to, wrangler/D1 bindings, and the deployed bundle version — rather than assuming identical code paths. Confidence: 0.65
- Keeps operational runbooks / command documentation (e.g., `apps/backend/wrangler-commands.md` documenting the D1 export table-ordering trap) in repo markdown files and expects the agent to read them and apply the documented procedure when performing the related operation (e.g., fixing dump table order), treating the doc as the source of truth for the fix. Confidence: 0.65
- Prefers monetary amounts (totals, discounts, savings) displayed as whole numbers only — explicitly truncates decimals (e.g., `Math.trunc()`) rather than rounding, keeping internal calculations at full precision and truncating only at the render site ("Just truncate and show only the whole number"). Confidence: 0.7
- When displaying savings/benefit lines, hides the row entirely unless the amount exceeds a meaningful threshold (e.g., "show only if the savings is greater than rs 1") so the truncated whole-number display never shows a negligible ₹0/₹1 saving. Confidence: 0.55
- Prefers out-of-stock items pushed to the end of product list sections (e.g., home page tab sections) while preserving the existing/admin-curated order — a stable partition (in-stock first, out-of-stock last, relative order kept within each group), reusing the same out-of-stock detection rule used elsewhere on the page ("preserve the order but push the out of stock items to last"). Confidence: 0.7
- Wants product grid sections (e.g., Explore Products, All Available Products on the home page) to render at least 3 columns even on the smallest screens, scaling up on larger breakpoints — prefers the minimum column count on mobile to not be reduced to 2. Confidence: 0.7
- Tracks previously discussed/planned fixes and follows up to verify they were actually applied (e.g., "did we take care of the math.trunc"); expects the agent to check the current state of the code and apply any outstanding planned changes rather than assume they were completed. Confidence: 0.8
- Prevents contradictory/invalid states in admin forms by hiding the inapplicable control entirely — including its label/text row — rather than leaving it visible but disabled (e.g., the entire "Combo Only SKU" checkbox row is hidden when the SKU itself is a combo — has combo items — not just disabled). Confidence: 0.6
- Wants savings figures kept consistent across all order surfaces: a savings concept shown in the cart/checkout bill (market price − offered price) must also be reflected in the order confirmation summary ("you saved n on this order"), aggregating all savings sources (coupon discount, market-price savings, free delivery) rather than only the coupon/discount component. Confidence: 0.85
- Cares about the exact user-facing wording of labels and explicitly dictates renames (e.g., "Total Savings" → "Total Discount" on the cart page), expecting the change to be applied exactly as specified — including new labels dictated verbatim in the request (e.g., a link literally named "Add Coupons to account", a button that "should say Add Multiple", not paraphrased). Confidence: 0.8
- When a button/feature is broken on one page but works on a sibling page (e.g., "Edit Notes" in the order-list three-dot menu vs. the order detail page), expects it fixed to behave like the working page — including calling the proper API with the correct parameter types (numeric order id matching the backend's zod schema, not a stringified id) rather than a no-op or wrong call. Confidence: 0.7
- Reports UI bugs by pointing at the specific file and describing the intended action plus the visible symptom (e.g., "submit not happening", "I see [id]/index instead of product name in the top bar"), often with a hypothesis about the cause ("maybe we're not fulfilling conditions to enable"); expects the agent to trace the actual code path and find the root cause rather than just making the UI appear to work. Confidence: 0.65
- Expects form validation and submit-enable conditions to match the current UI mode: fields hidden by a mode toggle (e.g., the single coupon-code field when "reserved coupon" is selected) must not be required, and discount-type toggles should not pre-fill placeholder values (like 0) that fail the `> 0` validation — hidden/placeholder state must never block submission. Confidence: 0.55
- On mobile screens, prefers abbreviated button labels to conserve horizontal space — e.g., the add-to-cart button shows just the cart icon + "Add" on mobile and the full "Add to Cart" label from the `md` breakpoint up ("if the screen is mobile one just show cart symbol and Add instead of Add to cart"), implemented with responsive `md:hidden` / `hidden md:inline` spans. Confidence: 0.8
- Expects the UI to reflect state changes immediately after an action, without a manual page refresh — e.g., items added to the cart must show up in the cart/badge right away; reports staleness bugs as "added items are not visible unless page is refreshed. They are added but not shown in cart," distinguishing that data was persisted (localStorage) but the UI didn't update. Confidence: 0.7
- Wants the same UI component variant used consistently across every section/page in the app: when the user designates one section as having the "correct" version of a component, that exact section is the reference and its variant must be replicated everywhere else. Confirmed by an explicit correction: the Explore tabs section's mini floating cart icon (`miniView={true}`) was the correct one — "what was first present in tabs section, should've been replicated elsewhere" — i.e., replicated to All Products, search results, offers, and store detail, not the other way around. He expects the agent to follow the stated direction precisely and will correct a swapped interpretation. Confidence: 0.9
- When the user asks for "similar tabs" on a page (e.g., the home page's category tabs on the 1-hr flash page), they mean the tabs model should REPLACE the page's existing filter/navigation mechanism — e.g., the store selector sidebar — entirely, not be layered on top of it ("I meant, replace the store selector with tabs model"). The page should use a single, consistent navigation/filter model like the home page, not two stacked filter controls; expects the agent to remove the superseded component and its now-unused imports/state. Confidence: 0.85
- Dislikes transparent backgrounds on UI controls that overlay content — e.g., the quantity stepper floating over product images must have a solid background (white with a subtle shadow) so it reads clearly over any image, not a transparent one ("the background of the quantifier is transparent. Don't do that."). Confidence: 0.7
- Modal dialogs (e.g., the add-to-cart dialog) must always layer above persistent fixed UI — the floating cart bar and the bottom navigation — never behind them; states the rule explicitly: the bar "shouldn't have more z index than the dialog," on both mobile and desktop. On mobile, interactive dialog content (the Add/Update button) must also clear the bottom nav (higher z-index than the nav's z-50 plus mobile-only bottom padding) while desktop behavior stays unchanged ("Move it a little top in case of mobile view"). Confidence: 0.75
- In any cart surface, decrementing a quantity stepper down to 0 must remove the item from the cart entirely (make it disappear), never leave it persisted at quantity 0 — expected both on the cart page and in the cart slide-over opened from the floating cart bar, and the user will explicitly correct which surface he meant if the fix targets the wrong one ("I'm unable to click - to make it 0 and disappear" / "I clicked the cart bar to open cart view. There I'm not able to make '0' and remove"). Confidence: 0.7
- In Tailwind v4 apps, arbitrary-value classes (e.g., `z-[60]`) authored in external/shared packages (like `packages/web-components`) can be silently dropped by the content scanner even when sibling classes from the same file compile — so for critical layering/positioning, prefer built-in scale values or an inline `style={{ zIndex: ... }}` and verify the compiled output (CSS/JS bundle) actually contains it rather than trusting the class source. Confidence: 0.7
- In modal dialogs that contain a list plus a primary action (e.g., the add-to-cart dialog with delivery slots and an Add to Cart button), only the list region should scroll — the header and footer (quantity + action buttons) stay pinned and always visible, so reaching the primary action never requires scrolling ("only the slots should be scrollable... I need to scroll down to see the add to cart button"); implemented as a flex column with a fixed header, a `flex-1 min-h-0 overflow-y-auto` scrollable middle, and a `shrink-0` footer. Confidence: 0.75
- On narrow/small screens, prefers text to scale DOWN to avoid crowding — prices/amounts and general card text alike: e.g., cart item prices `text-sm` on mobile bumping to `text-base` at the `sm` breakpoint, product card prices `text-base` → `text-lg`, and tightened vertical gaps near the quantity row ("if the width is small, reduce the price size and also the gap below the quantity"). Explicitly generalized to all card text (name, price, unit/quantity) with the direct request "when the screen width is small, reduce the font size too" — implemented as smaller arbitrary sizes (e.g., `text-[13px]`, `text-[15px]`, `text-[11px]`) below the `sm` breakpoint returning to normal sizes at `sm` and up. Explicitly requested and then repeatedly reinforced ("I still see large blue text in price"). Confidence: 0.8
- When he reports a visual issue persisting ("I still see the same"), he is referring to the same visual pattern (e.g., "large blue text in price" = any `text-brand-600` price across cart pages, product cards) wherever it appears — expects the agent to grep the whole codebase for every occurrence of the matching styling and fix them all, not just the one surface initially identified. Confidence: 0.7
- When a spacing/visual complaint persists ("I still see the gap below the quantity"), the same issue may live in a different rendering mode of the component than the one already fixed — e.g., product cards in `miniView` where the quantity control overlays the image and the gap comes from the unit-line bottom margin plus the card's bottom padding, not the cart slide-over that was edited first. Expects the agent to re-inspect the actual rendered layout of each variant/mode and tighten spacing everywhere the pattern appears. Confidence: 0.6
- Prefers vertical tab/sidebar lists for store/category selection on ALL screen sizes — a vertical sidebar layout must not be swapped to a horizontal scrolling chip strip on mobile ("on the flash screen, the store tabs are horizontal, they should have been vertical"); instead keep the vertical list, stacked full-width above the content on small screens and as a sticky rail on desktop. Confidence: 0.7
- When adopting the tabs model to replace a store filter, the tabs must be driven by the same dimension as the replaced filter — one tab per store, labeled by the store name, with each tab showing only that store's items (per-tab scoped content), not category/product tags. Explicitly corrected after a misinterpretation ("the tab labels should be store names. In every tab we need to show the items of that store"). Confidence: 0.8
- When replicating a horizontal scrollable tab strip (store/category tabs) from user-ui to web-ui, expects identical interactive behavior, not just styling — the active tab must auto-scroll into view on selection so clicking a right-most tab brings it fully into view (matching user-ui's scroll-to-tab-position behavior, e.g., scroll to `offsetLeft - 16`), and the same auto-scroll must be applied consistently to every page using that tab strip pattern ("the tabs aren't behaving same as user-ui. They aren't auto scrolling when I try to click a right most tab"). Confidence: 0.8
- For compact product cards (price, strike-through market price, quantity), dictates a specific vertical stacking layout rather than a side-by-side row: show the price first, then the struck market price on the same line, and the quantity on a new line below ("first show the price, then the striked price, in new line show the quantity") — this supersedes earlier attempts to pin the quantity to the right of the same row. Confidence: 0.7
- For text that wraps next to a leading icon in a chip/label (e.g., the delivery-date chip with a truck icon), constrains multiline text to a maximum of 2 lines (`line-clamp-2`) and pins the icon to the top of the first line (`items-start` + `shrink-0` + top margin on the icon) so it never drops to a second line when the text wraps ("which takes at most 2 lines, with the truck on the first line"). Confidence: 0.6
- When a fixed N-line block (e.g., the delivery-date chip capped at 2 lines) must carry an icon on line 1 only, he rejects relying on natural text wrapping: if the text naturally fits on one line, the second line renders empty ("still the same. I see truck and space below it in next line empty"). Prefers a DETERMINISTIC structure that explicitly fills every line — split the content into two deliberate lines (e.g., date on line 1 next to the icon, time on its own line 2) so line 2 always has content, rather than wrap/clamp heuristics that can leave a gap. Confidence: 0.75
- Prefers minimal, chrome-free presentation for informational text like the delivery-date line: drop the background, border, and padding entirely and show just the text (and any leading icon) in the brand color at 70% opacity (`text-brand-700/70`), rather than a colored/bordered chip, after the layout was finalized ("remove the blue background and the padding. Just show the text in brand color but 70% opacity"). Confidence: 0.7
- When a pinned leading icon reserves its own column in a chip, a subsequent wrapped text line must NOT carry over that reserved gap — the second line should span the full inner width with proper spacing, not leave an "open gap" where the icon column sits on the first line ("in the second line I don't see truck but the gap is open. It should have space"). Confidence: 0.45
- When he wants a UI element/feature hidden for now (e.g., a delivery-date block), prefers the agent to comment the code out (wrapping in `{/* ... */}`) rather than delete it, so it can be easily restored later ("just hide the delivery date. just comment it out"). Confidence: 0.6
- Prefers the product-card quantity line to carry an explicit "Qty:" label prefix before the formatted value — e.g., "Qty: 12Kg" — rather than showing the bare formatted quantity (e.g., just `12Kg`). Confidence: 0.7
- Prefers a lighter, more compact look for product-card text: the product name rendered at `font-medium` (not `font-bold`) and the card's content padding tightened (e.g., `px-3 pt-2.5 pb-2.5` instead of `px-4 pt-3 pb-3`) — explicit instruction: "for the text of product name, reduce the weight and it's padding." He then continued tightening the horizontal padding by directly dictating the value ("make the padding px-1.5"), so expects the agent to apply exact spacing values he specifies. Confidence: 0.7
- Prefers secondary/informational product-card text (e.g., the quantity line) in the brand color at 70% opacity (`text-brand-700/70`) rather than muted gray — "show the quantity in the branch [brand] color 70% opacity" — the same `text-brand-700/70` treatment he chose for the delivery-date line, suggesting a recurring card-text color treatment for secondary info. When the line carries a label prefix (e.g., "Qty:"), only the VALUE part gets the brand color; the label stays muted gray and the value gets a touch more weight (`font-semibold`) to stand out — "only the value part. not the 'Qty'". Confidence: 0.7
- During product-card decluttering passes, wants promo/discount badges (e.g., the "n% OFF" label) hidden too — prefers a clean, uncluttered product card with no discount badge overlays ("hide the n% off label too"), the same treatment previously applied to hiding the delivery-date block. Confidence: 0.6
- Prefers bottom-sheet dialogs (the app's `BottomDialog`) for collecting simple input values (e.g., a count for bulk coupon generation) rather than separate screens or inline form sections — explicitly requested "it should open a bottom dialog and should take input of the desired count". Confidence: 0.4
- Expects newly generated/derived data to be merged into existing state structures rather than managed separately — e.g., bulk-generated coupon codes appended to the existing `couponCodes` array because "we already have coupon codes as array". Confidence: 0.5
- Expects back navigation in the mobile app to return to the screen he navigated from, not to an unrelated tab root — when a link from the cart page to the coupons page (which lives in another tab's stack) made pressing back land on the "Me" page instead of the cart, he reported it as a bug ("when I try to press back I don't come to the cart page again. I come to me page. why is that"); cross-tab navigation flows must preserve a way back to the origin screen. Confidence: 0.6
- When the same screen can be reached from multiple entry points, wants its UI to adapt based on the entry point — e.g., the coupons page opened from the cart page (via a `?from=cart` param) should hide the bottom tab bar while focused and restore it on leaving, while the same page opened from its own tab keeps the tab bar visible ("if coupons page is accessed from cart page, I want to hide the bottom nav bar"). Confidence: 0.7
- For bulk/sequential generation from a code pattern (e.g., ABC12 → ABC13...), expects numbering to continue from the HIGHEST existing value so regeneration never re-emits already-entered codes — after entering ABC12, the next batch must start at ABC13, not restart at 12 (the first matching code). Confidence: 0.6
- Dislikes UI that renders transient loading states as definitive business states — e.g., the home page showed every item as "out of stock" until slot data loaded, because the out-of-stock check treated "no slot yet" (data not loaded) as genuinely out of stock. Expects a "data loaded" guard so the UI never flashes a wrong definitive status (out of stock) before data arrives, while still applying real out-of-stock detection once loaded. Confidence: 0.7
- When deleting a record, prefers the existing soft-delete/invalidate path over hard-deleting rows: the supported delete already sets `isInvalidated: true` (keeping history/audit and avoiding broken FK joins), and a raw hard delete should only be considered when confirmed nothing references the row (no usage records), with related rows (couponApplicableUsers/Products) removed transactionally to avoid orphans. Confidence: 0.75
e changes. Confidence: 0.95
er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the agent to mirror that pattern exactly, including details like item counts and container styling. Confidence: 0.9
als) rather than introducing new brand palettes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95
roducing new brand palettes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95
er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the agent to mirror that pattern exactly, including details like item counts and container styling. Confidence: 0.9
tes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95
er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the agent to mirror that pattern exactly, including details like item counts and container styling. Confidence: 0.9
y, including details like item counts and container styling. Confidence: 0.9
tes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95
er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the agent to mirror that pattern exactly, including details like item counts and container styling. Confidence: 0.9

View file

@ -1,4 +0,0 @@
- trpc.user.tags.getTagsByStore — apps/backend/src/trpc/apis/user-apis/apis/tags.ts
- trpc.common.product.getAllProductsSummary — apps/backend/src/trpc/apis/common-apis/common.ts
- remove slots from products cache
- remove redundant product details like name, description etc from the slots api

File diff suppressed because one or more lines are too long

View file

@ -1,7 +1,6 @@
import { Drawer } from "expo-router/drawer"; import { Drawer } from "expo-router/drawer";
import { DrawerContentScrollView, DrawerItem } from "@react-navigation/drawer"; import { DrawerContentScrollView, DrawerItem } from "@react-navigation/drawer";
import { useRouter, Redirect } from "expo-router"; import { useRouter, Redirect } from "expo-router";
import { useNavigation, DrawerActions } from "@react-navigation/native";
import { import {
TouchableOpacity, TouchableOpacity,
DeviceEventEmitter, DeviceEventEmitter,
@ -13,6 +12,25 @@ import { REFRESH_EVENT } from "common-ui/src/lib/const-strs";
import { useStaffAuth } from "@/components/context/staff-auth-context"; import { useStaffAuth } from "@/components/context/staff-auth-context";
import { tw, MyText, theme } from "common-ui"; import { tw, MyText, theme } from "common-ui";
const SCREEN_TITLES: Record<string, string> = {
index: "Dashboard",
products: "Products",
"prices-overview": "Prices Overview",
"product-groupings": "Product Groupings",
"dashboard-banners": "Dashboard Banners",
slots: "Slots",
complaints: "Complaints",
"manage-orders": "Manage Orders",
coupons: "Coupons",
"vendor-snippets": "Vendor Snippets",
stores: "Stores",
"user-management": "User Management",
"send-notifications": "Send Notifications",
"product-tags": "Product Tags",
"rebalance-orders": "Rebalance Orders",
"customize-app": "Customize App",
};
function CustomDrawerContent() { function CustomDrawerContent() {
const router = useRouter(); const router = useRouter();
const { logout, staff } = useStaffAuth(); const { logout, staff } = useStaffAuth();
@ -32,105 +50,91 @@ function CustomDrawerContent() {
)} )}
<DrawerItem <DrawerItem
label="Dashboard" label="Dashboard"
onPress={() => router.push("/(drawer)/dashboard" as any)} onPress={() => router.dismissTo("/(drawer)/dashboard" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="dashboard" size={size} color={color} /> <MaterialIcons name="dashboard" size={size} color={color} />
)} )}
/> />
{/* <DrawerItem
label="Add Product"
onPress={() => router.push("/(drawer)/add-product" as any)}
icon={({ color, size }) => (
<MaterialIcons name="add" size={size} color={color} />
)}
/> */}
<DrawerItem <DrawerItem
label="Products" label="Products"
onPress={() => router.push("/(drawer)/products" as any)} onPress={() => router.push("/(drawer)/dashboard/products" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="inventory" size={size} color={color} /> <MaterialIcons name="inventory" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Prices Overview" label="Prices Overview"
onPress={() => router.push("/(drawer)/prices-overview" as any)} onPress={() => router.push("/(drawer)/dashboard/prices-overview" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="attach-money" size={size} color={color} /> <MaterialIcons name="attach-money" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Product Groupings" label="Product Groupings"
onPress={() => router.push("/(drawer)/product-groupings" as any)} onPress={() => router.push("/(drawer)/dashboard/product-groupings" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="group-work" size={size} color={color} /> <MaterialIcons name="group-work" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Dashboard Banners" label="Dashboard Banners"
onPress={() => router.push("/(drawer)/dashboard-banners" as any)} onPress={() => router.push("/(drawer)/dashboard/dashboard-banners" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="view-carousel" size={size} color={color} /> <MaterialIcons name="view-carousel" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Slots" label="Slots"
onPress={() => router.push("/(drawer)/slots" as any)} onPress={() => router.push("/(drawer)/dashboard/slots" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="schedule" size={size} color={color} /> <MaterialIcons name="schedule" size={size} color={color} />
)} )}
/> />
{/* <DrawerItem
label="Edit Product"
onPress={() => router.push("/(drawer)/edit-product" as any)}
icon={({ color, size }) => (
<MaterialIcons name="edit" size={size} color={color} />
)}
/> */}
<DrawerItem <DrawerItem
label="Complaints" label="Complaints"
onPress={() => router.push("/(drawer)/complaints" as any)} onPress={() => router.push("/(drawer)/dashboard/complaints" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="report-problem" size={size} color={color} /> <MaterialIcons name="report-problem" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Manage Orders" label="Manage Orders"
onPress={() => router.push("/(drawer)/manage-orders" as any)} onPress={() => router.push("/(drawer)/dashboard/manage-orders" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="shopping-bag" size={size} color={color} /> <MaterialIcons name="shopping-bag" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Coupons" label="Coupons"
onPress={() => router.push("coupons" as any)} onPress={() => router.push("/(drawer)/dashboard/coupons" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="local-offer" size={size} color={color} /> <MaterialIcons name="local-offer" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Vendor Snippets" label="Vendor Snippets"
onPress={() => router.push("vendor-snippets" as any)} onPress={() => router.push("/(drawer)/dashboard/vendor-snippets" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="code" size={size} color={color} /> <MaterialIcons name="code" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Stores" label="Stores"
onPress={() => router.push("/(drawer)/stores" as any)} onPress={() => router.push("/(drawer)/dashboard/stores" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="store" size={size} color={color} /> <MaterialIcons name="store" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="User Management" label="User Management"
onPress={() => router.push("/(drawer)/user-management" as any)} onPress={() => router.push("/(drawer)/dashboard/user-management" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="people" size={size} color={color} /> <MaterialIcons name="people" size={size} color={color} />
)} )}
/> />
<DrawerItem <DrawerItem
label="Send Notifications" label="Send Notifications"
onPress={() => router.push("/(drawer)/send-notifications" as any)} onPress={() => router.push("/(drawer)/dashboard/send-notifications" as any)}
icon={({ color, size }) => ( icon={({ color, size }) => (
<MaterialIcons name="campaign" size={size} color={color} /> <MaterialIcons name="campaign" size={size} color={color} />
)} )}
@ -147,6 +151,7 @@ function CustomDrawerContent() {
} }
export default function Layout() { export default function Layout() {
const router = useRouter();
const { isLoggedIn, isLoading } = useStaffAuth(); const { isLoggedIn, isLoading } = useStaffAuth();
if (isLoading) { if (isLoading) {
@ -163,9 +168,17 @@ export default function Layout() {
return ( return (
<Drawer <Drawer
backBehavior="history"
drawerContent={CustomDrawerContent} drawerContent={CustomDrawerContent}
screenOptions={({ navigation, route }) => ({ screenOptions={({ navigation }) => {
const state = navigation.getState();
const focusedRoute = state?.routes?.[state?.index ?? 0];
const dashboardStack = (focusedRoute as any)?.state;
const nestedIndex = dashboardStack?.index ?? 0;
const canGoBack = nestedIndex > 0;
const nestedRoute = dashboardStack?.routes?.[nestedIndex];
const title = SCREEN_TITLES[nestedRoute?.name ?? ""] ?? "Dashboard";
return {
swipeEnabled: false, swipeEnabled: false,
headerShown: true, headerShown: true,
headerStyle: { headerStyle: {
@ -175,10 +188,13 @@ export default function Layout() {
shadowOffset: { height: 0, width: 0 }, shadowOffset: { height: 0, width: 0 },
elevation: 0, elevation: 0,
}, },
headerTitle: title,
headerTitleAlign: "center", headerTitleAlign: "center",
headerLeft: () => ( headerLeft: () => (
<TouchableOpacity <TouchableOpacity
onPress={() => (navigation as any).openDrawer()} onPress={() =>
canGoBack ? router.back() : (navigation as any).openDrawer()
}
style={{ style={{
marginLeft: 15, marginLeft: 15,
width: 40, width: 40,
@ -189,7 +205,11 @@ export default function Layout() {
alignItems: "center", alignItems: "center",
}} }}
> >
<MaterialIcons name="menu" size={24} color="black" /> <MaterialIcons
name={canGoBack ? "arrow-back" : "menu"}
size={24}
color="black"
/>
</TouchableOpacity> </TouchableOpacity>
), ),
headerRight: () => ( headerRight: () => (
@ -210,27 +230,10 @@ export default function Layout() {
<MaterialIcons name="refresh" size={24} color="black" /> <MaterialIcons name="refresh" size={24} color="black" />
</TouchableOpacity> </TouchableOpacity>
), ),
})} };
}}
> >
<Drawer.Screen name="dashboard" options={{ title: "Dashboard" }} /> <Drawer.Screen name="dashboard" options={{ title: "Dashboard" }} />
<Drawer.Screen name="products" options={{ title: "Products" }} />
<Drawer.Screen name="prices-overview" options={{ title: "Prices Overview" }} />
<Drawer.Screen name="product-groupings" options={{ title: "Product Groupings" }} />
<Drawer.Screen
name="manage-orders"
options={{ title: "Manage Orders" }}
/>
<Drawer.Screen name="complaints" options={{ title: "Complaints" }} />
<Drawer.Screen name="coupons" options={{ title: "Coupons" }} />
<Drawer.Screen name="slots" options={{ title: "Slots" }} />
<Drawer.Screen name="vendor-snippets" options={{ title: "Vendor Snippets" }} />
<Drawer.Screen name="stores" options={{ title: "Stores" }} />
<Drawer.Screen name="product-tags" options={{ title: "Product Tags" }} />
<Drawer.Screen name="rebalance-orders" options={{ title: "Rebalance Orders" }} />
<Drawer.Screen name="user-management" options={{ title: "User Management" }} />
<Drawer.Screen name="send-notifications" options={{ title: "Send Notifications" }} />
</Drawer> </Drawer>
); );
} }

View file

@ -2,14 +2,41 @@ import { Stack } from "expo-router";
export default function Layout() { export default function Layout() {
return ( return (
<Stack> <Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" options={{ title: "Dashboard" }} />
<Stack.Screen name="complaints" options={{ title: "Complaints" }} />
<Stack.Screen name="coupons" options={{ title: "Coupons" }} />
<Stack.Screen name="customize-app" options={{ title: "Customize App" }} />
<Stack.Screen <Stack.Screen
name="index" name="dashboard-banners"
options={{ options={{ title: "Dashboard Banners" }}
title: "Dashboard",
headerShown: false,
}}
/> />
<Stack.Screen name="manage-orders" options={{ title: "Manage Orders" }} />
<Stack.Screen
name="prices-overview"
options={{ title: "Prices Overview" }}
/>
<Stack.Screen
name="product-groupings"
options={{ title: "Product Groupings" }}
/>
<Stack.Screen name="product-tags" options={{ title: "Product Tags" }} />
<Stack.Screen name="products" options={{ title: "Products" }} />
<Stack.Screen
name="rebalance-orders"
options={{ title: "Rebalance Orders" }}
/>
<Stack.Screen
name="send-notifications"
options={{ title: "Send Notifications" }}
/>
<Stack.Screen name="slots" options={{ title: "Slots" }} />
<Stack.Screen name="stores" options={{ title: "Stores" }} />
<Stack.Screen
name="user-management"
options={{ title: "User Management" }}
/>
<Stack.Screen name="vendor-snippets" options={{ title: "Vendor Snippets" }} />
</Stack> </Stack>
); );
} }

View file

@ -47,11 +47,11 @@ export default function Complaints() {
}, [hasNextPage, isFetchingNextPage, fetchNextPage]); }, [hasNextPage, isFetchingNextPage, fetchNextPage]);
const handleUserPress = useCallback((userId: number) => { const handleUserPress = useCallback((userId: number) => {
router.push(`/(drawer)/user-management/${userId}`); router.push(`/(drawer)/dashboard/user-management/${userId}`);
}, [router]); }, [router]);
const handleOrderPress = useCallback((orderId: number) => { const handleOrderPress = useCallback((orderId: number) => {
router.push(`/(drawer)/manage-orders/order-details/${orderId}`); router.push(`/(drawer)/dashboard/manage-orders/order-details/${orderId}`);
}, [router]); }, [router]);
const handleMarkResolved = (id: number) => { const handleMarkResolved = (id: number) => {
@ -117,6 +117,10 @@ export default function Complaints() {
contentContainerStyle={tw`px-4 py-4`} contentContainerStyle={tw`px-4 py-4`}
data={complaints} data={complaints}
keyExtractor={(item) => item.id.toString()} keyExtractor={(item) => item.id.toString()}
initialNumToRender={10}
maxToRenderPerBatch={10}
windowSize={10}
removeClippedSubviews
onEndReached={handleLoadMore} onEndReached={handleLoadMore}
onEndReachedThreshold={0.5} onEndReachedThreshold={0.5}
renderItem={({ item }) => ( renderItem={({ item }) => (
@ -146,6 +150,20 @@ export default function Complaints() {
{item.text} {item.text}
</MyText> </MyText>
{item.response && (
<View style={tw`mb-3 bg-blue-50 border border-blue-100 rounded-xl p-3`}>
<View style={tw`flex-row items-center mb-1`}>
<MaterialIcons name="reply" size={16} color="#2563EB" />
<MyText style={tw`ml-1 text-xs font-bold text-blue-700`}>
Admin Reply
</MyText>
</View>
<MyText style={tw`text-sm text-gray-700 leading-5`}>
{item.response}
</MyText>
</View>
)}
{item.images && item.images.length > 0 && ( {item.images && item.images.length > 0 && (
<View style={tw`mb-3`}> <View style={tw`mb-3`}>
<MyText style={tw`text-sm font-semibold text-gray-700 mb-2`}> <MyText style={tw`text-sm font-semibold text-gray-700 mb-2`}>

View file

@ -24,34 +24,37 @@ export default function CreateCoupon() {
} }
) )
const handleCreateCoupon = (values: any) => { const handleCreateCoupon = async (values: any) => {
console.log('Form values:', values); // Debug log const { isReservedCoupon, couponCodes, ...rest } = values;
const { isReservedCoupon, ...rest } = values;
// Transform targetUsers array to targetUser for backend compatibility // Transform targetUsers array to targetUser for backend compatibility
const payload = { const payload = {
...rest, ...rest,
targetUser: rest.targetUsers?.[0] || undefined, targetUser: rest.targetUsers?.[0] || undefined,
}; };
delete payload.targetUsers; delete payload.targetUsers;
console.log('Payload:', payload); // Debug log
// For flat discounts, send the discount value as maxValue too
if (payload.flatDiscount !== undefined) {
payload.maxValue = payload.flatDiscount;
}
const codes = (couponCodes || []).map((c: string) => c.trim()).filter(Boolean);
if (codes.length === 0) {
Alert.alert('Error', 'At least one coupon code is required');
return;
}
const mutation = isReservedCoupon ? createReservedCoupon : createCoupon; const mutation = isReservedCoupon ? createReservedCoupon : createCoupon;
const isLoading = isReservedCoupon ? createReservedCoupon.isPending : createCoupon.isPending; try {
await mutation.mutateAsync({ ...payload, couponCodes: codes });
if (isLoading) return; // Prevent double submission
mutation.mutate(payload, {
onSuccess: async () => {
await refetchCoupons() await refetchCoupons()
await refetchReservedCoupons() await refetchReservedCoupons()
Alert.alert('Success', `${isReservedCoupon ? 'Reserved coupon' : 'Coupon'} created successfully`, [ Alert.alert('Success', `${codes.length} coupon${codes.length > 1 ? 's' : ''} created successfully`, [
{ text: 'OK', onPress: () => router.back() } { text: 'OK', onPress: () => router.back() }
]); ]);
}, } catch (error: any) {
onError: (error: any) => { Alert.alert('Error', error.message || 'Failed to create coupons');
Alert.alert('Error', error.message || 'Failed to create coupon'); }
},
});
}; };
return ( return (

View file

@ -37,6 +37,11 @@ export default function EditCoupon() {
}; };
delete updates.targetUsers; delete updates.targetUsers;
// For flat discounts, send the discount value as maxValue too
if (updates.flatDiscount !== undefined) {
updates.maxValue = updates.flatDiscount;
}
updateCoupon.mutate({ id: couponId, updates }, { updateCoupon.mutate({ id: couponId, updates }, {
onSuccess: async () => { onSuccess: async () => {
await refetch() await refetch()
@ -74,7 +79,7 @@ export default function EditCoupon() {
// Transform coupon data for form (targetUser to targetUsers array) // Transform coupon data for form (targetUser to targetUsers array)
const initialValues: Partial<CreateCouponPayload & { isReservedCoupon?: boolean }> = { const initialValues: Partial<CreateCouponPayload & { isReservedCoupon?: boolean }> = {
couponCode: coupon.couponCode, couponCodes: coupon.couponCode ? [coupon.couponCode] : [''],
isUserBased: coupon.isUserBased, isUserBased: coupon.isUserBased,
isApplyForAll: coupon.isApplyForAll, isApplyForAll: coupon.isApplyForAll,
targetUsers: coupon.targetUser ? [coupon.targetUser.id] : [], targetUsers: coupon.targetUser ? [coupon.targetUser.id] : [],
@ -84,7 +89,7 @@ export default function EditCoupon() {
maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined, maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined,
validTill: coupon.validTill ? dayjs(coupon.validTill).format('YYYY-MM-DD') : undefined, validTill: coupon.validTill ? dayjs(coupon.validTill).format('YYYY-MM-DD') : undefined,
maxLimitForUser: coupon.maxLimitForUser || undefined, maxLimitForUser: coupon.maxLimitForUser || undefined,
productIds: coupon.productIds, skuIds: coupon.skuIds,
isReservedCoupon: false, // Normal coupons isReservedCoupon: false, // Normal coupons
}; };

View file

@ -90,7 +90,7 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
<View style={tw`flex-row mt-3 gap-2`}> <View style={tw`flex-row mt-3 gap-2`}>
<TouchableOpacity <TouchableOpacity
onPress={() => router.push(`/coupons/edit/${item.id}`)} onPress={() => router.push(`/(drawer)/dashboard/coupons/edit/${item.id}`)}
style={tw`bg-blue-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`} style={tw`bg-blue-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
> >
<MaterialCommunityIcons name="pencil" size={16} color="white" /> <MaterialCommunityIcons name="pencil" size={16} color="white" />
@ -497,7 +497,7 @@ export default function Coupons() {
)} )}
/> />
<MyTouchableOpacity <MyTouchableOpacity
onPress={() => router.push('/coupons/create')} onPress={() => router.push('/(drawer)/dashboard/coupons/create')}
activeOpacity={0.95} activeOpacity={0.95}
style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }} style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }}
> >

View file

@ -217,7 +217,7 @@ export default function ReservedCoupons() {
</View> </View>
<MyText style={tw`text-xl font-semibold text-gray-600 mb-2`}>No Reserved Coupons Yet</MyText> <MyText style={tw`text-xl font-semibold text-gray-600 mb-2`}>No Reserved Coupons Yet</MyText>
<MyText style={tw`text-gray-500 text-center mb-4`}>Create your first reserved coupon to start offering secret discounts</MyText> <MyText style={tw`text-gray-500 text-center mb-4`}>Create your first reserved coupon to start offering secret discounts</MyText>
<MyButton onPress={() => router.push('/coupons/create')} style={tw`bg-blue-500`}> <MyButton onPress={() => router.push('/(drawer)/dashboard/coupons/create')} style={tw`bg-blue-500`}>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MaterialCommunityIcons name="plus" size={16} color="white" /> <MaterialCommunityIcons name="plus" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Create Reserved Coupon</MyText> <MyText style={tw`text-white font-semibold ml-1`}>Create Reserved Coupon</MyText>
@ -230,7 +230,7 @@ export default function ReservedCoupons() {
{/* FAB for Add New Reserved Coupon */} {/* FAB for Add New Reserved Coupon */}
<MyTouchableOpacity <MyTouchableOpacity
onPress={() => router.push('/coupons/create')} onPress={() => router.push('/(drawer)/dashboard/coupons/create')}
activeOpacity={0.95} activeOpacity={0.95}
style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }} style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }}
> >

View file

@ -18,7 +18,7 @@ import {
MyTouchableOpacity, MyTouchableOpacity,
} from "common-ui"; } from "common-ui";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { trpc } from "../../../src/trpc-client"; import { trpc } from "../../../../src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons"; import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";

View file

@ -2,7 +2,7 @@ import React from 'react';
import { View, ScrollView, Alert } from 'react-native'; import { View, ScrollView, Alert } from 'react-native';
import { Formik } from 'formik'; import { Formik } from 'formik';
import { MyText, MyTextInput, MyTouchableOpacity, tw, AppContainer, Checkbox } from 'common-ui'; import { MyText, MyTextInput, MyTouchableOpacity, tw, AppContainer, Checkbox } from 'common-ui';
import { trpc } from '../../../src/trpc-client'; import { trpc } from '../../../../src/trpc-client';
import { useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
@ -71,7 +71,7 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
{CONST_LABELS[constantKey] || constantKey} {CONST_LABELS[constantKey] || constantKey}
</MyText> </MyText>
<MyTouchableOpacity <MyTouchableOpacity
onPress={() => router.push('/(drawer)/customize-app/popular-items')} onPress={() => router.push('/(drawer)/dashboard/customize-app/popular-items')}
style={tw`bg-blue-50 border-2 border-dashed border-blue-200 p-4 rounded-lg flex-row items-center justify-center`} style={tw`bg-blue-50 border-2 border-dashed border-blue-200 p-4 rounded-lg flex-row items-center justify-center`}
> >
<MaterialIcons name="edit" size={20} color="#3b82f6" style={tw`mr-2`} /> <MaterialIcons name="edit" size={20} color="#3b82f6" style={tw`mr-2`} />
@ -93,7 +93,7 @@ const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFi
{CONST_LABELS[constantKey] || constantKey} {CONST_LABELS[constantKey] || constantKey}
</MyText> </MyText>
<MyTouchableOpacity <MyTouchableOpacity
onPress={() => router.push('/(drawer)/customize-app/all-items-order')} onPress={() => router.push('/(drawer)/dashboard/customize-app/all-items-order')}
style={tw`bg-green-50 border-2 border-dashed border-green-200 p-4 rounded-lg flex-row items-center justify-center`} style={tw`bg-green-50 border-2 border-dashed border-green-200 p-4 rounded-lg flex-row items-center justify-center`}
> >
<MaterialIcons name="reorder" size={20} color="#16a34a" style={tw`mr-2`} /> <MaterialIcons name="reorder" size={20} color="#16a34a" style={tw`mr-2`} />

View file

@ -19,9 +19,9 @@ import {
BottomDropdown, BottomDropdown,
MyTouchableOpacity, MyTouchableOpacity,
} from "common-ui"; } from "common-ui";
import ProductsSelector from "../../../components/ProductsSelector"; import ProductsSelector from "../../../../components/ProductsSelector";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { trpc } from "../../../src/trpc-client"; import { trpc } from "../../../../src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons"; import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
@ -416,7 +416,7 @@ export default function CustomizePopularItems() {
multiple={true} multiple={true}
label="Select Products" label="Select Products"
placeholder="Choose products..." placeholder="Choose products..."
labelFormat={(product) => `${product.name} - ₹${product.price}`} labelFormat={(product) => `${product.productName} - ₹${product.price}`}
/> />
<View style={tw`flex-row gap-3 mt-6`}> <View style={tw`flex-row gap-3 mt-6`}>

View file

@ -15,7 +15,7 @@ export default function CreateBanner() {
name: '', name: '',
imageUrl: '', imageUrl: '',
description: '', description: '',
productIds: [], skuIds: [],
redirectUrl: '', redirectUrl: '',
// serialNum removed - assigned automatically by backend // serialNum removed - assigned automatically by backend
}; };
@ -38,7 +38,7 @@ export default function CreateBanner() {
name: values.name, name: values.name,
imageUrl, imageUrl,
description: values.description || undefined, description: values.description || undefined,
productIds: values.productIds.length > 0 ? values.productIds : [], skuIds: values.skuIds.length > 0 ? values.skuIds : [],
redirectUrl: values.redirectUrl || undefined, redirectUrl: values.redirectUrl || undefined,
}); });

View file

@ -12,7 +12,7 @@ interface Banner {
name: string; name: string;
imageUrl: string; imageUrl: string;
description?: string; description?: string;
productIds?: number[]; skuIds?: number[];
redirectUrl?: string; redirectUrl?: string;
serialNum: number; serialNum: number;
isActive: boolean; isActive: boolean;
@ -45,12 +45,12 @@ export default function EditBanner() {
if (bannerData) { if (bannerData) {
// Handle data format compatibility (productId -> productIds migration) // Handle data format compatibility (productId -> skuIds migration)
const processedBanner = { const processedBanner = {
...bannerData, ...bannerData,
productIds: Array.isArray(bannerData.productIds) skuIds: Array.isArray(bannerData.skuIds)
? bannerData.productIds ? bannerData.skuIds
: (bannerData.productIds ? [bannerData.productIds] : []) : (bannerData.skuIds ? [bannerData.skuIds] : [])
}; };
setBanner(processedBanner); setBanner(processedBanner);
@ -74,14 +74,14 @@ export default function EditBanner() {
name: banner.name, name: banner.name,
imageUrl: banner.imageUrl, imageUrl: banner.imageUrl,
description: banner.description || '', description: banner.description || '',
productIds: banner.productIds || [], skuIds: banner.skuIds || [],
redirectUrl: banner.redirectUrl || '', redirectUrl: banner.redirectUrl || '',
// serialNum removed - handled automatically by backend // serialNum removed - handled automatically by backend
} : { } : {
name: '', name: '',
imageUrl: '', imageUrl: '',
description: '', description: '',
productIds: [], skuIds: [],
redirectUrl: '', redirectUrl: '',
// serialNum removed - handled automatically by backend // serialNum removed - handled automatically by backend
}; };
@ -99,7 +99,7 @@ export default function EditBanner() {
name: values.name, name: values.name,
imageUrl: imageUrl || banner.imageUrl, imageUrl: imageUrl || banner.imageUrl,
description: values.description || undefined, description: values.description || undefined,
productIds: values.productIds.length > 0 ? values.productIds : [], skuIds: values.skuIds.length > 0 ? values.skuIds : [],
redirectUrl: values.redirectUrl || undefined, redirectUrl: values.redirectUrl || undefined,
}); });

View file

@ -1,7 +1,7 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { View, ScrollView, TouchableOpacity, Alert, Image, RefreshControl } from 'react-native'; import { View, ScrollView, TouchableOpacity, Alert, Image, RefreshControl } from 'react-native';
import { AppContainer, MyText, tw, MyTouchableOpacity } from 'common-ui'; import { AppContainer, MyText, tw, MyTouchableOpacity } from 'common-ui';
import { trpc } from '../../../src/trpc-client'; import { trpc } from '../../../../src/trpc-client';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
@ -10,7 +10,7 @@ interface Banner {
name: string; name: string;
imageUrl: string; imageUrl: string;
description: string | null; description: string | null;
productIds: number[] | null; skuIds: number[] | null;
redirectUrl: string | null; redirectUrl: string | null;
serialNum: number | null; serialNum: number | null;
isActive: boolean; isActive: boolean;
@ -180,7 +180,7 @@ export default function DashboardBanners() {
}; };
const handleEdit = (banner: Banner) => { const handleEdit = (banner: Banner) => {
router.push(`/dashboard-banners/edit/${banner.id}` as any); router.push(`/(drawer)/dashboard/dashboard-banners/edit/${banner.id}` as any);
}; };
const handleDelete = (id: number) => { const handleDelete = (id: number) => {
@ -207,7 +207,7 @@ export default function DashboardBanners() {
}; };
const handleCreate = () => { const handleCreate = () => {
router.push('/dashboard-banners/create' as any); router.push('/(drawer)/dashboard/dashboard-banners/create' as any);
}; };
if (isLoading) { if (isLoading) {

View file

@ -63,21 +63,21 @@ export default function Dashboard() {
const handleManageOrdersPress = () => { const handleManageOrdersPress = () => {
setNavigationTarget('/manage-orders/orders'); setNavigationTarget('/(drawer)/dashboard/manage-orders/orders');
router.push('/(drawer)/manage-orders'); router.push('/(drawer)/dashboard/manage-orders');
}; };
const handleDeliverySequencesPress = () => { const handleDeliverySequencesPress = () => {
setNavigationTarget('/manage-orders/delivery-sequences'); setNavigationTarget('/(drawer)/dashboard/manage-orders/delivery-sequences');
router.push('/(drawer)/manage-orders'); router.push('/(drawer)/dashboard/manage-orders');
}; };
const menuItems: MenuItem[] = [ const menuItems: MenuItem[] = [
{ {
title: 'Manage Orderss', title: 'Manage Orders',
icon: 'shopping-bag', icon: 'shopping-bag',
description: 'View and manage customer orders', description: 'View and manage customer orders',
route: '/(drawer)/manage-orders', route: '/(drawer)/dashboard/manage-orders',
category: 'orders', category: 'orders',
iconColor: '#10B981', iconColor: '#10B981',
iconBg: '#D1FAE5', iconBg: '#D1FAE5',
@ -87,7 +87,7 @@ export default function Dashboard() {
title: 'Delivery Sequences', title: 'Delivery Sequences',
icon: 'alt-route', icon: 'alt-route',
description: 'Plan and optimize delivery routes', description: 'Plan and optimize delivery routes',
route: '/manage-orders/delivery-sequences', route: '/(drawer)/dashboard/manage-orders/delivery-sequences',
category: 'orders', category: 'orders',
iconColor: '#8B5CF6', iconColor: '#8B5CF6',
iconBg: '#EDE9FE', iconBg: '#EDE9FE',
@ -97,7 +97,7 @@ export default function Dashboard() {
title: 'Delivery Slots', title: 'Delivery Slots',
icon: 'schedule', icon: 'schedule',
description: 'Configure delivery times', description: 'Configure delivery times',
route: '/(drawer)/slots' as any, route: '/(drawer)/dashboard/slots' as any,
category: 'quick', category: 'quick',
iconColor: '#06B6D4', iconColor: '#06B6D4',
iconBg: '#CFFAFE', iconBg: '#CFFAFE',
@ -107,7 +107,7 @@ export default function Dashboard() {
title: 'Add Product', title: 'Add Product',
icon: 'add-circle', icon: 'add-circle',
description: 'Create a new product listing', description: 'Create a new product listing',
route: '/products/add', route: '/(drawer)/dashboard/products/add',
category: 'quick', category: 'quick',
iconColor: theme.colors.brand500, iconColor: theme.colors.brand500,
iconBg: theme.colors.brand50, iconBg: theme.colors.brand50,
@ -116,7 +116,7 @@ export default function Dashboard() {
title: 'Complaints', title: 'Complaints',
icon: 'report-problem', icon: 'report-problem',
description: 'Handle customer complaints', description: 'Handle customer complaints',
route: '/(drawer)/complaints', route: '/(drawer)/dashboard/complaints',
category: 'quick', category: 'quick',
iconColor: '#F59E0B', iconColor: '#F59E0B',
iconBg: '#FEF3C7', iconBg: '#FEF3C7',
@ -126,7 +126,7 @@ export default function Dashboard() {
title: 'Products', title: 'Products',
icon: 'inventory-2', icon: 'inventory-2',
description: 'Manage product catalog', description: 'Manage product catalog',
route: '/(drawer)/products', route: '/(drawer)/dashboard/products',
category: 'products', category: 'products',
iconColor: '#6366F1', iconColor: '#6366F1',
iconBg: '#E0E7FF', iconBg: '#E0E7FF',
@ -135,7 +135,7 @@ export default function Dashboard() {
title: 'Prices Overview', title: 'Prices Overview',
icon: 'attach-money', icon: 'attach-money',
description: 'Update product pricing', description: 'Update product pricing',
route: '/(drawer)/prices-overview', route: '/(drawer)/dashboard/prices-overview',
category: 'products', category: 'products',
iconColor: '#059669', iconColor: '#059669',
iconBg: '#ECFDF5', iconBg: '#ECFDF5',
@ -144,7 +144,7 @@ export default function Dashboard() {
title: 'Product Tags', title: 'Product Tags',
icon: 'label', icon: 'label',
description: 'Organize with tags', description: 'Organize with tags',
route: '/(drawer)/product-tags', route: '/(drawer)/dashboard/product-tags',
category: 'products', category: 'products',
iconColor: '#EC4899', iconColor: '#EC4899',
iconBg: '#FCE7F3', iconBg: '#FCE7F3',
@ -153,7 +153,7 @@ export default function Dashboard() {
title: 'Product Groupings', title: 'Product Groupings',
icon: 'category', icon: 'category',
description: 'Group products together', description: 'Group products together',
route: '/(drawer)/product-groupings', route: '/(drawer)/dashboard/product-groupings',
category: 'products', category: 'products',
iconColor: '#8B5CF6', iconColor: '#8B5CF6',
iconBg: '#F3E8FF', iconBg: '#F3E8FF',
@ -162,7 +162,7 @@ export default function Dashboard() {
title: 'Stores', title: 'Stores',
icon: 'store', icon: 'store',
description: 'Manage store locations', description: 'Manage store locations',
route: '/(drawer)/stores', route: '/(drawer)/dashboard/stores',
category: 'settings', category: 'settings',
iconColor: '#14B8A6', iconColor: '#14B8A6',
iconBg: '#CCFBF1', iconBg: '#CCFBF1',
@ -171,7 +171,7 @@ export default function Dashboard() {
title: 'Coupons', title: 'Coupons',
icon: 'local-offer', icon: 'local-offer',
description: 'Create discount coupons', description: 'Create discount coupons',
route: '/(drawer)/coupons', route: '/(drawer)/dashboard/coupons',
category: 'marketing', category: 'marketing',
iconColor: '#F97316', iconColor: '#F97316',
iconBg: '#FFEDD5', iconBg: '#FFEDD5',
@ -180,7 +180,7 @@ export default function Dashboard() {
title: 'App Constants', title: 'App Constants',
icon: 'settings-applications', icon: 'settings-applications',
description: 'Customize app settings', description: 'Customize app settings',
route: '/(drawer)/customize-app', route: '/(drawer)/dashboard/customize-app',
category: 'settings', category: 'settings',
iconColor: '#7C3AED', iconColor: '#7C3AED',
iconBg: '#F3E8FF', iconBg: '#F3E8FF',
@ -189,7 +189,7 @@ export default function Dashboard() {
title: 'User Management', title: 'User Management',
icon: 'people', icon: 'people',
description: 'View and manage all users', description: 'View and manage all users',
route: '/(drawer)/user-management', route: '/(drawer)/dashboard/user-management',
category: 'users', category: 'users',
iconColor: '#0EA5E9', iconColor: '#0EA5E9',
iconBg: '#E0F2FE', iconBg: '#E0F2FE',
@ -198,7 +198,7 @@ export default function Dashboard() {
title: 'Send Notifications', title: 'Send Notifications',
icon: 'campaign', icon: 'campaign',
description: 'Send push notifications to users', description: 'Send push notifications to users',
route: '/(drawer)/send-notifications', route: '/(drawer)/dashboard/send-notifications',
category: 'users', category: 'users',
iconColor: '#8B5CF6', iconColor: '#8B5CF6',
iconBg: '#F3E8FF', iconBg: '#F3E8FF',

View file

@ -302,7 +302,7 @@ export default function DeliverySequences() {
// Auto-select first slot if no slotId provided // Auto-select first slot if no slotId provided
useEffect(() => { useEffect(() => {
if (!slotId && slotsData?.slots && slotsData.slots.length > 0) { if (!slotId && slotsData?.slots && slotsData.slots.length > 0) {
router.replace(`/manage-orders/delivery-sequences?slotId=${slotsData.slots[0].id}`); router.replace(`/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=${slotsData.slots[0].id}`);
} }
}, [slotId, slotsData, router]); }, [slotId, slotsData, router]);
@ -505,7 +505,7 @@ export default function DeliverySequences() {
value={selectedSlotId || ""} value={selectedSlotId || ""}
onValueChange={(val) => { onValueChange={(val) => {
if (val) { if (val) {
router.replace(`/manage-orders/delivery-sequences?slotId=${val}`); router.replace(`/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=${val}`);
} }
}} }}
placeholder="Select slot" placeholder="Select slot"
@ -726,7 +726,7 @@ export default function DeliverySequences() {
}} }}
onViewDetails={() => { onViewDetails={() => {
if (selectedOrder) { if (selectedOrder) {
router.push(`/manage-orders/order-details/${selectedOrder.id}`); router.push(`/(drawer)/dashboard/manage-orders/order-details/${selectedOrder.id}`);
} }
setShowOrderMenu(false); setShowOrderMenu(false);
}} }}

View file

@ -46,7 +46,7 @@ export default function ManageOrders() {
Alert.alert('Flash Deliveries', 'Flash deliveries do not have delivery sequences. Use the Orders menu to manage flash deliveries.'); Alert.alert('Flash Deliveries', 'Flash deliveries do not have delivery sequences. Use the Orders menu to manage flash deliveries.');
return; return;
} }
router.push(`/manage-orders/delivery-sequences?slotId=${selectedSlotId}`); router.push(`/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=${selectedSlotId}`);
}, },
}, },
{ {
@ -55,9 +55,9 @@ export default function ManageOrders() {
color: 'bg-cyan-500', color: 'bg-cyan-500',
onPress: () => { onPress: () => {
if (selectedSlotId === 'flash') { if (selectedSlotId === 'flash') {
router.push('/manage-orders/orders?filter=flash'); router.push('/(drawer)/dashboard/manage-orders/orders?filter=flash');
} else { } else {
router.push('/manage-orders/orders'); router.push('/(drawer)/dashboard/manage-orders/orders');
} }
}, },
}, },

View file

@ -378,7 +378,7 @@ export default function OrderDetails() {
{/* Customer Details */} {/* Customer Details */}
<TouchableOpacity <TouchableOpacity
onPress={() => order.userId && router.push(`/(drawer)/user-management/${order.userId}`)} onPress={() => order.userId && router.push(`/(drawer)/dashboard/user-management/${order.userId}`)}
activeOpacity={0.7} activeOpacity={0.7}
style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`} style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}
> >
@ -463,7 +463,7 @@ export default function OrderDetails() {
{item.name} {item.name}
</MyText> </MyText>
<MyText style={tw`text-xs text-gray-500`}> <MyText style={tw`text-xs text-gray-500`}>
{Number(item.quantity) * item.productSize} {item.unit} × ₹{item.price} {Number(item.quantity)} x {item.unit} × ₹{item.price}
</MyText> </MyText>
<View style={tw`flex-row items-center mt-2 gap-3`}> <View style={tw`flex-row items-center mt-2 gap-3`}>
<TouchableOpacity <TouchableOpacity
@ -784,7 +784,7 @@ export default function OrderDetails() {
</TouchableOpacity> </TouchableOpacity>
)} )}
<TouchableOpacity <TouchableOpacity
onPress={() => router.push("/(drawer)/manage-orders")} onPress={() => router.push("/(drawer)/dashboard/manage-orders")}
style={tw`bg-gray-900 rounded-xl py-4 items-center shadow-lg`} style={tw`bg-gray-900 rounded-xl py-4 items-center shadow-lg`}
> >
<MyText style={tw`text-white font-bold text-base`}> <MyText style={tw`text-white font-bold text-base`}>

View file

@ -105,12 +105,12 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
const updateItemPackagingMutation = trpc.admin.order.updateOrderItemPackaging.useMutation(); const updateItemPackagingMutation = trpc.admin.order.updateOrderItemPackaging.useMutation();
const handleOrderPress = () => { const handleOrderPress = () => {
router.push(`/manage-orders/order-details/${order.orderId}` as any); router.push(`/(drawer)/dashboard/manage-orders/order-details/${order.orderId}` as any);
}; };
const handleMenuOption = () => { const handleMenuOption = () => {
setMenuOpen(false); setMenuOpen(false);
router.push(`/manage-orders/order-details/${order.orderId}` as any); router.push(`/(drawer)/dashboard/manage-orders/order-details/${order.orderId}` as any);
}; };
const handleMarkPackaged = (isPackaged: boolean) => { const handleMarkPackaged = (isPackaged: boolean) => {
@ -284,17 +284,17 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
> >
<MaterialIcons name="shopping-cart" size={16} color="#3B82F6" /> <MaterialIcons name="shopping-cart" size={16} color="#3B82F6" />
<MyText style={tw`text-sm font-medium text-blue-700 ml-2`}> <MyText style={tw`text-sm font-medium text-blue-700 ml-2`}>
{order.items.length} {order.items.length === 1 ? 'item' : 'items'} {`${order.items.length} ${order.items.length === 1 ? 'item' : 'items'}`}
</MyText> </MyText>
{order.isFlashDelivery && ( {order.isFlashDelivery && (
<View style={tw`ml-2 bg-amber-100 px-1.5 py-0.5 rounded-full`}> <View style={tw`ml-2 bg-amber-100 px-1.5 py-0.5 rounded-full`}>
<MyText style={tw`text-xs font-bold text-amber-700`}>⚡</MyText> <MaterialIcons name="bolt" size={12} color="#D97706" />
</View> </View>
)} )}
</TouchableOpacity> </TouchableOpacity>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MyText style={tw`text-base font-semibold text-gray-900 mr-2`}>Total:</MyText> <MyText style={tw`text-base font-semibold text-gray-900 mr-2`}>Total:</MyText>
<MyText style={tw`text-lg font-bold ${order.isFlashDelivery ? 'text-amber-700' : 'text-gray-900'}`}>₹{order.totalAmount}</MyText> <MyText style={tw`text-lg font-bold ${order.isFlashDelivery ? 'text-amber-700' : 'text-gray-900'}`}>{`₹${order.totalAmount}`}</MyText>
</View> </View>
</View> </View>
</View> </View>
@ -315,7 +315,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
)} )}
{order.discountAmount && ( {order.discountAmount && (
<MyText style={tw`text-sm font-bold text-pink-800`}> <MyText style={tw`text-sm font-bold text-pink-800`}>
Discount: ₹{order.discountAmount} {`Discount: ₹${order.discountAmount}`}
</MyText> </MyText>
)} )}
</View> </View>
@ -353,7 +353,7 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
<View style={tw`pt-3 border-t border-gray-100`}> <View style={tw`pt-3 border-t border-gray-100`}>
<View style={tw`flex-row justify-between items-center`}> <View style={tw`flex-row justify-between items-center`}>
<MyText style={tw`text-sm text-gray-500`}>Delivery Charge</MyText> <MyText style={tw`text-sm text-gray-500`}>Delivery Charge</MyText>
<MyText style={tw`text-sm text-gray-900`}>₹{order.deliveryCharge}</MyText> <MyText style={tw`text-sm text-gray-900`}>{`₹${order.deliveryCharge}`}</MyText>
</View> </View>
</View> </View>
)} )}
@ -407,13 +407,13 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
)} )}
</View> </View>
<MyText style={tw`text-sm text-gray-600 mb-6`}> <MyText style={tw`text-sm text-gray-600 mb-6`}>
Total: ₹{order.totalAmount} {`Total: ₹${order.totalAmount}`}
</MyText> </MyText>
{order.items.map((item, idx) => ( {order.items.map((item, idx) => (
<View key={idx} style={tw`py-2 border-b border-gray-50 last:border-0`}> <View key={idx} style={tw`py-2 border-b border-gray-50 last:border-0`}>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<View style={tw`bg-gray-100 px-2 py-1 rounded items-center justify-center mr-2`}> <View style={tw`bg-gray-100 px-2 py-1 rounded items-center justify-center mr-2`}>
<MyText style={tw`text-xs font-bold text-gray-600`}>{item.quantity * item.productSize } {item.unit}</MyText> <MyText style={tw`text-xs font-bold text-gray-600`}>{`${item.quantity} x ${item.unit}`}</MyText>
</View> </View>
<MyText style={tw`text-sm text-gray-800 flex-1`} numberOfLines={1} ellipsizeMode="tail"> <MyText style={tw`text-sm text-gray-800 flex-1`} numberOfLines={1} ellipsizeMode="tail">
{item.name.length > 30 ? `${item.name.substring(0, 30)}...` : item.name} {item.name.length > 30 ? `${item.name.substring(0, 30)}...` : item.name}

View file

@ -21,31 +21,32 @@ import { trpc } from "@/src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons"; import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { Entypo } from "@expo/vector-icons"; import { Entypo } from "@expo/vector-icons";
interface ProductItemProps { interface SkuItemProps {
item: any; sku: any;
hasChanges: (productId: number) => boolean; productName: string;
hasChanges: (skuId: number) => boolean;
pendingChanges: Record<string, any>; pendingChanges: Record<string, any>;
setPendingChanges: React.Dispatch<React.SetStateAction<Record<string, any>>>; setPendingChanges: React.Dispatch<React.SetStateAction<Record<string, any>>>;
openEditDialog: (product: any) => void; openEditDialog: (sku: any, productName: string) => void;
} }
const ProductItemComponent: React.FC<ProductItemProps> = ({ const SkuItemComponent: React.FC<SkuItemProps> = ({
item: product, sku,
productName,
hasChanges, hasChanges,
pendingChanges, pendingChanges,
setPendingChanges, setPendingChanges,
openEditDialog, openEditDialog,
}) => { }) => {
const changed = hasChanges(product.id); const changed = hasChanges(sku.id);
const change = pendingChanges[product.id] || {}; const change = pendingChanges[sku.id] || {};
const displayPrice = change.price !== undefined ? change.price : product.price; const displayPrice = change.price !== undefined ? change.price : sku.price;
const displayMarketPrice = change.marketPrice !== undefined ? change.marketPrice : product.marketPrice; const displayMarketPrice = change.marketPrice !== undefined ? change.marketPrice : sku.marketPrice;
const displayFlashPrice = change.flashPrice !== undefined ? change.flashPrice : product.flashPrice; const displayFlashPrice = change.flashPrice !== undefined ? change.flashPrice : sku.flashPrice;
const displayProductQuantity = change.productQuantity !== undefined ? change.productQuantity : product.productQuantity; const displayUnit = (sku.features || []).map((f: any) => f.featureValue).join(' ') || '—';
return ( return (
<View style={tw`bg-white p-4 mb-3 rounded-xl border border-gray-200 shadow-sm`}> <View style={tw`bg-white p-4 mb-3 rounded-xl border border-gray-200 shadow-sm`}>
{/* Change indicator */}
<View style={tw`absolute top-2 right-2`}> <View style={tw`absolute top-2 right-2`}>
<View <View
style={[ style={[
@ -57,31 +58,33 @@ const ProductItemComponent: React.FC<ProductItemProps> = ({
</View> </View>
</View> </View>
{/* First row: Image and Name */}
<View style={tw`flex-row items-center mb-2`}> <View style={tw`flex-row items-center mb-2`}>
{/* Product image */}
<Image <Image
source={{ source={{
uri: product.images?.[0] || "https://via.placeholder.com/32x32?text=No+Image" uri: sku.images?.[0] || "https://via.placeholder.com/32x32?text=No+Image"
}} }}
style={tw`w-10 h-10 rounded-lg mr-3`} style={tw`w-10 h-10 rounded-lg mr-3`}
resizeMode="cover" resizeMode="cover"
/> />
{/* Product name and Flash Checkbox */}
<View style={tw`flex-1 flex-row items-center`}> <View style={tw`flex-1 flex-row items-center`}>
<View style={tw`flex-1`}>
<MyText style={tw`text-base font-medium text-gray-800`} numberOfLines={1}> <MyText style={tw`text-base font-medium text-gray-800`} numberOfLines={1}>
{product.name.length > 25 ? product.name.substring(0, 25) + '...' : product.name} {productName.length > 20 ? productName.substring(0, 20) + '...' : productName}
</MyText> </MyText>
<MyText style={tw`text-xs text-gray-500`} numberOfLines={1}>
{sku.displayName || sku.name || ''}
</MyText>
</View>
<View style={tw`flex-row items-center ml-2`}> <View style={tw`flex-row items-center ml-2`}>
<Checkbox <Checkbox
checked={change.isFlashAvailable ?? product.isFlashAvailable ?? false} checked={change.isFlashAvailable ?? sku.isFlashAvailable ?? false}
onPress={() => { onPress={() => {
const currentValue = change.isFlashAvailable ?? product.isFlashAvailable ?? false; const currentValue = change.isFlashAvailable ?? sku.isFlashAvailable ?? false;
setPendingChanges(prev => ({ setPendingChanges(prev => ({
...prev, ...prev,
[product.id]: { [sku.id]: {
...change, ...prev[sku.id],
isFlashAvailable: !currentValue, isFlashAvailable: !currentValue,
}, },
})); }));
@ -93,47 +96,42 @@ const ProductItemComponent: React.FC<ProductItemProps> = ({
</View> </View>
</View> </View>
{/* Prices and Product Size Row */}
<View style={tw`flex-row items-center justify-between`}> <View style={tw`flex-row items-center justify-between`}>
{/* Our Price */}
<View style={tw`items-center`}> <View style={tw`items-center`}>
<MyText style={tw`text-xs text-gray-500 mb-1`}>Our Price</MyText> <MyText style={tw`text-xs text-gray-500 mb-1`}>Our Price</MyText>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MyText style={tw`text-sm font-bold text-green-600`}>₹{displayPrice}</MyText> <MyText style={tw`text-sm font-bold text-green-600`}>₹{displayPrice}</MyText>
<TouchableOpacity onPress={() => openEditDialog(product)} style={tw`ml-1`}> <TouchableOpacity onPress={() => openEditDialog(sku, productName)} style={tw`ml-1`}>
<MaterialIcons name="edit" size={14} color="#6b7280" /> <MaterialIcons name="edit" size={14} color="#6b7280" />
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>
{/* Market Price */}
<View style={tw`items-center`}> <View style={tw`items-center`}>
<MyText style={tw`text-xs text-gray-500 mb-1`}>Market Price</MyText> <MyText style={tw`text-xs text-gray-500 mb-1`}>Market Price</MyText>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MyText style={tw`text-sm text-gray-600`}>{displayMarketPrice ? `₹${displayMarketPrice}` : "N/A"}</MyText> <MyText style={tw`text-sm text-gray-600`}>{displayMarketPrice ? `₹${displayMarketPrice}` : "N/A"}</MyText>
<TouchableOpacity onPress={() => openEditDialog(product)} style={tw`ml-1`}> <TouchableOpacity onPress={() => openEditDialog(sku, productName)} style={tw`ml-1`}>
<MaterialIcons name="edit" size={14} color="#6b7280" /> <MaterialIcons name="edit" size={14} color="#6b7280" />
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>
{/* Flash Price */}
<View style={tw`items-center`}> <View style={tw`items-center`}>
<MyText style={tw`text-xs text-gray-500 mb-1`}>Flash Price</MyText> <MyText style={tw`text-xs text-gray-500 mb-1`}>Flash Price</MyText>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MyText style={tw`text-sm text-orange-600`}>{displayFlashPrice ? `₹${displayFlashPrice}` : "N/A"}</MyText> <MyText style={tw`text-sm text-orange-600`}>{displayFlashPrice ? `₹${displayFlashPrice}` : "N/A"}</MyText>
<TouchableOpacity onPress={() => openEditDialog(product)} style={tw`ml-1`}> <TouchableOpacity onPress={() => openEditDialog(sku, productName)} style={tw`ml-1`}>
<MaterialIcons name="edit" size={14} color="#6b7280" /> <MaterialIcons name="edit" size={14} color="#6b7280" />
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>
{/* Product Size */}
<View style={tw`items-center`}> <View style={tw`items-center`}>
<MyText style={tw`text-xs text-gray-500 mb-1`}>Size</MyText> <MyText style={tw`text-xs text-gray-500 mb-1`}>Size</MyText>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MyText style={tw`text-sm text-blue-600`}>{displayProductQuantity ? `${displayProductQuantity}${product.unit.shortNotation || ''}` : "N/A"}</MyText> <MyText style={tw`text-sm text-blue-600`}>{displayUnit}</MyText>
<TouchableOpacity onPress={() => openEditDialog(product)} style={tw`ml-1`}> <TouchableOpacity onPress={() => openEditDialog(sku, productName)} style={tw`ml-1`}>
<MaterialIcons name="edit" size={14} color="#6b7280" /> <MaterialIcons name="edit" size={14} color="#6b7280" />
</TouchableOpacity> </TouchableOpacity>
</View> </View>
@ -147,17 +145,16 @@ interface PendingChange {
price?: number; price?: number;
marketPrice?: number | null; marketPrice?: number | null;
flashPrice?: number | null; flashPrice?: number | null;
productQuantity?: number | null;
isFlashAvailable?: boolean; isFlashAvailable?: boolean;
} }
interface EditDialogState { interface EditDialogState {
open: boolean; open: boolean;
product: any; sku: any;
productName: string;
tempPrice: string; tempPrice: string;
tempMarketPrice: string; tempMarketPrice: string;
tempFlashPrice: string; tempFlashPrice: string;
tempProductQuantity: string;
} }
export default function PricesOverview() { export default function PricesOverview() {
@ -166,11 +163,11 @@ export default function PricesOverview() {
const [pendingChanges, setPendingChanges] = useState<Record<number, PendingChange>>({}); const [pendingChanges, setPendingChanges] = useState<Record<number, PendingChange>>({});
const [editDialog, setEditDialog] = useState<EditDialogState>({ const [editDialog, setEditDialog] = useState<EditDialogState>({
open: false, open: false,
product: null, sku: null,
productName: "",
tempPrice: "", tempPrice: "",
tempMarketPrice: "", tempMarketPrice: "",
tempFlashPrice: "", tempFlashPrice: "",
tempProductQuantity: "",
}); });
const [showMenu, setShowMenu] = useState(false); const [showMenu, setShowMenu] = useState(false);
@ -184,13 +181,11 @@ export default function PricesOverview() {
const stores = storesData?.stores || []; const stores = storesData?.stores || [];
const allProducts = productsData?.products || []; const allProducts = productsData?.products || [];
// Sort stores alphabetically
const sortedStores = useMemo(() => const sortedStores = useMemo(() =>
[...stores].sort((a, b) => a.name.localeCompare(b.name)), [...stores].sort((a, b) => a.name.localeCompare(b.name)),
[stores] [stores]
); );
// Store options for dropdown
const storeOptions = useMemo(() => const storeOptions = useMemo(() =>
sortedStores.map(store => ({ sortedStores.map(store => ({
label: store.name, label: store.name,
@ -199,43 +194,49 @@ export default function PricesOverview() {
[sortedStores] [sortedStores]
); );
// Initialize selectedStores to all if not set
useEffect(() => { useEffect(() => {
if (stores.length > 0 && selectedStores.length === 0) { if (stores.length > 0 && selectedStores.length === 0) {
setSelectedStores(stores.map(s => s.id.toString())); setSelectedStores(stores.map(s => s.id.toString()));
} }
}, [stores, selectedStores]); }, [stores, selectedStores]);
// Filter products by selected stores const allSkus = useMemo(() => {
const filteredProducts = useMemo(() => { const skus: any[] = [];
if (selectedStores.length === 0) return allProducts; for (const product of allProducts) {
return allProducts.filter(product => if (product.skus && product.skus.length > 0) {
product.storeId && selectedStores.includes(product.storeId.toString()) for (const sku of product.skus) {
skus.push({ ...sku, _productName: product.name, _storeId: product.storeId });
}
}
}
return skus;
}, [allProducts]);
const filteredSkus = useMemo(() => {
if (selectedStores.length === 0) return allSkus;
return allSkus.filter(sku =>
sku._storeId && selectedStores.includes(sku._storeId.toString())
); );
}, [allProducts, selectedStores]); }, [allSkus, selectedStores]);
// Check if a product has changes const hasChanges = (skuId: number) => !!pendingChanges[skuId];
const hasChanges = (productId: number) => !!pendingChanges[productId];
// Open edit dialog const openEditDialog = (sku: any, productName: string) => {
const openEditDialog = (product: any) => { const change = pendingChanges[sku.id] || {};
const change = pendingChanges[product.id] || {};
setEditDialog({ setEditDialog({
open: true, open: true,
product, sku,
tempPrice: (change.price ?? product.price)?.toString() || "", productName,
tempMarketPrice: (change.marketPrice ?? product.marketPrice)?.toString() || "", tempPrice: (change.price ?? sku.price)?.toString() || "",
tempFlashPrice: (change.flashPrice ?? product.flashPrice)?.toString() || "", tempMarketPrice: (change.marketPrice ?? sku.marketPrice)?.toString() || "",
tempProductQuantity: (change.productQuantity ?? product.productQuantity)?.toString() || "", tempFlashPrice: (change.flashPrice ?? sku.flashPrice)?.toString() || "",
}); });
}; };
// Save edit dialog
const saveEditDialog = () => { const saveEditDialog = () => {
const price = parseFloat(editDialog.tempPrice); const price = parseFloat(editDialog.tempPrice);
const marketPrice = editDialog.tempMarketPrice ? parseFloat(editDialog.tempMarketPrice) : null; const marketPrice = editDialog.tempMarketPrice ? parseFloat(editDialog.tempMarketPrice) : null;
const flashPrice = editDialog.tempFlashPrice ? parseFloat(editDialog.tempFlashPrice) : null; const flashPrice = editDialog.tempFlashPrice ? parseFloat(editDialog.tempFlashPrice) : null;
const productQuantity = editDialog.tempProductQuantity ? parseFloat(editDialog.tempProductQuantity) : null;
if (isNaN(price) || price <= 0) { if (isNaN(price) || price <= 0) {
Alert.alert("Error", "Please enter a valid price"); Alert.alert("Error", "Please enter a valid price");
@ -252,32 +253,24 @@ export default function PricesOverview() {
return; return;
} }
if (editDialog.tempProductQuantity && (isNaN(productQuantity!) || productQuantity! <= 0)) {
Alert.alert("Error", "Please enter a valid product size");
return;
}
setPendingChanges(prev => ({ setPendingChanges(prev => ({
...prev, ...prev,
[editDialog.product.id]: { [editDialog.sku.id]: {
price: price !== editDialog.product.price ? price : undefined, price: price !== parseFloat(editDialog.sku.price) ? price : undefined,
marketPrice: marketPrice !== editDialog.product.marketPrice ? marketPrice : undefined, marketPrice: marketPrice !== parseFloat(editDialog.sku.marketPrice || '0') ? marketPrice : undefined,
flashPrice: flashPrice !== editDialog.product.flashPrice ? flashPrice : undefined, flashPrice: flashPrice !== parseFloat(editDialog.sku.flashPrice || '0') ? flashPrice : undefined,
productQuantity: productQuantity !== editDialog.product.productQuantity ? productQuantity : undefined,
}, },
})); }));
setEditDialog({ open: false, product: null, tempPrice: "", tempMarketPrice: "", tempFlashPrice: "", tempProductQuantity: "" });
}; };
// Handle save all changes
const handleSave = () => { const handleSave = () => {
const updates = Object.entries(pendingChanges).map(([productId, change]) => { const updates = Object.entries(pendingChanges).map(([skuId, change]) => {
const update: any = { productId: parseInt(productId) }; const sku = allSkus.find(s => s.id === parseInt(skuId));
const update: any = { productId: sku?.id };
if (change.price !== undefined) update.price = change.price; if (change.price !== undefined) update.price = change.price;
if (change.marketPrice !== undefined) update.marketPrice = change.marketPrice; if (change.marketPrice !== undefined) update.marketPrice = change.marketPrice;
if (change.flashPrice !== undefined) update.flashPrice = change.flashPrice; if (change.flashPrice !== undefined) update.flashPrice = change.flashPrice;
if (change.productQuantity !== undefined) update.productQuantity = change.productQuantity;
if (change.isFlashAvailable !== undefined) update.isFlashAvailable = change.isFlashAvailable; if (change.isFlashAvailable !== undefined) update.isFlashAvailable = change.isFlashAvailable;
return update; return update;
}); });
@ -297,13 +290,10 @@ export default function PricesOverview() {
); );
}; };
const changeCount = Object.keys(pendingChanges).length; const changeCount = Object.keys(pendingChanges).length;
return ( return (
<View style={tw`flex-1 bg-gray-50`}> <View style={tw`flex-1 bg-gray-50`}>
{/* Stores filter, save button, and menu */}
<View style={tw`bg-white px-4 py-4 border-b border-gray-200 flex-row items-center`}> <View style={tw`bg-white px-4 py-4 border-b border-gray-200 flex-row items-center`}>
<View style={tw`flex-1 mr-4`}> <View style={tw`flex-1 mr-4`}>
<BottomDropdown <BottomDropdown
@ -350,7 +340,6 @@ export default function PricesOverview() {
</TouchableOpacity> </TouchableOpacity>
</View> </View>
{/* Content */}
{productsLoading || storesLoading ? ( {productsLoading || storesLoading ? (
<View style={tw`flex-1 justify-center items-center`}> <View style={tw`flex-1 justify-center items-center`}>
<ActivityIndicator size="large" color="#3b82f6" /> <ActivityIndicator size="large" color="#3b82f6" />
@ -358,10 +347,11 @@ export default function PricesOverview() {
</View> </View>
) : ( ) : (
<FlatList <FlatList
data={filteredProducts} data={filteredSkus}
renderItem={({ item }) => ( renderItem={({ item }) => (
<ProductItemComponent <SkuItemComponent
item={item} sku={item}
productName={item._productName}
hasChanges={hasChanges} hasChanges={hasChanges}
pendingChanges={pendingChanges} pendingChanges={pendingChanges}
setPendingChanges={setPendingChanges} setPendingChanges={setPendingChanges}
@ -374,10 +364,10 @@ export default function PricesOverview() {
/> />
)} )}
{/* Edit Dialog */} <BottomDialog open={editDialog.open} onClose={() => setEditDialog({ ...editDialog, open: false, tempFlashPrice: "", tempMarketPrice: "", tempPrice: "" })}>
<BottomDialog open={editDialog.open} onClose={() => setEditDialog({ ...editDialog, open: false, tempFlashPrice: "", tempMarketPrice: "", tempPrice: "", tempProductQuantity: "" })}>
<View style={tw`p-4`}> <View style={tw`p-4`}>
<MyText style={tw`text-lg font-bold mb-4`}>{editDialog.product?.name}</MyText> <MyText style={tw`text-lg font-bold mb-1`}>{editDialog.productName}</MyText>
<MyText style={tw`text-sm text-gray-500 mb-4`}>{editDialog.sku?.displayName || editDialog.sku?.name || ''}</MyText>
<View style={tw`mb-4`}> <View style={tw`mb-4`}>
<MyText style={tw`text-sm font-medium mb-1`}>Our Price</MyText> <MyText style={tw`text-sm font-medium mb-1`}>Our Price</MyText>
@ -412,17 +402,6 @@ export default function PricesOverview() {
/> />
</View> </View>
<View style={tw`mb-4`}>
<MyText style={tw`text-sm font-medium mb-1`}>Product Size</MyText>
<TextInput
style={tw`border border-gray-300 rounded-md px-3 py-2`}
value={editDialog.tempProductQuantity}
onChangeText={(text) => setEditDialog({ ...editDialog, tempProductQuantity: text })}
keyboardType="decimal-pad"
placeholder="Enter product size"
/>
</View>
<TouchableOpacity <TouchableOpacity
style={tw`bg-blue-600 py-3 rounded-md items-center`} style={tw`bg-blue-600 py-3 rounded-md items-center`}
onPress={saveEditDialog} onPress={saveEditDialog}
@ -432,7 +411,6 @@ export default function PricesOverview() {
</View> </View>
</BottomDialog> </BottomDialog>
{/* Menu Dialog */}
<BottomDialog open={showMenu} onClose={() => setShowMenu(false)}> <BottomDialog open={showMenu} onClose={() => setShowMenu(false)}>
<View style={tw`p-6`}> <View style={tw`p-6`}>
<MyText style={tw`text-lg font-bold text-gray-800 mb-6`}> <MyText style={tw`text-lg font-bold text-gray-800 mb-6`}>
@ -441,7 +419,7 @@ export default function PricesOverview() {
<TouchableOpacity <TouchableOpacity
style={tw`flex-row items-center p-4 bg-gray-50 rounded-lg`} style={tw`flex-row items-center p-4 bg-gray-50 rounded-lg`}
onPress={() => { onPress={() => {
router.push('/rebalance-orders' as any); router.push('/(drawer)/dashboard/rebalance-orders' as any);
setShowMenu(false); setShowMenu(false);
}} }}
> >
@ -452,8 +430,6 @@ export default function PricesOverview() {
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</BottomDialog> </BottomDialog>
</View> </View>
); );
} }

View file

@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { View } from 'react-native'; import { View } from 'react-native';
import { AppContainer } from 'common-ui'; import { AppContainer } from 'common-ui';
import ProductGroupForm from '../../../components/ProductGroupForm'; import ProductGroupForm from '../../../../components/ProductGroupForm';
import { useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
export default function CreateProductGroup() { export default function CreateProductGroup() {

View file

@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { View } from 'react-native'; import { View } from 'react-native';
import { AppContainer, MyText } from 'common-ui'; import { AppContainer, MyText } from 'common-ui';
import ProductGroupForm from '../../../../components/ProductGroupForm'; import ProductGroupForm from '../../../../../components/ProductGroupForm';
import { useRouter, useLocalSearchParams } from 'expo-router'; import { useRouter, useLocalSearchParams } from 'expo-router';
import { trpc } from '@/src/trpc-client'; import { trpc } from '@/src/trpc-client';

View file

@ -10,7 +10,7 @@ import {
MyTouchableOpacity, MyTouchableOpacity,
BottomDialog, BottomDialog,
} from "common-ui"; } from "common-ui";
import { trpc } from "../../../src/trpc-client"; import { trpc } from "../../../../src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons"; import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { LinearGradient } from "expo-linear-gradient"; import { LinearGradient } from "expo-linear-gradient";
import dayjs from "dayjs"; import dayjs from "dayjs";
@ -143,11 +143,11 @@ export default function ProductGroupings() {
}); });
const handleCreate = () => { const handleCreate = () => {
router.push("/product-groupings/create"); router.push("/(drawer)/dashboard/product-groupings/create");
}; };
const handleEdit = (group: ProductGroup) => { const handleEdit = (group: ProductGroup) => {
router.push(`/product-groupings/edit/${group.id}`); router.push(`/(drawer)/dashboard/product-groupings/edit/${group.id}`);
}; };
const handleDelete = (id: number) => { const handleDelete = (id: number) => {

View file

@ -6,6 +6,7 @@ export default function Layout() {
<Stack.Screen name="index" options={{ title: "Product Tags" }} /> <Stack.Screen name="index" options={{ title: "Product Tags" }} />
<Stack.Screen name="add" options={{ title: "Add Tag" }} /> <Stack.Screen name="add" options={{ title: "Add Tag" }} />
<Stack.Screen name="edit/index" options={{ title: "Edit Tag" }} /> <Stack.Screen name="edit/index" options={{ title: "Edit Tag" }} />
<Stack.Screen name="order" options={{ title: "Tag Orders" }} />
</Stack> </Stack>
); );
} }

View file

@ -11,6 +11,7 @@ interface TagFormData {
tagDescription: string; tagDescription: string;
isDashboardTag: boolean; isDashboardTag: boolean;
relatedStores: number[]; relatedStores: number[];
productIds: number[];
} }
export default function AddTag() { export default function AddTag() {
@ -45,6 +46,7 @@ export default function AddTag() {
imageUrl, imageUrl,
isDashboardTag: values.isDashboardTag, isDashboardTag: values.isDashboardTag,
relatedStores: values.relatedStores, relatedStores: values.relatedStores,
productIds: values.productIds,
uploadUrls, uploadUrls,
}) })
@ -66,6 +68,7 @@ export default function AddTag() {
tagDescription: '', tagDescription: '',
isDashboardTag: false, isDashboardTag: false,
relatedStores: [], relatedStores: [],
productIds: [],
}; };
return ( return (

View file

@ -11,6 +11,7 @@ interface TagFormData {
tagDescription: string; tagDescription: string;
isDashboardTag: boolean; isDashboardTag: boolean;
relatedStores: number[]; relatedStores: number[];
productIds: number[];
existingImageUrl?: string; existingImageUrl?: string;
} }
@ -58,6 +59,7 @@ export default function EditTag() {
imageUrl, imageUrl,
isDashboardTag: values.isDashboardTag, isDashboardTag: values.isDashboardTag,
relatedStores: values.relatedStores, relatedStores: values.relatedStores,
productIds: values.productIds,
uploadUrls, uploadUrls,
}) })
@ -95,11 +97,16 @@ export default function EditTag() {
} }
const tag = tagData.tag; const tag = tagData.tag;
const tagProductIds = tag.productIds || (tag.products || []).map((p: any) => p.productId);
// Order by the saved sortOrder (fall back to the join order if empty).
const orderedProductIds = (tag.sortOrder || []).filter((id: number) => tagProductIds.includes(id));
const remainingProductIds = tagProductIds.filter((id: number) => !orderedProductIds.includes(id));
const initialValues: TagFormData = { const initialValues: TagFormData = {
tagName: tag.tagName, tagName: tag.tagName,
tagDescription: tag.tagDescription || '', tagDescription: tag.tagDescription || '',
isDashboardTag: tag.isDashboardTag, isDashboardTag: tag.isDashboardTag,
relatedStores: Array.isArray(tag.relatedStores) ? tag.relatedStores : [], relatedStores: Array.isArray(tag.relatedStores) ? tag.relatedStores : [],
productIds: [...orderedProductIds, ...remainingProductIds],
existingImageUrl: tag.imageUrl || undefined, existingImageUrl: tag.imageUrl || undefined,
}; };

View file

@ -53,11 +53,18 @@ const TagItem: React.FC<TagItemProps> = ({ item, onDeleteSuccess }) => (
interface TagHeaderProps { interface TagHeaderProps {
onAddNewTag: () => void; onAddNewTag: () => void;
onOrderTags: () => void;
} }
const TagHeader: React.FC<TagHeaderProps> = ({ onAddNewTag }) => ( const TagHeader: React.FC<TagHeaderProps> = ({ onAddNewTag, onOrderTags }) => (
<View style={tw`flex-row justify-between items-center p-4 bg-white border-b border-gray-200`}> <View style={tw`flex-row justify-between items-center p-4 bg-white border-b border-gray-200`}>
<MyText style={tw`text-xl font-bold text-gray-800`}>Product Tags</MyText> <TouchableOpacity
onPress={onOrderTags}
style={tw`bg-gray-100 px-3 py-2 rounded-lg flex-row items-center`}
>
<MaterialIcons name="sort" size={18} color="#374151" />
<MyText style={tw`text-gray-800 font-medium ml-1.5`}>Tag Orders</MyText>
</TouchableOpacity>
<TouchableOpacity <TouchableOpacity
onPress={onAddNewTag} onPress={onAddNewTag}
style={tw`bg-blue-500 px-4 py-2 rounded-lg flex-row items-center`} style={tw`bg-blue-500 px-4 py-2 rounded-lg flex-row items-center`}
@ -88,7 +95,11 @@ export default function ProductTags() {
}; };
const handleAddNewTag = () => { const handleAddNewTag = () => {
router.push('/product-tags/add'); router.push('/(drawer)/dashboard/product-tags/add');
};
const handleOrderTags = () => {
router.push('/(drawer)/dashboard/product-tags/order');
}; };
@ -127,7 +138,7 @@ export default function ProductTags() {
refreshControl={ refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} /> <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
} }
ListHeaderComponent={<TagHeader onAddNewTag={handleAddNewTag} />} ListHeaderComponent={<TagHeader onAddNewTag={handleAddNewTag} onOrderTags={handleOrderTags} />}
contentContainerStyle={tw`pb-4`} contentContainerStyle={tw`pb-4`}
ListEmptyComponent={ ListEmptyComponent={
<View style={tw`flex-1 justify-center items-center py-12`}> <View style={tw`flex-1 justify-center items-center py-12`}>

View file

@ -0,0 +1,369 @@
import React, { useState, useEffect, useCallback } from 'react';
import {
View,
Alert,
ActivityIndicator,
Dimensions,
StyleSheet,
} from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { Image } from 'expo-image';
import DraggableFlatList, {
ScaleDecorator,
} from 'react-native-draggable-flatlist';
import {
AppContainer,
MyText,
tw,
MyTouchableOpacity,
} from 'common-ui';
import { useRouter } from 'expo-router';
import { trpc } from '../../../../src/trpc-client';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useQueryClient } from '@tanstack/react-query';
const { width: screenWidth } = Dimensions.get('window');
const itemWidth = screenWidth - 48;
const itemHeight = 80;
interface Tag {
id: number;
tagName: string;
imageUrl: string | null;
}
interface TagItemProps {
item: Tag;
drag: () => void;
isActive: boolean;
}
const TagItem: React.FC<TagItemProps> = ({ item, drag, isActive }) => {
return (
<ScaleDecorator>
<TouchableOpacity
onLongPress={drag}
activeOpacity={1}
style={[
styles.item,
isActive && styles.activeItem,
]}
>
{/* Drag Handle */}
<View style={styles.dragHandle}>
<MaterialIcons
name="drag-indicator"
size={24}
color={isActive ? '#3b82f6' : '#9ca3af'}
/>
</View>
{/* Tag Image */}
{item.imageUrl ? (
<Image
source={{ uri: item.imageUrl }}
style={styles.image}
contentFit="cover"
/>
) : (
<View style={styles.placeholderImage}>
<MaterialIcons name="label" size={24} color="#9ca3af" />
</View>
)}
{/* Tag Info */}
<View style={styles.info}>
<MyText style={styles.name} numberOfLines={1}>
{item.tagName}
</MyText>
</View>
</TouchableOpacity>
</ScaleDecorator>
);
};
export default function TagOrders() {
const router = useRouter();
const queryClient = useQueryClient();
const [tags, setTags] = useState<Tag[]>([]);
const [hasChanges, setHasChanges] = useState(false);
// Get current order from constants
const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.const.getConstants.useQuery();
const { data: tagsData, isLoading: isLoadingTags, error: tagsError } = trpc.admin.product.getProductTags.useQuery();
const updateConstants = trpc.admin.const.updateConstants.useMutation();
// Initialize tags from the tagsOrder constant
useEffect(() => {
if (tagsData?.tags) {
const tagsOrderConstant = constants?.find(c => c.key === 'tagsOrder');
let orderedIds: number[] = [];
if (tagsOrderConstant) {
const value = tagsOrderConstant.value;
if (Array.isArray(value)) {
orderedIds = value.map((id: any) => parseInt(id));
} else if (typeof value === 'string') {
orderedIds = value.split(',').map((id: string) => parseInt(id.trim())).filter(id => !isNaN(id));
}
}
// Create tag map for quick lookup
const tagMap = new Map(tagsData.tags.map(t => [t.id, t]));
// Sort tags based on order, tags not in order go to end
const sortedTags: Tag[] = [];
// First add tags in the specified order
for (const id of orderedIds) {
const tag = tagMap.get(id);
if (tag) {
sortedTags.push({
id: tag.id,
tagName: tag.tagName,
imageUrl: tag.imageUrl || null,
});
tagMap.delete(id);
}
}
// Then add remaining tags (not in order yet)
for (const tag of tagMap.values()) {
sortedTags.push({
id: tag.id,
tagName: tag.tagName,
imageUrl: tag.imageUrl || null,
});
}
setTags(sortedTags);
}
}, [constants, tagsData]);
const handleDragEnd = useCallback(({ data }: { data: Tag[] }) => {
setTags(data);
setHasChanges(true);
}, []);
const renderItem = useCallback(({ item, drag, isActive }: { item: Tag; drag: () => void; isActive: boolean }) => {
return (
<TagItem
item={item}
drag={drag}
isActive={isActive}
/>
);
}, []);
const handleSave = () => {
const tagIds = tags.map(t => t.id);
updateConstants.mutate(
{
constants: [{
key: 'tagsOrder',
value: tagIds
}]
},
{
onSuccess: () => {
setHasChanges(false);
Alert.alert('Success', 'Tag order updated successfully!');
queryClient.invalidateQueries({ queryKey: ['const.getConstants'] });
},
onError: (error) => {
Alert.alert('Error', 'Failed to update tag order. Please try again.');
console.error('Update tag order error:', error);
}
}
);
};
// Show loading state while data is being fetched
if (isLoadingConstants || isLoadingTags) {
return (
<AppContainer>
<View style={tw`flex-1 bg-gray-50`}>
<View style={tw`bg-white px-4 py-4 border-b border-gray-200 flex-row items-center justify-between`}>
<TouchableOpacity
onPress={() => router.back()}
style={tw`p-2 -ml-4`}
>
<MaterialIcons name="chevron-left" size={24} color="#374151" />
</TouchableOpacity>
<MyText style={tw`text-xl font-bold text-gray-900`}>Tag Orders</MyText>
<View style={tw`w-16`} />
</View>
<View style={tw`flex-1 justify-center items-center p-8`}>
<ActivityIndicator size="large" color="#3b82f6" />
<MyText style={tw`text-gray-500 mt-4 text-center`}>
{isLoadingConstants ? 'Loading order...' : 'Loading tags...'}
</MyText>
</View>
</View>
</AppContainer>
);
}
// Show error state if queries failed
if (constantsError || tagsError) {
return (
<AppContainer>
<View style={tw`flex-1 bg-gray-50`}>
<View style={tw`bg-white px-4 py-4 border-b border-gray-200 flex-row items-center justify-between`}>
<TouchableOpacity
onPress={() => router.back()}
style={tw`p-2 -ml-4`}
>
<MaterialIcons name="chevron-left" size={24} color="#374151" />
</TouchableOpacity>
<MyText style={tw`text-xl font-bold text-gray-900`}>Tag Orders</MyText>
<View style={tw`w-16`} />
</View>
<View style={tw`flex-1 justify-center items-center p-8`}>
<MaterialIcons name="error-outline" size={64} color="#ef4444" />
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Error</MyText>
<MyText style={tw`text-gray-500 mt-2 text-center`}>
{constantsError ? 'Failed to load order' : 'Failed to load tags'}
</MyText>
<TouchableOpacity
onPress={() => router.back()}
style={tw`mt-6 bg-blue-600 px-6 py-3 rounded-full`}
>
<MyText style={tw`text-white font-semibold`}>Go Back</MyText>
</TouchableOpacity>
</View>
</View>
</AppContainer>
);
}
return (
<View style={tw`flex-1 bg-gray-50`}>
{/* Header */}
<View style={tw`bg-white px-4 py-4 border-b border-gray-200 flex-row items-center justify-between`}>
<MyTouchableOpacity
onPress={() => router.back()}
style={tw`p-2 -ml-4`}
>
<MaterialIcons name="chevron-left" size={24} color="#374151" />
</MyTouchableOpacity>
<MyText style={tw`text-xl font-bold text-gray-900`}>Tag Orders</MyText>
<MyTouchableOpacity
onPress={handleSave}
disabled={!hasChanges || updateConstants.isPending}
style={tw`px-4 py-2 rounded-lg ${
hasChanges && !updateConstants.isPending
? 'bg-blue-600'
: 'bg-gray-300'
}`}
>
<MyText style={tw`${
hasChanges && !updateConstants.isPending
? 'text-white'
: 'text-gray-500'
} font-semibold`}>
{updateConstants.isPending ? 'Saving...' : 'Save'}
</MyText>
</MyTouchableOpacity>
</View>
{/* Content */}
{tags.length === 0 ? (
<View style={tw`flex-1 justify-center items-center p-8`}>
<MaterialIcons name="label-off" size={64} color="#e5e7eb" />
<MyText style={tw`text-gray-500 mt-4 text-center text-lg`}>
No tags available
</MyText>
</View>
) : (
<View style={tw`flex-1`}>
<View style={tw`bg-blue-50 px-4 py-2 mb-2 mt-2 mx-4 rounded-lg`}>
<MyText style={tw`text-blue-700 text-xs text-center`}>
Long press and drag to reorder • {tags.length} items
</MyText>
</View>
<View style={tw`flex-1 px-3`}>
<DraggableFlatList
data={tags}
renderItem={renderItem}
keyExtractor={(item) => item.id.toString()}
onDragEnd={handleDragEnd}
showsVerticalScrollIndicator={true}
contentContainerStyle={{ paddingBottom: 20 }}
containerStyle={tw`flex-1`}
keyboardShouldPersistTaps="handled"
activationDistance={10}
/>
</View>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
item: {
width: itemWidth,
height: 60,
backgroundColor: 'white',
borderRadius: 8,
borderWidth: 1,
borderColor: '#e5e7eb',
padding: 10,
flexDirection: 'row',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 2,
marginVertical: 4,
},
activeItem: {
shadowColor: '#3b82f6',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 8,
borderColor: '#3b82f6',
transform: [{ scale: 1.02 }],
},
dragHandle: {
marginRight: 8,
padding: 2,
},
image: {
width: 30,
height: 30,
borderRadius: 6,
marginRight: 10,
},
placeholderImage: {
width: 30,
height: 30,
borderRadius: 6,
backgroundColor: '#f3f4f6',
marginRight: 10,
alignItems: 'center',
justifyContent: 'center',
},
info: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
name: {
fontSize: 13,
color: '#111827',
fontWeight: '500',
flex: 1,
marginRight: 4,
},
});

View file

@ -0,0 +1,141 @@
import React from 'react'
import { Alert } from 'react-native'
import { AppContainer, ImageUploaderNeoPayload } from 'common-ui'
import ProductForm from '@/src/components/ProductForm'
import { trpc } from '@/src/trpc-client'
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
export default function AddProduct() {
const createProduct = trpc.admin.product.createProduct.useMutation()
const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
enabled: false,
})
const { upload, isUploading } = useUploadToObjectStorage()
const handleSubmit = async (values: any, variantImages: ImageUploaderNeoPayload[][], _deletedImageKeys?: string[]) => {
try {
for (const variant of values.variants) {
const price = parseFloat(variant.price)
if (isNaN(price) || price <= 0) {
Alert.alert('Error', 'Please enter a valid price for every variant')
return
}
}
const seenSignatures = new Set<string>()
for (const variant of values.variants) {
const attributes = variant.attributes || []
const hasQuantity = attributes.some(
(a: any) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
)
if (!hasQuantity) {
Alert.alert('Error', 'Every SKU must have a quantity feature')
return
}
const signature = attributes
.map((a: any) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
.sort()
.join('|')
if (seenSignatures.has(signature)) {
Alert.alert('Error', 'Two variants have the same attributes')
return
}
seenSignatures.add(signature)
}
const allBlobs: { blob: Blob; mimeType: string }[] = []
const imageCounts: number[] = variantImages.map((imgs) => imgs.length)
for (const imgs of variantImages) {
for (const img of imgs) {
const response = await fetch(img.url)
const blob = await response.blob()
allBlobs.push({ blob, mimeType: img.mimeType || 'image/jpeg' })
}
}
let allUploadUrls: string[] = []
if (allBlobs.length > 0) {
const result = await upload({ images: allBlobs, contextString: 'product_info' })
allUploadUrls = result.presignedUrls
}
let urlCursor = 0
const skus = values.variants.map((variant: any, vIndex: number) => {
const count = imageCounts[vIndex]
const variantUrls = allUploadUrls.slice(urlCursor, urlCursor + count)
urlCursor += count
return {
name: variant.name || null,
price: parseFloat(variant.price),
marketPrice: variant.marketPrice ? parseFloat(variant.marketPrice) : undefined,
images: variantUrls,
isFlashAvailable: variant.isFlashAvailable || false,
flashPrice: variant.flashPrice ? parseFloat(variant.flashPrice) : undefined,
isOffer: variant.isOffer || false,
isComboOnly: variant.isComboOnly || false,
isDeleted: variant.isDeleted || false,
isSuspended: variant.isSuspended || false,
features: variant.attributes.map((attr: any) => ({
featureName: attr.featureName,
featureValue: attr.featureValue,
})),
comboItems: (variant.comboItems || []).map((ci: any) => ({
skuId: typeof ci.skuId === 'string' ? parseInt(ci.skuId) : ci.skuId,
})),
}
})
await createProduct.mutateAsync({
name: values.name,
shortDescription: values.shortDescription || undefined,
longDescription: values.longDescription || undefined,
storeId: values.storeId,
productType: values.productType,
incrementStep: 1,
skus,
})
await refetchProducts()
Alert.alert('Success', 'Product created successfully!')
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to create product')
}
}
const initialValues = {
name: '',
shortDescription: '',
longDescription: '',
storeId: 1,
productType: 'item' as const,
variants: [
{
id: undefined as number | undefined,
name: '',
price: '',
marketPrice: '',
isFlashAvailable: false,
flashPrice: '',
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
attributes: [{ featureName: 'quantity', featureValue: '' }],
comboItems: [] as { skuId: number | string }[],
},
],
}
return (
<AppContainer>
<ProductForm
mode="create"
initialValues={initialValues}
onSubmit={handleSubmit}
isLoading={createProduct.isPending || isUploading}
/>
</AppContainer>
)
}

View file

@ -149,12 +149,11 @@ export default function ProductDetail() {
refetch(); refetch();
}); });
const toggleOutOfStock = trpc.admin.product.toggleOutOfStock.useMutation();
const product = productData?.product; const product = productData?.product;
const defaultSku = product?.skus?.[0]
const handleEdit = () => { const handleEdit = () => {
router.push(`/products/edit?id=${productId}` as any); router.push(`/(drawer)/dashboard/products/edit?id=${productId}` as any);
}; };
@ -188,9 +187,9 @@ export default function ProductDetail() {
{/* Hero Section */} {/* Hero Section */}
<View style={tw`relative`}> <View style={tw`relative`}>
{product.images && product.images.length > 0 ? ( {defaultSku?.images && defaultSku.images.length > 0 ? (
<ImageCarousel <ImageCarousel
urls={product.images} urls={defaultSku.images}
imageWidth={screenWidth} imageWidth={screenWidth}
imageHeight={carouselHeight} imageHeight={carouselHeight}
showPaginationDots={true} showPaginationDots={true}
@ -229,43 +228,12 @@ export default function ProductDetail() {
<Animated.View entering={FadeInUp.delay(100).duration(500)} style={tw`bg-white px-6 pt-8 pb-6 rounded-b-[32px] shadow-sm mb-4`}> <Animated.View entering={FadeInUp.delay(100).duration(500)} style={tw`bg-white px-6 pt-8 pb-6 rounded-b-[32px] shadow-sm mb-4`}>
<View style={tw`flex-row justify-between items-start mb-2`}> <View style={tw`flex-row justify-between items-start mb-2`}>
<MyText style={tw`text-3xl font-extrabold text-gray-900 flex-1 mr-4 leading-tight`}>{product.name}</MyText> <MyText style={tw`text-3xl font-extrabold text-gray-900 flex-1 mr-4 leading-tight`}>{product.name}</MyText>
<TouchableOpacity
onPress={() => {
toggleOutOfStock.mutate({ id: productId }, {
onSuccess: () => Alert.alert('Success', 'Stock status updated'),
onError: (err) => Alert.alert('Error', err.message)
});
}}
activeOpacity={0.9}
>
<LinearGradient
colors={product.isOutOfStock ? ['#EF4444', '#DC2626'] : ['#10B981', '#059669']}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
style={tw`px-4 py-1.5 rounded-full shadow-sm`}
>
<Text style={tw`text-white text-xs font-bold uppercase tracking-wide`}>
{product.isOutOfStock ? 'Out of Stock' : 'In Stock'}
</Text>
</LinearGradient>
</TouchableOpacity>
</View> </View>
<View style={tw`flex-row items-end mt-2`}> <View style={tw`flex-row items-end mt-2`}>
<Text style={tw`text-4xl font-black text-gray-900`}>₹{product.price}</Text>
<Text style={tw`text-gray-500 text-xl font-medium mb-1.5 ml-2`}>/ {product.unit?.shortNotation}</Text>
{product.marketPrice && (
<View style={tw`ml-4 mb-2 px-2 py-0.5 bg-red-50 rounded`}>
<Text style={tw`text-red-400 text-base line-through font-medium`}>₹{product.marketPrice}</Text>
</View>
)}
</View>
{/* Increment Step Info */}
<View style={tw`mt-3 flex-row items-center`}>
<View style={tw`bg-blue-50 px-3 py-1.5 rounded-full border border-blue-100`}> <View style={tw`bg-blue-50 px-3 py-1.5 rounded-full border border-blue-100`}>
<Text style={tw`text-blue-700 text-sm font-bold`}> <Text style={tw`text-blue-700 text-sm font-bold`}>
Increment: {product.incrementStep || 1} {product.skus?.length ?? 0} Variant{(product.skus?.length ?? 0) !== 1 ? 's' : ''}
</Text> </Text>
</View> </View>
</View> </View>
@ -287,29 +255,10 @@ export default function ProductDetail() {
<Text style={tw`text-lg font-bold text-gray-900`}>{reviewsData?.reviews.length || 0}</Text> <Text style={tw`text-lg font-bold text-gray-900`}>{reviewsData?.reviews.length || 0}</Text>
<Text style={tw`text-xs text-gray-400 font-medium mt-1 uppercase`}>Reviews</Text> <Text style={tw`text-xs text-gray-400 font-medium mt-1 uppercase`}>Reviews</Text>
</View> </View>
{/* <View style={tw`flex-1 items-center`}> <View style={tw`flex-1 items-center`}>
<TouchableOpacity <Text style={tw`text-lg font-bold text-gray-900`}>{product.incrementStep || 1}</Text>
onPress={() => { <Text style={tw`text-xs text-gray-400 font-medium mt-1 uppercase`}>Step</Text>
toggleOutOfStock.mutate({ id: productId }, { </View>
onSuccess: () => Alert.alert('Success', 'Stock status updated'),
onError: (err) => Alert.alert('Error', err.message)
});
}}
activeOpacity={0.9}
>
<LinearGradient
colors={product.isOutOfStock ? ['#EF4444', '#DC2626'] : ['#10B981', '#059669']}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
style={tw`px-3 py-1 rounded-full shadow-sm`}
>
<Text style={tw`text-white text-xs font-bold uppercase tracking-wide`}>
{product.isOutOfStock ? 'Out of Stock' : 'In Stock'}
</Text>
</LinearGradient>
</TouchableOpacity>
<Text style={tw`text-xs text-gray-400 font-medium mt-1 uppercase`}>Stock</Text>
</View> */}
</View> </View>
</Animated.View> </Animated.View>
@ -333,43 +282,67 @@ export default function ProductDetail() {
</View> </View>
</Animated.View> </Animated.View>
{/* Availability */} {/* Variants Section */}
<Animated.View entering={FadeInDown.delay(250).duration(500)} style={tw`px-4 mb-4`}> <Animated.View entering={FadeInDown.delay(300).duration(500)} style={tw`px-4 mb-4`}>
<View style={tw`bg-white p-6 rounded-3xl shadow-sm`}> <View style={tw`bg-white p-6 rounded-3xl shadow-sm`}>
<View style={tw`flex-row items-center mb-4`}> <View style={tw`flex-row items-center mb-4`}>
<View style={tw`w-10 h-10 bg-blue-50 rounded-full items-center justify-center mr-3`}> <View style={tw`w-10 h-10 bg-green-50 rounded-full items-center justify-center mr-3`}>
<MaterialIcons name="inventory" size={22} color="#2563EB" /> <MaterialIcons name="category" size={22} color="#059669" />
</View>
<Text style={tw`text-lg font-bold text-gray-900`}>Variants</Text>
<View style={tw`bg-gray-100 px-3 py-1 rounded-full ml-3`}>
<Text style={tw`text-xs font-bold text-gray-600`}>{product.skus?.length ?? 0}</Text>
</View> </View>
<Text style={tw`text-lg font-bold text-gray-900`}>Availability</Text>
</View> </View>
<Text style={tw`text-gray-600 mb-4`}> {product.skus?.map((sku) => (
This product is currently {product.isOutOfStock ? 'out of stock' : 'in stock'}. <View key={sku.id} style={tw`border border-gray-200 rounded-2xl p-4 mb-3`}>
</Text> {/* Attributes */}
{sku.features?.map((f) => (
<View key={f.id} style={tw`flex-row mb-1`}>
<Text style={tw`text-gray-500 text-sm w-24 font-medium`}>{f.featureName}</Text>
<Text style={tw`text-gray-900 text-sm font-semibold`}>{f.featureValue}</Text>
</View>
))}
<TouchableOpacity {/* Pricing row */}
onPress={() => { <View style={tw`flex-row items-end justify-between mt-3 pt-3 border-t border-gray-100`}>
toggleOutOfStock.mutate({ id: productId }, { <View>
onSuccess: () => { <Text style={tw`text-2xl font-black text-gray-900`}>₹{sku.price}</Text>
Alert.alert('Success', 'Stock status updated'); {sku.marketPrice && (
refetch(); <Text style={tw`text-sm text-gray-400 line-through`}>₹{sku.marketPrice}</Text>
}, )}
onError: (err) => Alert.alert('Error', err.message) </View>
}); <View style={tw`flex-row items-center gap-2`}>
}} {sku.isFlashAvailable && (
activeOpacity={0.8} <View style={tw`bg-red-50 px-2 py-1 rounded-full border border-red-200`}>
style={tw`bg-gray-100 px-4 py-2 rounded-full border border-gray-200 self-start`} <Text style={tw`text-red-600 text-xs font-bold`}>Flash ₹{sku.flashPrice}</Text>
> </View>
<Text style={tw`text-gray-700 font-bold text-sm`}> )}
Mark as {product.isOutOfStock ? 'In Stock' : 'Out of Stock'} <View style={tw`px-3 py-1 rounded-full ${sku.isOutOfStock ? 'bg-red-100' : 'bg-green-100'}`}>
<Text style={tw`text-xs font-bold ${sku.isOutOfStock ? 'text-red-700' : 'text-green-700'}`}>
{sku.isOutOfStock ? 'Out of Stock' : 'In Stock'}
</Text> </Text>
</TouchableOpacity> </View>
</View>
</View>
{/* SKU Images */}
{sku.images && sku.images.length > 0 && (
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={tw`mt-3`}>
{sku.images.map((url, idx) => (
<Image key={idx} source={{ uri: url }} style={tw`w-16 h-16 rounded-lg mr-2 bg-gray-100`} />
))}
</ScrollView>
)}
</View>
))}
</View> </View>
</Animated.View> </Animated.View>
{/* Special Deals */} {/* Special Deals */}
{product.deals && product.deals.length > 0 && ( {product.deals && product.deals.length > 0 && (
<Animated.View entering={FadeInDown.delay(300).duration(500)} style={tw`px-4 mb-4`}> <Animated.View entering={FadeInDown.delay(350).duration(500)} style={tw`px-4 mb-4`}>
<LinearGradient <LinearGradient
colors={['#FFFBEB', '#FEF3C7']} colors={['#FFFBEB', '#FEF3C7']}
start={{ x: 0, y: 0 }} start={{ x: 0, y: 0 }}

View file

@ -0,0 +1,223 @@
import React, { useRef, useMemo } from 'react';
import { View, Alert } from 'react-native';
import { useLocalSearchParams } from 'expo-router';
import { AppContainer, useManualRefresh, MyText, tw, ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'common-ui';
import ProductForm, { ProductFormRef } from '@/src/components/ProductForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';
export default function EditProduct() {
const { id } = useLocalSearchParams();
const productId = Number(id);
const productFormRef = useRef<ProductFormRef>(null);
const { data: productResponse, isLoading: isFetching, refetch } = trpc.admin.product.getProductById.useQuery(
{ id: productId },
{ enabled: !!productId }
);
const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
enabled: false,
});
const updateProduct = trpc.admin.product.updateProduct.useMutation();
const { upload, isUploading } = useUploadToObjectStorage();
useManualRefresh(() => refetch());
const productData = productResponse?.product;
const initialValues = useMemo(() => {
if (!productData) {
return {
name: '',
shortDescription: '',
longDescription: '',
storeId: 0,
variants: [],
}
}
return {
name: productData.name,
shortDescription: productData.shortDescription || '',
longDescription: productData.longDescription || '',
storeId: productData.storeId || 1,
productType: (productData.productType as 'item' | 'combo') || 'item',
variants: (productData.skus || []).map((sku) => ({
id: sku.id,
name: sku.name || '',
price: sku.price || '',
marketPrice: sku.marketPrice || '',
isFlashAvailable: sku.isFlashAvailable || false,
flashPrice: sku.flashPrice || '',
isOffer: sku.isOffer || false,
isComboOnly: sku.isComboOnly || false,
isDeleted: sku.isDeleted || false,
isSuspended: sku.isSuspended || false,
attributes: (sku.features || []).map((f) => ({
featureName: f.featureName,
featureValue: f.featureValue,
})),
comboItems: (sku.comboItems || []).map((ci: any) => ({
skuId: ci.skuId.toString(),
})),
})),
}
}, [productData])
const existingVariantImages = useMemo(() => {
if (!productData) return []
return (productData.skus || []).map((sku) =>
(sku.images || []).map((url) => ({ imgUrl: url, mimeType: null } as ImageUploaderNeoItem))
)
}, [productData])
const existingVariantImageKeys = useMemo(() => {
if (!productData) return []
return (productData.skus || []).map((sku) =>
(sku.imageKeys || []).map(String)
)
}, [productData])
const handleSubmit = async (values: any, variantImages: ImageUploaderNeoPayload[][], deletedImageKeys: string[]) => {
try {
for (const variant of values.variants) {
const price = parseFloat(variant.price)
if (isNaN(price) || price <= 0) {
Alert.alert('Error', 'Please enter a valid price for every variant')
return
}
}
const seenSignatures = new Set<string>()
for (const variant of values.variants) {
const attributes = variant.attributes || []
const hasQuantity = attributes.some(
(a: any) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
)
if (!hasQuantity) {
Alert.alert('Error', 'Every SKU must have a quantity feature')
return
}
const signature = attributes
.map((a: any) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
.sort()
.join('|')
if (seenSignatures.has(signature)) {
Alert.alert('Error', 'Two variants have the same attributes')
return
}
seenSignatures.add(signature)
}
const allBlobs: { blob: Blob; mimeType: string }[] = []
const imageCounts: number[] = variantImages.map((imgs) =>
imgs.filter((img) => img.mimeType !== null).length
)
for (const imgs of variantImages) {
for (const img of imgs) {
if (img.mimeType === null) continue // existing image, skip
const response = await fetch(img.url)
const blob = await response.blob()
allBlobs.push({ blob, mimeType: img.mimeType || 'image/jpeg' })
}
}
let allUploadUrls: string[] = []
if (allBlobs.length > 0) {
const result = await upload({ images: allBlobs, contextString: 'product_info' })
allUploadUrls = result.presignedUrls
}
// Build SKU inputs with images (existing + new)
let urlCursor = 0
const skus = values.variants.map((variant: any, vIndex: number) => {
const count = imageCounts[vIndex]
const newUrls = allUploadUrls.slice(urlCursor, urlCursor + count)
urlCursor += count
// Existing images (mimeType === null) stay as-is
const existingUrls = variantImages[vIndex]
?.filter((img) => img.mimeType === null)
.map((img) => img.url) || []
const allUrls = [...existingUrls, ...newUrls]
return {
id: variant.id,
name: variant.name || null,
price: parseFloat(variant.price),
marketPrice: variant.marketPrice ? parseFloat(variant.marketPrice) : undefined,
images: allUrls,
isFlashAvailable: variant.isFlashAvailable || false,
flashPrice: variant.flashPrice ? parseFloat(variant.flashPrice) : undefined,
isOffer: variant.isOffer || false,
isComboOnly: variant.isComboOnly || false,
isDeleted: variant.isDeleted || false,
isSuspended: variant.isSuspended || false,
features: variant.attributes.map((attr: any) => ({
featureName: attr.featureName,
featureValue: attr.featureValue,
})),
comboItems: (variant.comboItems || []).map((ci: any) => ({
skuId: typeof ci.skuId === 'string' ? parseInt(ci.skuId) : ci.skuId,
})),
}
})
await updateProduct.mutateAsync({
id: productId,
name: values.name,
shortDescription: values.shortDescription || undefined,
longDescription: values.longDescription || undefined,
storeId: values.storeId,
productType: values.productType,
incrementStep: 1,
skus,
deletedImageKeys,
newImageUrls: allUploadUrls,
} as any)
await refetch()
await refetchProducts()
Alert.alert('Success', 'Product updated successfully!')
productFormRef.current?.clearImages()
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to update product')
}
};
if (isFetching) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-gray-600`}>Loading product...</MyText>
</View>
</AppContainer>
);
}
if (!productData) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-red-600`}>Product not found</MyText>
</View>
</AppContainer>
);
}
return (
<AppContainer>
<ProductForm
ref={productFormRef}
mode="edit"
initialValues={initialValues}
onSubmit={handleSubmit}
isLoading={updateProduct.isPending || isUploading}
existingVariantImages={existingVariantImages}
existingVariantImageKeys={existingVariantImageKeys}
/>
</AppContainer>
);
}

View file

@ -0,0 +1,240 @@
import React, { useState, useMemo } from 'react';
import { View, TouchableOpacity, RefreshControl } from 'react-native';
import { Image } from 'expo-image';
import { useRouter } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { AppContainer, MyText, tw, MyButton, useManualRefresh, SearchBar, useMarkDataFetchers, MyFlatList } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import type { AdminSku } from '@packages/shared';
type FilterType = 'all' | 'in-stock' | 'out-of-stock';
function getDefaultSku(product: { skus: AdminSku[] }): AdminSku | null {
return product.skus?.[0] ?? null
}
export default function Products() {
const router = useRouter();
const [searchTerm, setSearchTerm] = useState('');
const [activeFilter, setActiveFilter] = useState<FilterType>('all');
const [refreshing, setRefreshing] = useState(false);
const { data: productsData, isLoading, error, refetch } = trpc.admin.product.getProducts.useQuery();
useManualRefresh(refetch);
useMarkDataFetchers(() => {
refetch();
});
const products = productsData?.products || [];
const handleRefresh = async () => {
setRefreshing(true);
await refetch();
setRefreshing(false);
};
const filteredProducts = useMemo(() => {
return products.filter(product => {
const defaultSku = getDefaultSku(product)
const matchesSearch = product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
(product.shortDescription?.toLowerCase().includes(searchTerm.toLowerCase()));
const matchesFilter = activeFilter === 'all' ||
(activeFilter === 'in-stock' && !defaultSku?.isOutOfStock) ||
(activeFilter === 'out-of-stock' && defaultSku?.isOutOfStock);
return matchesSearch && matchesFilter;
});
}, [products, searchTerm, activeFilter]);
const handleEdit = (productId: number) => {
router.push(`/(drawer)/dashboard/products/edit?id=${productId}` as any);
};
const handleViewDetails = (productId: number) => {
router.push(`/(drawer)/dashboard/products/detail/${productId}` as any);
};
const FilterButton = ({ filter, label, count }: { filter: FilterType; label: string; count: number }) => (
<TouchableOpacity
onPress={() => setActiveFilter(filter)}
style={tw`px-4 py-2 rounded-lg ${activeFilter === filter ? 'bg-blue-500' : 'bg-gray-200'}`}
>
<MyText style={tw`${activeFilter === filter ? 'text-white' : 'text-gray-700'} font-semibold`}>
{label} ({count})
</MyText>
</TouchableOpacity>
);
if (isLoading) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-gray-600`}>Loading products...</MyText>
</View>
</AppContainer>
);
}
if (error) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-red-600`}>Error loading products</MyText>
<TouchableOpacity
onPress={() => refetch()}
style={tw`mt-4 bg-blue-500 px-4 py-2 rounded-lg`}
>
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
</TouchableOpacity>
</View>
</AppContainer>
);
}
const inStockCount = products.filter(p => getDefaultSku(p) && !getDefaultSku(p)!.isOutOfStock).length;
const outOfStockCount = products.filter(p => getDefaultSku(p)?.isOutOfStock).length;
const listHeader = (
<>
{/* Header */}
<View style={tw`flex-row justify-between items-center mb-6`}>
<MyText style={tw`text-2xl font-bold text-gray-800`}>Products</MyText>
<MyButton onPress={() => router.push('/(drawer)/dashboard/products/add' as any)}>
Add Product
</MyButton>
</View>
{/* Search Bar */}
<View style={tw`mb-4`}>
<SearchBar
value={searchTerm}
onChangeText={setSearchTerm}
onSearch={() => {}}
placeholder="Search products..."
containerStyle={tw`mb-0`}
/>
</View>
{/* Filter Tabs */}
<View style={tw`flex-row gap-2 mb-6`}>
<FilterButton filter="all" label="All" count={products.length} />
<FilterButton filter="in-stock" label="In Stock" count={inStockCount} />
<FilterButton filter="out-of-stock" label="Out of Stock" count={outOfStockCount} />
</View>
</>
);
const renderItem = ({ item: product }: { item: any }) => {
const defaultSku = getDefaultSku(product)
const skuImages = defaultSku?.images ?? null
const isOut = defaultSku?.isOutOfStock ?? false
return (
<View key={product.id} style={tw`bg-white rounded-2xl shadow-lg mb-4 overflow-hidden`}>
{/* Product Image */}
{skuImages && skuImages.length > 0 ? (
<Image
source={{ uri: skuImages[0] }}
style={tw`w-full h-48`}
resizeMode="cover"
/>
) : (
<View style={tw`w-full h-48 bg-gray-200 justify-center items-center`}>
<MaterialIcons name="image" size={48} color="#9CA3AF" />
</View>
)}
{/* Product Info */}
<View style={tw`p-4`}>
<View style={tw`flex-row justify-between items-start mb-2`}>
<MyText style={tw`text-lg font-bold text-gray-800 flex-1 mr-2`} numberOfLines={2}>
{product.name}
</MyText>
<View style={tw`flex-row items-center`}>
<View style={tw`w-3 h-3 rounded-full mr-1 ${isOut ? 'bg-red-500' : 'bg-green-500'}`} />
<MyText style={tw`text-sm ${isOut ? 'text-red-500' : 'text-green-500'} font-semibold`}>
{isOut ? 'Out' : 'In'}
</MyText>
</View>
</View>
{product.shortDescription && (
<MyText style={tw`text-gray-600 mb-2`} numberOfLines={2}>
{product.shortDescription}
</MyText>
)}
<View style={tw`flex-row justify-between items-center mb-3`}>
<MyText style={tw`text-sm text-gray-500 font-medium`}>
{product.skus?.length ?? 0} Variants
</MyText>
</View>
{/* Action Buttons */}
<View style={tw`flex-row gap-2`}>
<TouchableOpacity
onPress={() => handleViewDetails(product.id)}
style={tw`flex-1 bg-gray-500 p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="visibility" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>View</MyText>
</TouchableOpacity>
<TouchableOpacity
onPress={() => handleEdit(product.id)}
style={tw`flex-1 bg-blue-500 p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="edit" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Edit</MyText>
</TouchableOpacity>
</View>
</View>
</View>
)
};
return (
<AppContainer>
<View style={tw`flex-1`}>
<MyFlatList
data={filteredProducts}
renderItem={renderItem}
keyExtractor={(item) => item.id.toString()}
ListHeaderComponent={listHeader}
ListEmptyComponent={
<View style={tw`flex-1 justify-center items-center py-10`}>
<MaterialIcons name="inventory" size={64} color="#D1D5DB" />
<MyText style={tw`text-gray-500 text-center mt-4 text-lg`}>
{searchTerm || activeFilter !== 'all' ? 'No products match your filters' : 'No products found'}
</MyText>
<MyText style={tw`text-gray-400 text-center mt-2`}>
{searchTerm || activeFilter !== 'all' ? 'Try adjusting your search or filters' : 'Start by adding your first product'}
</MyText>
{(searchTerm || activeFilter !== 'all') && (
<TouchableOpacity
onPress={() => {
setSearchTerm('');
setActiveFilter('all');
}}
style={tw`mt-4 bg-blue-500 px-4 py-2 rounded-lg`}
>
<MyText style={tw`text-white font-semibold`}>Clear Filters</MyText>
</TouchableOpacity>
)}
</View>
}
contentContainerStyle={tw`pb-4`}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
}
/>
</View>
</AppContainer>
);
}

View file

@ -2,7 +2,7 @@ import React, { useState } from 'react';
import { View, TouchableOpacity, Alert, FlatList } from 'react-native'; import { View, TouchableOpacity, Alert, FlatList } from 'react-native';
import { MaterialCommunityIcons } from '@expo/vector-icons'; import { MaterialCommunityIcons } from '@expo/vector-icons';
import { MyText, tw, MyTouchableOpacity, MyFlatList, BottomDialog } from 'common-ui'; import { MyText, tw, MyTouchableOpacity, MyFlatList, BottomDialog } from 'common-ui';
import { trpc } from '../../../src/trpc-client'; import { trpc } from '../../../../src/trpc-client';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { LinearGradient } from 'expo-linear-gradient'; import { LinearGradient } from 'expo-linear-gradient';

View file

@ -0,0 +1,9 @@
import { Stack } from 'expo-router'
export default function Layout() {
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" options={{ title: 'Send Notifications' }} />
</Stack>
)
}

View file

@ -55,7 +55,7 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
return ( return (
<TouchableOpacity <TouchableOpacity
onPress={() => router.push(`/(drawer)/slots/slot-details?slotId=${slot.id}`)} onPress={() => router.push(`/(drawer)/dashboard/slots/slot-details?slotId=${slot.id}`)}
activeOpacity={0.7} activeOpacity={0.7}
> >
<View style={tw`bg-white p-5 mb-4 rounded-3xl shadow-sm border border-gray-100`}> <View style={tw`bg-white p-5 mb-4 rounded-3xl shadow-sm border border-gray-100`}>
@ -72,7 +72,7 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
</View> </View>
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<TouchableOpacity <TouchableOpacity
onPress={() => router.push(`/slots/edit/${slot.id}` as any)} onPress={() => router.push(`/(drawer)/dashboard/slots/edit/${slot.id}` as any)}
style={tw`px-3 py-1 rounded-full bg-pink2 mr-2`} style={tw`px-3 py-1 rounded-full bg-pink2 mr-2`}
> >
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
@ -147,7 +147,7 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
<TouchableOpacity <TouchableOpacity
onPress={() => { onPress={() => {
setMenuOpen(false); setMenuOpen(false);
router.push(`/slots/add?baseslot=${slot.id}` as any); router.push(`/(drawer)/dashboard/slots/add?baseslot=${slot.id}` as any);
}} }}
style={tw`py-4 border-b border-gray-200`} style={tw`py-4 border-b border-gray-200`}
> >
@ -277,7 +277,7 @@ export default function Slots() {
<MyTouchableOpacity <MyTouchableOpacity
testID="add-slot-fab" testID="add-slot-fab"
accessibilityLabel="add-slot-fab" accessibilityLabel="add-slot-fab"
onPress={() => router.push('/slots/add' as any)} onPress={() => router.push('/(drawer)/dashboard/slots/add' as any)}
activeOpacity={0.95} activeOpacity={0.95}
style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }} style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }}
> >

View file

@ -113,7 +113,7 @@ export default function SlotDetails() {
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<TouchableOpacity <TouchableOpacity
onPress={() => { onPress={() => {
const snippetProducts = products.filter(p => snippet.productIds.includes(p.id)); const snippetProducts = products.filter(p => snippet.skuIds.includes(p.id));
setDialogProducts(snippetProducts); setDialogProducts(snippetProducts);
setDialogOpen(true); setDialogOpen(true);
}} }}
@ -121,7 +121,7 @@ export default function SlotDetails() {
> >
<MaterialIcons name="shopping-bag" size={14} color="#94A3B8" /> <MaterialIcons name="shopping-bag" size={14} color="#94A3B8" />
<MyText style={tw`text-xs font-medium text-blue-600 ml-1 underline`}> <MyText style={tw`text-xs font-medium text-blue-600 ml-1 underline`}>
{snippet.productIds.length} products {snippet.skuIds.length} products
</MyText> </MyText>
</TouchableOpacity> </TouchableOpacity>
@ -198,7 +198,7 @@ export default function SlotDetails() {
{/* FAB for Edit Slot */} {/* FAB for Edit Slot */}
<MyTouchableOpacity <MyTouchableOpacity
onPress={() => router.push(`/slots/edit/${slot.id}` as any)} onPress={() => router.push(`/(drawer)/dashboard/slots/edit/${slot.id}` as any)}
activeOpacity={0.95} activeOpacity={0.95}
style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }} style={{ position: 'absolute', bottom: 32, right: 24, zIndex: 100 }}
> >

View file

@ -18,7 +18,7 @@ export default function AddStore() {
onSuccess: async (data) => { onSuccess: async (data) => {
await refetchStores(); await refetchStores();
Alert.alert('Success', data.message); Alert.alert('Success', data.message);
router.push('/stores' as any); // Navigate back to stores list router.push('/(drawer)/dashboard/stores' as any); // Navigate back to stores list
}, },
onError: (error: any) => { onError: (error: any) => {
Alert.alert('Error', error.message || 'Failed to create store'); Alert.alert('Error', error.message || 'Failed to create store');

View file

@ -23,7 +23,7 @@ export default function EditStore() {
onSuccess: (data) => { onSuccess: (data) => {
refetch(); refetch();
Alert.alert('Success', data.message); Alert.alert('Success', data.message);
router.push('/stores' as any); router.push('/(drawer)/dashboard/stores' as any);
}, },
onError: (error: any) => { onError: (error: any) => {
Alert.alert('Error', error.message || 'Failed to update store'); Alert.alert('Error', error.message || 'Failed to update store');

View file

@ -106,7 +106,7 @@ export default function Stores() {
const stores = storesData?.stores || []; const stores = storesData?.stores || [];
const handleEdit = (storeId: number) => { const handleEdit = (storeId: number) => {
router.push({ pathname: '/stores/edit', params: { id: storeId } }); router.push({ pathname: '/(drawer)/dashboard/stores/edit', params: { id: storeId } });
}; };
const handleDelete = (storeId: number) => { const handleDelete = (storeId: number) => {
@ -207,7 +207,7 @@ export default function Stores() {
<Animated.View entering={FadeInUp.delay(500)} style={tw`absolute bottom-8 right-6 shadow-xl`}> <Animated.View entering={FadeInUp.delay(500)} style={tw`absolute bottom-8 right-6 shadow-xl`}>
<TouchableOpacity <TouchableOpacity
activeOpacity={0.8} activeOpacity={0.8}
onPress={() => router.push('/stores/add' as any)} onPress={() => router.push('/(drawer)/dashboard/stores/add' as any)}
> >
<LinearGradient <LinearGradient
colors={['#2563EB', '#1D4ED8']} colors={['#2563EB', '#1D4ED8']}

View file

@ -112,7 +112,7 @@ export default function UserDetails() {
}); });
const handleOrderPress = useCallback((orderId: number) => { const handleOrderPress = useCallback((orderId: number) => {
router.push(`/(drawer)/manage-orders/order-details/${orderId}`); router.push(`/(drawer)/dashboard/manage-orders/order-details/${orderId}`);
}, [router]); }, [router]);
const handleSuspensionToggle = useCallback((isSuspended: boolean) => { const handleSuspensionToggle = useCallback((isSuspended: boolean) => {

View file

@ -0,0 +1,10 @@
import { Stack } from 'expo-router'
export default function Layout() {
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" options={{ title: 'User Management' }} />
<Stack.Screen name="[id]" options={{ title: 'User Details' }} />
</Stack>
)
}

View file

@ -189,7 +189,7 @@ export default function UserManagement() {
}, [hasNextPage, isFetchingNextPage, fetchNextPage]); }, [hasNextPage, isFetchingNextPage, fetchNextPage]);
const handleUserPress = useCallback((userId: number) => { const handleUserPress = useCallback((userId: number) => {
router.push(`/(drawer)/user-management/${userId}`); router.push(`/(drawer)/dashboard/user-management/${userId}`);
}, [router]); }, [router]);
const renderUserItem = useCallback(({ item, index }: { item: User; index: number }) => { const renderUserItem = useCallback(({ item, index }: { item: User; index: number }) => {

View file

@ -16,22 +16,22 @@ import {
useMarkDataFetchers, useMarkDataFetchers,
MyTouchableOpacity, MyTouchableOpacity,
} from "common-ui"; } from "common-ui";
import { trpc, trpcClient } from "../../../src/trpc-client"; import { trpc, trpcClient } from "../../../../src/trpc-client";
import MaterialIcons from "@expo/vector-icons/MaterialIcons"; import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { LinearGradient } from "expo-linear-gradient"; import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import VendorSnippetForm from "../../../components/VendorSnippetForm"; import VendorSnippetForm from "../../../../components/VendorSnippetForm";
import SnippetOrdersView from "../../../components/SnippetOrdersView"; import SnippetOrdersView from "../../../../components/SnippetOrdersView";
import { SnippetMenu } from "../../../components/SnippetMenu"; import { SnippetMenu } from "../../../../components/SnippetMenu";
import { ProductListDialog } from "../../../components/ProductListDialog"; import { ProductListDialog } from "../../../../components/ProductListDialog";
import { import {
VendorSnippet, VendorSnippet,
VendorSnippetProduct, VendorSnippetProduct,
VendorSnippetForm as VendorSnippetFormType, VendorSnippetForm as VendorSnippetFormType,
} from "../../../types/vendor-snippets"; } from "../../../../types/vendor-snippets";
const SnippetItem = ({ const SnippetItem = ({
snippet, snippet,
@ -192,7 +192,7 @@ const SnippetItem = ({
> >
<MaterialIcons name="shopping-bag" size={14} color="#94A3B8" /> <MaterialIcons name="shopping-bag" size={14} color="#94A3B8" />
<MyText style={tw`text-xs font-bold text-slate-500 ml-1.5`}> <MyText style={tw`text-xs font-bold text-slate-500 ml-1.5`}>
{snippet.productIds.length} Items {snippet.skuIds.length} Items
</MyText> </MyText>
<MaterialIcons name="chevron-right" size={14} color="#94A3B8" /> <MaterialIcons name="chevron-right" size={14} color="#94A3B8" />
</MyTouchableOpacity> </MyTouchableOpacity>
@ -212,7 +212,7 @@ const SnippetItem = ({
</View> </View>
<MyTouchableOpacity <MyTouchableOpacity
// onPress={() => router.push(`/(drawer)/slots/slot-details?slotId=${snippet.slotId}`)} // onPress={() => router.push(`/(drawer)/dashboard/slots/slot-details?slotId=${snippet.slotId}`)}
onPress={() => {}} onPress={() => {}}
activeOpacity={0.7} activeOpacity={0.7}
style={tw`flex-row items-center`} style={tw`flex-row items-center`}
@ -279,7 +279,7 @@ const handleViewProducts = (products: VendorSnippetProduct[]) => {
snippetCode: snippet.snippetCode, snippetCode: snippet.snippetCode,
slotId: snippet.slotId || 0, // Convert null to number for form slotId: snippet.slotId || 0, // Convert null to number for form
isPermanent: snippet.isPermanent, isPermanent: snippet.isPermanent,
productIds: snippet.productIds, skuIds: snippet.skuIds,
validTill: snippet.validTill, validTill: snippet.validTill,
createdAt: snippet.createdAt, createdAt: snippet.createdAt,
}; };

View file

@ -1,82 +0,0 @@
import React from 'react';
import { Alert } from 'react-native';
import { AppContainer, ImageUploaderNeoPayload } from 'common-ui';
import ProductForm from '@/src/components/ProductForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';
export default function AddProduct() {
const createProduct = trpc.admin.product.createProduct.useMutation();
const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
enabled: false,
});
const { upload, isUploading } = useUploadToObjectStorage();
const handleSubmit = async (values: any, images: ImageUploaderNeoPayload[]) => {
try {
let uploadUrls: string[] = [];
if (images.length > 0) {
const blobs = await Promise.all(
images.map(async (img) => {
const response = await fetch(img.url);
const blob = await response.blob();
return { blob, mimeType: img.mimeType || 'image/jpeg' };
})
);
const result = await upload({ images: blobs, contextString: 'product_info' });
uploadUrls = result.presignedUrls;
}
await createProduct.mutateAsync({
name: values.name,
shortDescription: values.shortDescription,
longDescription: values.longDescription,
unitId: parseInt(values.unitId),
storeId: parseInt(values.storeId),
price: parseFloat(values.price),
marketPrice: values.marketPrice ? parseFloat(values.marketPrice) : undefined,
incrementStep: 1,
productQuantity: values.productQuantity || 1,
isSuspended: values.isSuspended || false,
isFlashAvailable: values.isFlashAvailable || false,
flashPrice: values.flashPrice ? parseFloat(values.flashPrice) : undefined,
uploadUrls,
tagIds: values.tagIds || [],
});
await refetchProducts();
Alert.alert('Success', 'Product created successfully!');
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to create product');
}
};
const initialValues = {
name: '',
shortDescription: '',
longDescription: '',
unitId: 0,
price: '',
storeId: 1,
marketPrice: '',
deals: [{ quantity: '', price: '', validTill: new Date() }],
tagIds: [],
isSuspended: false,
isFlashAvailable: false,
flashPrice: '',
productQuantity: 1,
};
return (
<AppContainer>
<ProductForm
mode="create"
initialValues={initialValues}
onSubmit={handleSubmit}
isLoading={createProduct.isPending || isUploading}
/>
</AppContainer>
);
}

View file

@ -1,135 +0,0 @@
import React, { useRef } from 'react';
import { View, Alert } from 'react-native';
import { useLocalSearchParams } from 'expo-router';
import { AppContainer, useManualRefresh, MyText, tw, ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'common-ui';
import ProductForm, { ProductFormRef } from '@/src/components/ProductForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';
export default function EditProduct() {
const { id } = useLocalSearchParams();
const productId = Number(id);
const productFormRef = useRef<ProductFormRef>(null);
const { data: product, isLoading: isFetching, refetch } = trpc.admin.product.getProductById.useQuery(
{ id: productId },
{ enabled: !!productId }
);
const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
enabled: false,
});
const updateProduct = trpc.admin.product.updateProduct.useMutation();
const { upload, isUploading } = useUploadToObjectStorage();
useManualRefresh(() => refetch());
const handleSubmit = async (values: any, images: ImageUploaderNeoPayload[], imagesToDelete: string[]) => {
try {
// New images have mimeType !== null, existing images have mimeType === null
const newImages = images.filter(img => img.mimeType !== null);
let uploadUrls: string[] = [];
if (newImages.length > 0) {
const blobs = await Promise.all(
newImages.map(async (img) => {
const response = await fetch(img.url);
const blob = await response.blob();
return { blob, mimeType: img.mimeType || 'image/jpeg' };
})
);
const result = await upload({ images: blobs, contextString: 'product_info' });
uploadUrls = result.presignedUrls;
}
await updateProduct.mutateAsync({
id: productId,
name: values.name,
shortDescription: values.shortDescription,
longDescription: values.longDescription,
unitId: parseInt(values.unitId),
storeId: parseInt(values.storeId),
price: parseFloat(values.price),
marketPrice: values.marketPrice ? parseFloat(values.marketPrice) : undefined,
incrementStep: 1,
productQuantity: values.productQuantity || 1,
isSuspended: values.isSuspended || false,
isFlashAvailable: values.isFlashAvailable || false,
flashPrice: values.flashPrice ? parseFloat(values.flashPrice) : null,
uploadUrls,
imagesToDelete,
tagIds: values.tagIds || [],
});
await refetch();
await refetchProducts();
Alert.alert('Success', 'Product updated successfully!');
productFormRef.current?.clearImages();
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to update product');
}
};
if (isFetching) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-gray-600`}>Loading product...</MyText>
</View>
</AppContainer>
);
}
if (!product) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-red-600`}>Product not found</MyText>
</View>
</AppContainer>
);
}
const productData = product.product;
const existingImages: ImageUploaderNeoItem[] = (productData.images || []).map((url) => ({
imgUrl: url,
mimeType: null,
}));
const existingImageKeys = productData.imageKeys || [];
const initialValues = {
name: productData.name,
shortDescription: productData.shortDescription || '',
longDescription: productData.longDescription || '',
unitId: productData.unitId,
storeId: productData.storeId || 1,
price: productData.price.toString(),
marketPrice: productData.marketPrice?.toString() || '',
deals: productData.deals?.map(deal => ({
quantity: deal.quantity,
price: deal.price,
validTill: deal.validTill ? new Date(deal.validTill) : null,
})) || [{ quantity: '', price: '', validTill: null }],
tagIds: productData.tags?.map((tag: any) => tag.id) || [],
isSuspended: productData.isSuspended || false,
isFlashAvailable: productData.isFlashAvailable || false,
flashPrice: productData.flashPrice?.toString() || '',
productQuantity: productData.productQuantity || 1,
};
return (
<AppContainer>
<ProductForm
ref={productFormRef}
mode="edit"
initialValues={initialValues}
onSubmit={handleSubmit}
isLoading={updateProduct.isPending || isUploading}
existingImages={existingImages}
existingImageKeys={existingImageKeys}
/>
</AppContainer>
);
}

View file

@ -1,271 +0,0 @@
import React, { useState, useMemo } from 'react';
import { View, ScrollView, TouchableOpacity, Alert, RefreshControl } from 'react-native';
import { Image } from 'expo-image';
import { useRouter } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { AppContainer, MyText, tw, MyButton, useManualRefresh, MyTextInput, SearchBar, useMarkDataFetchers } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import type { AdminProduct } from '@packages/shared';
type FilterType = 'all' | 'in-stock' | 'out-of-stock';
export default function Products() {
const router = useRouter();
const [searchTerm, setSearchTerm] = useState('');
const [activeFilter, setActiveFilter] = useState<FilterType>('all');
const [refreshing, setRefreshing] = useState(false);
const { data: productsData, isLoading, error, refetch } = trpc.admin.product.getProducts.useQuery();
const toggleOutOfStockMutation = trpc.admin.product.toggleOutOfStock.useMutation();
useManualRefresh(refetch);
useMarkDataFetchers(() => {
refetch();
});
const products = productsData?.products || [];
const handleRefresh = async () => {
setRefreshing(true);
await refetch();
setRefreshing(false);
};
const filteredProducts = useMemo(() => {
return products.filter(product => {
const matchesSearch = product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
(product.shortDescription?.toLowerCase().includes(searchTerm.toLowerCase()));
const matchesFilter = activeFilter === 'all' ||
(activeFilter === 'in-stock' && !product.isOutOfStock) ||
(activeFilter === 'out-of-stock' && product.isOutOfStock);
return matchesSearch && matchesFilter;
});
}, [products, searchTerm, activeFilter]);
const handleEdit = (productId: number) => {
router.push(`/products/edit?id=${productId}` as any);
};
// const handleToggleStock = (product: any) => {
const handleToggleStock = (product: Pick<AdminProduct, 'id' | 'name' | 'isOutOfStock'>) => {
const action = product.isOutOfStock ? 'mark as in stock' : 'mark as out of stock';
Alert.alert(
'Update Stock Status',
`Are you sure you want to ${action} "${product.name}"?`,
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Confirm',
onPress: () => {
toggleOutOfStockMutation.mutate({ id: product.id }, {
onSuccess: (data) => {
Alert.alert('Success', data.message);
refetch(); // Refresh the list
},
onError: (error: any) => {
Alert.alert('Error', error.message || 'Failed to update stock status');
},
});
},
},
]
);
};
const handleViewDetails = (productId: number) => {
router.push(`/products/detail/${productId}` as any);
};
const FilterButton = ({ filter, label, count }: { filter: FilterType; label: string; count: number }) => (
<TouchableOpacity
onPress={() => setActiveFilter(filter)}
style={tw`px-4 py-2 rounded-lg ${activeFilter === filter ? 'bg-blue-500' : 'bg-gray-200'}`}
>
<MyText style={tw`${activeFilter === filter ? 'text-white' : 'text-gray-700'} font-semibold`}>
{label} ({count})
</MyText>
</TouchableOpacity>
);
if (isLoading) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-gray-600`}>Loading products...</MyText>
</View>
</AppContainer>
);
}
if (error) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-red-600`}>Error loading products</MyText>
<TouchableOpacity
onPress={() => refetch()}
style={tw`mt-4 bg-blue-500 px-4 py-2 rounded-lg`}
>
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
</TouchableOpacity>
</View>
</AppContainer>
);
}
const inStockCount = products.filter(p => !p.isOutOfStock).length;
const outOfStockCount = products.filter(p => p.isOutOfStock).length;
return (
<AppContainer>
<View style={tw`flex-1`}>
{/* Header */}
<View style={tw`flex-row justify-between items-center mb-6`}>
<MyText style={tw`text-2xl font-bold text-gray-800`}>Products</MyText>
<MyButton onPress={() => router.push('/products/add' as any)}>
Add Product
</MyButton>
</View>
{/* Search Bar */}
<View style={tw`mb-4`}>
<SearchBar
value={searchTerm}
onChangeText={setSearchTerm}
onSearch={() => {}}
placeholder="Search products..."
containerStyle={tw`mb-0`}
/>
</View>
</View>
{/* Filter Tabs */}
<View style={tw`flex-row gap-2 mb-6`}>
<FilterButton filter="all" label="All" count={products.length} />
<FilterButton filter="in-stock" label="In Stock" count={inStockCount} />
<FilterButton filter="out-of-stock" label="Out of Stock" count={outOfStockCount} />
</View>
{/* Products List */}
<ScrollView
style={tw`flex-1`}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
}
>
{filteredProducts.length === 0 ? (
<View style={tw`flex-1 justify-center items-center py-10`}>
<MaterialIcons name="inventory" size={64} color="#D1D5DB" />
<MyText style={tw`text-gray-500 text-center mt-4 text-lg`}>
{searchTerm || activeFilter !== 'all' ? 'No products match your filters' : 'No products found'}
</MyText>
<MyText style={tw`text-gray-400 text-center mt-2`}>
{searchTerm || activeFilter !== 'all' ? 'Try adjusting your search or filters' : 'Start by adding your first product'}
</MyText>
{(searchTerm || activeFilter !== 'all') && (
<TouchableOpacity
onPress={() => {
setSearchTerm('');
setActiveFilter('all');
}}
style={tw`mt-4 bg-blue-500 px-4 py-2 rounded-lg`}
>
<MyText style={tw`text-white font-semibold`}>Clear Filters</MyText>
</TouchableOpacity>
)}
</View>
) : (
<View style={tw`pb-4`}>
{filteredProducts.map(product => (
<View key={product.id} style={tw`bg-white rounded-2xl shadow-lg mb-4 overflow-hidden`}>
{/* Product Image */}
{product.images && product.images.length > 0 ? (
<Image
source={{ uri: product.images[0] }}
style={tw`w-full h-48`}
resizeMode="cover"
/>
) : (
<View style={tw`w-full h-48 bg-gray-200 justify-center items-center`}>
<MaterialIcons name="image" size={48} color="#9CA3AF" />
</View>
)}
{/* Product Info */}
<View style={tw`p-4`}>
<View style={tw`flex-row justify-between items-start mb-2`}>
<MyText style={tw`text-lg font-bold text-gray-800 flex-1 mr-2`} numberOfLines={2}>
{product.name}
</MyText>
<View style={tw`flex-row items-center`}>
<View style={tw`w-3 h-3 rounded-full mr-1 ${product.isOutOfStock ? 'bg-red-500' : 'bg-green-500'}`} />
<MyText style={tw`text-sm ${product.isOutOfStock ? 'text-red-500' : 'text-green-500'} font-semibold`}>
{product.isOutOfStock ? 'Out' : 'In'}
</MyText>
</View>
</View>
{product.shortDescription && (
<MyText style={tw`text-gray-600 mb-2`} numberOfLines={2}>
{product.shortDescription}
</MyText>
)}
<View style={tw`flex-row justify-between items-center mb-3`}>
<View>
<MyText style={tw`text-xl font-bold text-green-600`}>
₹{product.price}
</MyText>
{product.marketPrice && (
<MyText style={tw`text-sm text-gray-500 line-through`}>
₹{product.marketPrice}
</MyText>
)}
</View>
</View>
{/* Action Buttons */}
<View style={tw`flex-row gap-2`}>
<TouchableOpacity
onPress={() => handleViewDetails(product.id)}
style={tw`flex-1 bg-gray-500 p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="visibility" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>View</MyText>
</TouchableOpacity>
<TouchableOpacity
onPress={() => handleEdit(product.id)}
style={tw`flex-1 bg-blue-500 p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="edit" size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Edit</MyText>
</TouchableOpacity>
<TouchableOpacity
onPress={() => handleToggleStock(product)}
style={tw`flex-1 ${product.isOutOfStock ? 'bg-green-500' : 'bg-orange-500'} p-3 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name={product.isOutOfStock ? "check-circle" : "block"} size={16} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>
{product.isOutOfStock ? 'Stock' : 'Out'}
</MyText>
</TouchableOpacity>
</View>
</View>
</View>
))}
</View>
)}
</ScrollView>
</AppContainer>
);
}

View file

@ -1,93 +0,0 @@
import React, { useState } from 'react';
import { View, TouchableOpacity } from 'react-native';
import { Image } from 'expo-image';
import { useRouter } from 'expo-router';
import { AppContainer, MyText, tw, MyFlatList, MyTextInput } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import Ionicons from '@expo/vector-icons/Ionicons';
interface UserItemProps {
item: any;
onPress: (userId: string) => void;
}
const UserItem: React.FC<UserItemProps> = ({ item, onPress }) => (
<TouchableOpacity
style={tw`flex-row items-center p-4 bg-white border-b border-gray-100`}
onPress={() => onPress(item.id)}
>
{item.image ? (
<Image
source={{ uri: item.image }}
style={tw`w-12 h-12 rounded-full mr-4`}
/>
) : (
<View style={tw`w-12 h-12 rounded-full bg-gray-200 items-center justify-center mr-4`}>
<Ionicons name="person" size={24} color="#6b7280" />
</View>
)}
<View style={tw`flex-1`}>
<MyText style={tw`font-bold text-gray-800 text-lg`}>{item.name}</MyText>
<MyText style={tw`text-gray-600`}>{item.email}</MyText>
<MyText style={tw`text-gray-500 text-sm`}>{item.mobile}</MyText>
</View>
</TouchableOpacity>
);
export default function Users() {
const router = useRouter();
const [search, setSearch] = useState('');
const {
data,
isLoading,
fetchNextPage,
hasNextPage,
refetch,
} = trpc.admin.staffUser.getUsers.useInfiniteQuery(
{ search },
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
);
const users = data?.pages.flatMap(page => page.users) || [];
const handleUserPress = (userId: string) => {
router.push(`/(drawer)/user-management/${userId}`);
};
return (
<AppContainer>
<View style={tw`flex-1`}>
<View style={tw`bg-white px-4 py-2 border-b border-gray-100`}>
<MyTextInput
topLabel="Search Users"
placeholder="Search by name, email, or mobile"
value={search}
onChangeText={setSearch}
style={{ marginBottom: 0 }}
/>
</View>
<MyFlatList
data={users}
renderItem={({ item }) => <UserItem item={item} onPress={handleUserPress} />}
keyExtractor={(item) => item.id.toString()}
onRefresh={refetch}
onEndReached={() => {
if (hasNextPage) {
fetchNextPage();
}
}}
onEndReachedThreshold={0.5}
ListEmptyComponent={
<View style={tw`flex-1 justify-center items-center py-8`}>
<MyText style={tw`text-gray-500`}>No users found</MyText>
</View>
}
/>
</View>
</AppContainer>
);
}

View file

@ -14,7 +14,7 @@ export interface BannerFormData {
name: string; name: string;
imageUrl: string; imageUrl: string;
description: string; description: string;
productIds: number[]; skuIds: number[];
redirectUrl: string; redirectUrl: string;
// serialNum removed - will be assigned automatically by backend // serialNum removed - will be assigned automatically by backend
} }
@ -32,7 +32,7 @@ interface BannerFormProps {
const validationSchema = Yup.object().shape({ const validationSchema = Yup.object().shape({
name: Yup.string().trim().required('Banner name is required').max(255), name: Yup.string().trim().required('Banner name is required').max(255),
description: Yup.string().max(500), description: Yup.string().max(500),
productIds: Yup.array() skuIds: Yup.array()
.of(Yup.number()) .of(Yup.number())
.optional(), .optional(),
redirectUrl: Yup.string() redirectUrl: Yup.string()
@ -177,15 +177,15 @@ export default function BannerForm({
<View style={{ marginBottom: 16 }}> <View style={{ marginBottom: 16 }}>
<ProductsSelector <ProductsSelector
value={values.productIds} value={values.skuIds}
onChange={(value) => { onChange={(value) => {
const selectedValues = Array.isArray(value) ? value : [value]; const selectedValues = Array.isArray(value) ? value : [value];
setFieldValue('productIds', selectedValues.map(v => Number(v))); setFieldValue('skuIds', selectedValues.map(v => Number(v)));
}} }}
multiple={true} multiple={true}
label="Select Products" label="Select Products"
placeholder="Select products for banner (optional)" placeholder="Select products for banner (optional)"
labelFormat={(product) => `${product.name} (${product.price})`} labelFormat={(product) => `${product.productName} (₹${product.price})`}
/> />
</View> </View>

View file

@ -119,7 +119,7 @@ const ProductGroupForm: React.FC<ProductGroupFormProps> = ({
multiple={true} multiple={true}
label="Products" label="Products"
placeholder="Select products" placeholder="Select products"
labelFormat={(product) => `${product.name}${product.shortDescription ? ` - ${product.shortDescription}` : ''}`} labelFormat={(product) => product.label}
/> />
{/* Actions */} {/* Actions */}

View file

@ -4,22 +4,19 @@ import BottomDropdown, { DropdownOption } from 'common-ui/src/components/bottom-
import { trpc } from '../src/trpc-client'; import { trpc } from '../src/trpc-client';
import { tw } from 'common-ui'; import { tw } from 'common-ui';
interface Product { interface SkuSummary {
id: number; id: number;
name: string; productId: number;
price: number; productName: string;
unit?: string; label: string;
shortDescription?: string | null; storeId: number | null;
isOutOfStock?: boolean; price: string;
isSuspended?: boolean;
storeId?: number | null;
unitNotation?: string;
} }
interface Group { interface Group {
id: number; id: number;
groupName: string; groupName: string;
products: Product[]; products: { id: number }[];
} }
interface ProductsSelectorProps { interface ProductsSelectorProps {
@ -30,8 +27,8 @@ interface ProductsSelectorProps {
placeholder?: string; placeholder?: string;
disabled?: boolean; disabled?: boolean;
error?: boolean; error?: boolean;
isDisabled?: (product: Product) => boolean; isDisabled?: (product: SkuSummary) => boolean;
labelFormat?: (product: Product) => string; labelFormat?: (product: SkuSummary) => string;
groups?: Group[]; groups?: Group[];
selectedGroupIds?: number[]; selectedGroupIds?: number[];
onGroupChange?: (groupIds: number[]) => void; onGroupChange?: (groupIds: number[]) => void;
@ -53,85 +50,78 @@ export default function ProductsSelector({
selectedGroupIds = [], selectedGroupIds = [],
onGroupChange, onGroupChange,
}: ProductsSelectorProps) { }: ProductsSelectorProps) {
const { data: productsData } = trpc.common.product.getAllProductsSummary.useQuery({}); const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery({});
const products = productsData?.products || []; const allSkus: SkuSummary[] = skusData?.skus || [];
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
// Format product label: name (unit) (₹price)
const formatProductLabel = (product: Product): string => {
if (labelFormat) {
return labelFormat(product);
}
const unit = product.unit ? ` (${product.unit})` : '';
const price = ` (₹${product.price})`;
return `${product.name}${unit}${price}`;
};
// Handle group selection changes // Handle group selection changes
const handleGroupChange = (newGroupIds: number[]) => { const handleGroupChange = (newGroupIds: number[]) => {
if (!onGroupChange) return; if (!onGroupChange) return;
const previousGroupIds = selectedGroupIds; const previousGroupIds = selectedGroupIds;
// Find which groups were added and which were removed
const addedGroups = newGroupIds.filter(id => !previousGroupIds.includes(id)); const addedGroups = newGroupIds.filter(id => !previousGroupIds.includes(id));
const removedGroups = previousGroupIds.filter(id => !newGroupIds.includes(id)); const removedGroups = previousGroupIds.filter(id => !newGroupIds.includes(id));
// Get current selected products let currentSkus = Array.isArray(value) ? [...value] : value ? [value] : [];
let currentProducts = Array.isArray(value) ? [...value] : value ? [value] : [];
// Add products from newly selected groups const addedSkus = addedGroups.flatMap(groupId => {
const addedProducts = addedGroups.flatMap(groupId => {
const group = groups.find(g => g.id === groupId); const group = groups.find(g => g.id === groupId);
return group?.products.map(p => p.id) || []; if (!group) return [];
const productIds = new Set(group.products.map(p => p.id));
return allSkus.filter(s => productIds.has(s.productId)).map(s => s.id);
}); });
// Remove products from deselected groups const removedSkus = removedGroups.flatMap(groupId => {
const removedProducts = removedGroups.flatMap(groupId => {
const group = groups.find(g => g.id === groupId); const group = groups.find(g => g.id === groupId);
return group?.products.map(p => p.id) || []; if (!group) return [];
const productIds = new Set(group.products.map(p => p.id));
return allSkus.filter(s => productIds.has(s.productId)).map(s => s.id);
}); });
// Update product list: add new ones, remove deselected group ones currentSkus = [...new Set([...currentSkus, ...addedSkus])];
currentProducts = [...new Set([...currentProducts, ...addedProducts])]; currentSkus = currentSkus.filter(id => !removedSkus.includes(id));
currentProducts = currentProducts.filter(id => !removedProducts.includes(id));
onGroupChange(newGroupIds); onGroupChange(newGroupIds);
if (multiple) { if (multiple) {
onChange(currentProducts.length > 0 ? currentProducts : []); onChange(currentSkus.length > 0 ? currentSkus : []);
} else { } else {
onChange(currentProducts.length > 0 ? currentProducts[0] : 0); onChange(currentSkus.length > 0 ? currentSkus[0] : 0);
} }
}; };
// Filter products based on search query // Filter products based on search query
const filteredProducts = useMemo(() => { const filteredSkus = useMemo(() => {
if (!searchQuery.trim()) return products; if (!searchQuery.trim()) return allSkus;
const query = searchQuery.toLowerCase(); const query = searchQuery.toLowerCase();
return products.filter(product => return allSkus.filter(sku =>
product.name.toLowerCase().includes(query) || sku.label.toLowerCase().includes(query) ||
(product.shortDescription && product.shortDescription.toLowerCase().includes(query)) || sku.productName.toLowerCase().includes(query)
(product.unit && product.unit.toLowerCase().includes(query))
); );
}, [products, searchQuery]); }, [allSkus, searchQuery]);
// Build dropdown options // Build dropdown options
const productOptions: DropdownOption[] = useMemo(() => { const productOptions: DropdownOption[] = useMemo(() => {
return filteredProducts.map((product) => { return filteredSkus.map((sku) => {
const isFromGroup = selectedGroupIds.length > 0 && groups.some(group => const isFromGroup = selectedGroupIds.length > 0 && groups.some(group => {
selectedGroupIds.includes(group.id) && group.products.some(p => p.id === product.id) if (!selectedGroupIds.includes(group.id)) return false;
); return group.products.some(p => p.id === sku.productId);
});
const isProductDisabled = isDisabled ? isDisabled(product as Product) : false; const isProductDisabled = isDisabled ? isDisabled(sku) : false;
const displayLabel = labelFormat
? labelFormat(sku)
: sku.label;
return { return {
label: `${formatProductLabel(product as Product)}${isFromGroup ? ' (from group)' : ''}`, label: `${displayLabel}${isFromGroup ? ' (from group)' : ''}`,
value: product.id.toString(), value: sku.id.toString(),
disabled: isProductDisabled, disabled: isProductDisabled,
}; };
}); });
}, [filteredProducts, selectedGroupIds, groups, isDisabled, labelFormat]); }, [filteredSkus, selectedGroupIds, groups, isDisabled, labelFormat]);
// Build group options if groups are provided // Build group options if groups are provided
const groupOptions: DropdownOption[] = useMemo(() => { const groupOptions: DropdownOption[] = useMemo(() => {
@ -143,7 +133,6 @@ export default function ProductsSelector({
return ( return (
<View style={tw`w-full`}> <View style={tw`w-full`}>
{/* Groups selector (if groups are provided and showGroups is true) */}
{showGroups && groups.length > 0 && ( {showGroups && groups.length > 0 && (
<View style={tw`mb-4`}> <View style={tw`mb-4`}>
<BottomDropdown <BottomDropdown
@ -151,8 +140,8 @@ export default function ProductsSelector({
label="Select Product Groups" label="Select Product Groups"
options={groupOptions} options={groupOptions}
value={selectedGroupIds.map(id => id.toString())} value={selectedGroupIds.map(id => id.toString())}
onValueChange={(value) => { onValueChange={(selectedValue) => {
const selectedValues = Array.isArray(value) ? value : typeof value === 'string' ? [value] : []; const selectedValues = Array.isArray(selectedValue) ? selectedValue : typeof selectedValue === 'string' ? [selectedValue] : [];
const newGroupIds = selectedValues.map(v => parseInt(v as string)); const newGroupIds = selectedValues.map(v => parseInt(v as string));
handleGroupChange(newGroupIds); handleGroupChange(newGroupIds);
}} }}
@ -162,7 +151,6 @@ export default function ProductsSelector({
</View> </View>
)} )}
{/* Products selector */}
<BottomDropdown <BottomDropdown
label={label} label={label}
options={productOptions} options={productOptions}

View file

@ -9,7 +9,7 @@ import ProductsSelector from '../components/ProductsSelector';
interface VendorSnippet { interface VendorSnippet {
name: string; name: string;
groupIds: number[]; groupIds: number[];
productIds: number[]; skuIds: number[];
validTill?: string; validTill?: string;
} }
@ -40,7 +40,7 @@ export default function SlotForm({
const vendorSnippetsFromSlot = (slotData?.slot?.vendorSnippets || []).map((snippet: any) => ({ const vendorSnippetsFromSlot = (slotData?.slot?.vendorSnippets || []).map((snippet: any) => ({
name: snippet.name || '', name: snippet.name || '',
groupIds: snippet.groupIds || [], groupIds: snippet.groupIds || [],
productIds: snippet.productIds || [], skuIds: snippet.skuIds || [],
validTill: snippet.validTill || undefined, validTill: snippet.validTill || undefined,
})) as VendorSnippet[]; })) as VendorSnippet[];
@ -48,7 +48,7 @@ export default function SlotForm({
deliveryTime: initialDeliveryTime || (slotData?.slot?.deliveryTime ? new Date(slotData.slot.deliveryTime) : null), deliveryTime: initialDeliveryTime || (slotData?.slot?.deliveryTime ? new Date(slotData.slot.deliveryTime) : null),
freezeTime: initialFreezeTime || (slotData?.slot?.freezeTime ? new Date(slotData.slot.freezeTime) : null), freezeTime: initialFreezeTime || (slotData?.slot?.freezeTime ? new Date(slotData.slot.freezeTime) : null),
selectedGroupIds: initialGroupIds.length > 0 ? initialGroupIds : (slotData?.slot?.groupIds || []), selectedGroupIds: initialGroupIds.length > 0 ? initialGroupIds : (slotData?.slot?.groupIds || []),
selectedProductIds: initialProductIds.length > 0 ? initialProductIds : (slotData?.slot?.products?.map((p: any) => p.id) || []), selectedSkuIds: initialProductIds.length > 0 ? initialProductIds : (slotData?.slot?.products?.map((p: any) => p.id) || []),
vendorSnippetList: vendorSnippetsFromSlot, vendorSnippetList: vendorSnippetsFromSlot,
}; };
@ -58,15 +58,8 @@ export default function SlotForm({
const isEditMode = !!slotId; const isEditMode = !!slotId;
const isPending = isCreating || isUpdating; const isPending = isCreating || isUpdating;
// Fetch groups
const { data: groupsData } = trpc.admin.product.getGroups.useQuery(); const { data: groupsData } = trpc.admin.product.getGroups.useQuery();
const handleFormSubmit = (values: typeof initialValues) => { const handleFormSubmit = (values: typeof initialValues) => {
if (!values.deliveryTime || !values.freezeTime) { if (!values.deliveryTime || !values.freezeTime) {
Alert.alert('Error', 'Please fill all fields'); Alert.alert('Error', 'Please fill all fields');
@ -78,23 +71,22 @@ export default function SlotForm({
return; return;
} }
const slotData = { const slotInputData = {
deliveryTime: values.deliveryTime.toISOString(), deliveryTime: values.deliveryTime.toISOString(),
freezeTime: values.freezeTime.toISOString(), freezeTime: values.freezeTime.toISOString(),
isActive: initialIsActive, isActive: initialIsActive,
groupIds: values.selectedGroupIds, groupIds: values.selectedGroupIds,
productIds: values.selectedProductIds, skuIds: values.selectedSkuIds,
vendorSnippets: values.vendorSnippetList.map((snippet: VendorSnippet) => ({ vendorSnippets: values.vendorSnippetList.map((snippet: VendorSnippet) => ({
name: snippet.name, name: snippet.name,
productIds: snippet.productIds, skuIds: snippet.skuIds,
validTill: snippet.validTill, validTill: snippet.validTill,
})), })),
}; };
if (isEditMode && slotId) { if (isEditMode && slotId) {
updateSlot( updateSlot(
{ id: slotId, ...slotData }, { id: slotId, ...slotInputData },
{ {
onSuccess: () => { onSuccess: () => {
Alert.alert('Success', 'Slot updated successfully!'); Alert.alert('Success', 'Slot updated successfully!');
@ -109,12 +101,10 @@ export default function SlotForm({
); );
} else { } else {
createSlot( createSlot(
slotData, slotInputData,
{ {
onSuccess: () => { onSuccess: () => {
Alert.alert('Success', 'Slot created successfully!'); Alert.alert('Success', 'Slot created successfully!');
// Reset form
// Formik will handle reset
onSlotAdded?.(); onSlotAdded?.();
}, },
onError: (error: any) => { onError: (error: any) => {
@ -131,12 +121,11 @@ export default function SlotForm({
onSubmit={handleFormSubmit} onSubmit={handleFormSubmit}
> >
{({ handleSubmit, values, setFieldValue }) => { {({ handleSubmit, values, setFieldValue }) => {
// Map groups data to match ProductsSelector types (convert price from string to number)
const mappedGroups = (groupsData?.groups || []).map(group => ({ const mappedGroups = (groupsData?.groups || []).map(group => ({
...group, ...group,
products: group.products.map(product => ({ products: group.products.map(product => ({
...product, ...product,
price: parseFloat(product.price as unknown as string) || 0, id: product.id,
})), })),
})); }));
@ -168,8 +157,8 @@ export default function SlotForm({
<View style={tw`mb-4`}> <View style={tw`mb-4`}>
<ProductsSelector <ProductsSelector
value={values.selectedProductIds} value={values.selectedSkuIds}
onChange={(newProductIds) => setFieldValue('selectedProductIds', newProductIds)} onChange={(newSkuIds) => setFieldValue('selectedSkuIds', newSkuIds)}
groups={mappedGroups} groups={mappedGroups}
selectedGroupIds={values.selectedGroupIds} selectedGroupIds={values.selectedGroupIds}
onGroupChange={(newGroupIds) => setFieldValue('selectedGroupIds', newGroupIds)} onGroupChange={(newGroupIds) => setFieldValue('selectedGroupIds', newGroupIds)}
@ -196,19 +185,19 @@ export default function SlotForm({
<View style={tw`mb-4`}> <View style={tw`mb-4`}>
<ProductsSelector <ProductsSelector
value={snippet.productIds || []} value={snippet.skuIds || []}
onChange={(newProductIds) => setFieldValue(`vendorSnippetList.${index}.productIds`, newProductIds)} onChange={(newSkuIds) => setFieldValue(`vendorSnippetList.${index}.skuIds`, newSkuIds)}
groups={mappedGroups.filter(group => groups={mappedGroups.filter(group =>
values.selectedGroupIds.includes(group.id) values.selectedGroupIds.includes(group.id)
).map(group => ({ ).map(group => ({
...group, ...group,
products: group.products.filter(p => values.selectedProductIds.includes(p.id)) products: group.products.filter((p: any) => values.selectedSkuIds.includes(p.id))
}))} }))}
selectedGroupIds={snippet.groupIds || []} selectedGroupIds={snippet.groupIds || []}
onGroupChange={(newGroupIds) => setFieldValue(`vendorSnippetList.${index}.groupIds`, newGroupIds)} onGroupChange={(newGroupIds) => setFieldValue(`vendorSnippetList.${index}.groupIds`, newGroupIds)}
label="Select Products" label="Select Products"
placeholder="Select products for snippet" placeholder="Select products for snippet"
isDisabled={(product) => !values.selectedProductIds.includes(product.id)} isDisabled={(sku) => !values.selectedSkuIds.includes(sku.id)}
/> />
</View> </View>
<TouchableOpacity <TouchableOpacity
@ -220,7 +209,7 @@ export default function SlotForm({
</View> </View>
))} ))}
<TouchableOpacity <TouchableOpacity
onPress={() => push({ name: '', groupIds: [], productIds: [], validTill: '' })} onPress={() => push({ name: '', groupIds: [], skuIds: [], validTill: '' })}
style={tw`bg-blue-500 px-4 py-3 rounded-lg items-center`} style={tw`bg-blue-500 px-4 py-3 rounded-lg items-center`}
> >
<Text style={tw`text-white font-medium`}>Add Vendor Snippet</Text> <Text style={tw`text-white font-medium`}>Add Vendor Snippet</Text>

View file

@ -45,12 +45,12 @@ const StoreForm = forwardRef<StoreFormRef, StoreFormProps>((props, ref) => {
const [selectedImages, setSelectedImages] = useState<{ blob: Blob; mimeType: string }[]>([]); const [selectedImages, setSelectedImages] = useState<{ blob: Blob; mimeType: string }[]>([]);
const [displayImages, setDisplayImages] = useState<{ uri?: string }[]>([]); const [displayImages, setDisplayImages] = useState<{ uri?: string }[]>([]);
// For edit mode, pre-select products belonging to this store // For edit mode, pre-select SKUs belonging to this store's products
const initialSelectedProducts = useMemo(() => { const initialSelectedProducts = useMemo(() => {
if (mode !== 'edit' || !productsData?.products) return []; if (mode !== 'edit' || !productsData?.products) return [];
return productsData.products return productsData.products
.filter(p => p.storeId === storeId) .filter(p => p.storeId === storeId)
.map(p => p.id); .flatMap(p => (p.skus || []).map(sku => sku.id));
}, [mode, productsData?.products, storeId]); }, [mode, productsData?.products, storeId]);
useEffect(() => { useEffect(() => {
@ -166,8 +166,8 @@ const StoreForm = forwardRef<StoreFormRef, StoreFormProps>((props, ref) => {
multiple={true} multiple={true}
label="Products" label="Products"
placeholder="Select products" placeholder="Select products"
isDisabled={(product) => product.storeId !== null && product.storeId !== storeId} isDisabled={(sku) => sku.storeId !== null && sku.storeId !== storeId}
labelFormat={(product) => `${product.name} - ₹${product.price}`} labelFormat={(sku) => `${sku.productName} - ₹${sku.price}`}
/> />
<View style={tw`mb-6`}> <View style={tw`mb-6`}>
<MyText style={tw`text-sm font-bold text-gray-700 mb-3 uppercase tracking-wider`}>Store Image</MyText> <MyText style={tw`text-sm font-bold text-gray-700 mb-3 uppercase tracking-wider`}>Store Image</MyText>

View file

@ -34,7 +34,7 @@ const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
snippetCode: snippet?.snippetCode || '', snippetCode: snippet?.snippetCode || '',
slotId: snippet?.slotId?.toString() || '', slotId: snippet?.slotId?.toString() || '',
isPermanent: snippet?.isPermanent || false, isPermanent: snippet?.isPermanent || false,
productIds: snippet?.productIds?.map(id => id.toString()) || [], skuIds: snippet?.skuIds?.map(id => id.toString()) || [],
validTill: snippet?.validTill ? new Date(snippet.validTill) : null, validTill: snippet?.validTill ? new Date(snippet.validTill) : null,
}, },
validate: (values) => { validate: (values) => {
@ -55,8 +55,8 @@ const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
errors.slotId = 'Slot selection is required'; errors.slotId = 'Slot selection is required';
} }
if (values.productIds.length === 0) { if (values.skuIds.length === 0) {
errors.productIds = 'At least one product must be selected'; errors.skuIds = 'At least one product must be selected';
} }
return errors; return errors;
@ -68,7 +68,7 @@ const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
snippetCode: values.snippetCode, snippetCode: values.snippetCode,
slotId: values.isPermanent ? undefined : parseInt(values.slotId || '0'), slotId: values.isPermanent ? undefined : parseInt(values.slotId || '0'),
isPermanent: values.isPermanent, isPermanent: values.isPermanent,
productIds: values.productIds.map(id => parseInt(id)), skuIds: values.skuIds.map(id => parseInt(id)),
validTill: values.validTill ? values.validTill.toISOString() : undefined, validTill: values.validTill ? values.validTill.toISOString() : undefined,
}; };
@ -180,15 +180,15 @@ const VendorSnippetForm: React.FC<VendorSnippetFormProps> = ({
{/* Product Selection */} {/* Product Selection */}
<View> <View>
<ProductsSelector <ProductsSelector
value={formik.values.productIds.map(id => parseInt(id))} value={formik.values.skuIds.map(id => parseInt(id))}
onChange={(selectedProductIds) => formik.setFieldValue('productIds', (selectedProductIds as number[]).map(id => id.toString()))} onChange={(selectedProductIds) => formik.setFieldValue('skuIds', (selectedProductIds as number[]).map(id => id.toString()))}
multiple={true} multiple={true}
label="Select Products" label="Select Products"
placeholder="Select products" placeholder="Select products"
labelFormat={(product) => `${product.name} (${product.unit})`} labelFormat={(product) => product.label}
/> />
{formik.errors.productIds && formik.touched.productIds && ( {formik.errors.skuIds && formik.touched.skuIds && (
<MyText style={tw`text-red-500 text-sm mt-1`}>{formik.errors.productIds}</MyText> <MyText style={tw`text-red-500 text-sm mt-1`}>{formik.errors.skuIds}</MyText>
)} )}
</View> </View>

View file

@ -8,6 +8,10 @@
"distribution": "internal", "distribution": "internal",
"channel": "development" "channel": "development"
}, },
"dev": {
"distribution": "internal",
"channel": "dev"
},
"preview": { "preview": {
"distribution": "internal", "distribution": "internal",
"channel": "preview" "channel": "preview"

View file

@ -19,7 +19,7 @@
"@react-navigation/elements": "^2.3.8", "@react-navigation/elements": "^2.3.8",
"@react-navigation/material-top-tabs": "^7.4.11", "@react-navigation/material-top-tabs": "^7.4.11",
"@react-navigation/native": "^7.1.6", "@react-navigation/native": "^7.1.6",
"@tanstack/react-query": "^5.85.9", "@tanstack/react-query": "^5.100.0",
"@trpc/client": "^11.6.0", "@trpc/client": "^11.6.0",
"@trpc/react-query": "^11.6.0", "@trpc/react-query": "^11.6.0",
"axios": "^1.11.0", "axios": "^1.11.0",

View file

@ -83,9 +83,9 @@ export const NotificationProvider: React.FC<NotificationProviderProps> = ({
Notifications.addNotificationResponseReceivedListener((response) => { Notifications.addNotificationResponseReceivedListener((response) => {
const data = response.notification.request.content.data; const data = response.notification.request.content.data;
if (data && data.doctorId) { if (data && data.doctorId) {
router.push(`/(drawer)/dashboard`); router.navigate(`/(drawer)/dashboard`);
} else if (data && data.tokenId) { } else if (data && data.tokenId) {
router.push(`/(drawer)/dashboard`); router.navigate(`/(drawer)/dashboard`);
} }
}); });

View file

@ -4,7 +4,7 @@ export interface Banner {
name: string; name: string;
imageUrl: string; imageUrl: string;
description?: string; description?: string;
productId?: number; skuIds?: number[];
redirectUrl?: string; redirectUrl?: string;
serialNum: number; serialNum: number;
isActive: boolean; isActive: boolean;
@ -16,7 +16,7 @@ export interface CreateBannerPayload {
name: string; name: string;
imageUrl: string; imageUrl: string;
description?: string; description?: string;
productId?: number; skuIds?: number[];
redirectUrl?: string; redirectUrl?: string;
serialNum: number; serialNum: number;
} }

View file

@ -9,19 +9,27 @@ import { CreateCouponPayload } from 'common-ui/shared-types';
const USERS_PAGE_SIZE = 10; const USERS_PAGE_SIZE = 10;
interface CouponFormValues extends CreateCouponPayload {
isReservedCoupon?: boolean;
couponCodes: string[];
skuIds?: number[];
}
interface CouponFormProps { interface CouponFormProps {
onSubmit: (values: CreateCouponPayload & { isReservedCoupon?: boolean }) => void; onSubmit: (values: CouponFormValues) => void;
isLoading: boolean; isLoading: boolean;
initialValues?: Partial<CreateCouponPayload & { isReservedCoupon?: boolean }>; initialValues?: Partial<CouponFormValues>;
} }
const couponValidationSchema = Yup.object().shape({ const couponValidationSchema = Yup.object().shape({
isReservedCoupon: Yup.boolean().optional(), isReservedCoupon: Yup.boolean().optional(),
couponCode: Yup.string() couponCodes: Yup.array().of(
.required('Coupon code is required') Yup.string()
.min(3, 'Coupon code must be at least 3 characters') .required('Code is required')
.max(50, 'Coupon code cannot exceed 50 characters') .min(3, 'Code must be at least 3 characters')
.matches(/^[A-Z0-9_-]+$/, 'Coupon code can only contain uppercase letters, numbers, underscores, and hyphens'), .max(50, 'Code cannot exceed 50 characters')
.matches(/^[A-Z0-9_-]+$/, 'Code can only contain uppercase letters, numbers, underscores, and hyphens')
),
discountPercent: Yup.number() discountPercent: Yup.number()
.min(0, 'Must be positive') .min(0, 'Must be positive')
.max(100, 'Cannot exceed 100%') .max(100, 'Cannot exceed 100%')
@ -49,6 +57,18 @@ const couponValidationSchema = Yup.object().shape({
return this.createError({ message: 'Must provide either percentage or flat discount' }); return this.createError({ message: 'Must provide either percentage or flat discount' });
} }
return true; return true;
}).test('codes-required', 'At least one coupon code is required', function(value: any) {
const codes = (value.couponCodes || []).filter((c: string) => c && c.trim());
if (codes.length === 0) {
return this.createError({ path: 'couponCodes', message: 'Add at least one coupon code' });
}
return true;
}).test('codes-unique', 'Coupon codes must be unique', function(value: any) {
const codes = (value.couponCodes || []).map((c: string) => c.trim()).filter(Boolean);
if (new Set(codes).size !== codes.length) {
return this.createError({ path: 'couponCodes', message: 'Coupon codes must be unique' });
}
return true;
}); });
export default function CouponForm({ onSubmit, isLoading, initialValues }: CouponFormProps) { export default function CouponForm({ onSubmit, isLoading, initialValues }: CouponFormProps) {
@ -60,6 +80,10 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
const [hasMoreUsers, setHasMoreUsers] = useState(true); const [hasMoreUsers, setHasMoreUsers] = useState(true);
const [usersDropdownOpen, setUsersDropdownOpen] = useState(false); const [usersDropdownOpen, setUsersDropdownOpen] = useState(false);
// Add-multiple dialog states (for pattern codes like ABC12)
const [multiDialogOpen, setMultiDialogOpen] = useState(false);
const [multiCount, setMultiCount] = useState('');
const { data: usersData, isFetching: isFetchingUsers } = trpc.admin.coupon.getUsersMiniInfo.useQuery( const { data: usersData, isFetching: isFetchingUsers } = trpc.admin.coupon.getUsersMiniInfo.useQuery(
{ search: userSearchQuery, limit: USERS_PAGE_SIZE, offset: userOffset }, { search: userSearchQuery, limit: USERS_PAGE_SIZE, offset: userOffset },
{ enabled: usersDropdownOpen } { enabled: usersDropdownOpen }
@ -94,8 +118,8 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
// User search functionality will be inside Formik // User search functionality will be inside Formik
const defaultValues: CreateCouponPayload & { isReservedCoupon?: boolean } = { const defaultValues: CouponFormValues = {
couponCode: '', couponCodes: [''],
isUserBased: false, isUserBased: false,
isApplyForAll: false, isApplyForAll: false,
targetUsers: [], targetUsers: [],
@ -105,7 +129,7 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
maxValue: undefined, maxValue: undefined,
validTill: undefined, validTill: undefined,
maxLimitForUser: undefined, maxLimitForUser: undefined,
productIds: undefined, skuIds: undefined,
applicableUsers: [], applicableUsers: [],
applicableProducts: [], applicableProducts: [],
exclusiveApply: false, exclusiveApply: false,
@ -113,8 +137,8 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
}; };
return ( return (
<Formik <Formik<CouponFormValues>
initialValues={(initialValues || defaultValues) as CreateCouponPayload} initialValues={(initialValues || defaultValues) as CouponFormValues}
validationSchema={couponValidationSchema} validationSchema={couponValidationSchema}
onSubmit={onSubmit} onSubmit={onSubmit}
> >
@ -132,6 +156,34 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
const isReserved = (values as any).isReservedCoupon; const isReserved = (values as any).isReservedCoupon;
// Detect pattern codes like ABC12 (ends in digits) for bulk generation.
// Continue numbering from the highest code with the same prefix.
const patternCode = (values.couponCodes || []).find(
(c: string) => /^[A-Z0-9_-]*\d+$/.test(c.trim())
);
const patternPrefix = patternCode ? patternCode.replace(/\d+$/, '') : '';
const patternStart = (values.couponCodes || []).reduce((max, c) => {
const trimmed = c.trim();
if (!patternPrefix || !trimmed.startsWith(patternPrefix)) return max;
const m = trimmed.match(/\d+$/);
if (!m) return max;
return Math.max(max, parseInt(m[0], 10));
}, patternCode ? parseInt((patternCode.match(/\d+$/) || ['0'])[0], 10) : 0);
const handleAddMultiple = () => {
const count = parseInt(multiCount, 10);
if (!count || count < 1 || count > 100) return;
// Start from the next number after the highest existing code
const newCodes = Array.from(
{ length: count },
(_, i) => `${patternPrefix}${patternStart + 1 + i}`
);
const existing = (values.couponCodes || []).filter((c: string) => c && c.trim());
setFieldValue('couponCodes', [...existing, ...newCodes]);
setMultiDialogOpen(false);
setMultiCount('');
};
return ( return (
<AppContainer> <AppContainer>
{/* Is Reserved Coupon Checkbox */} {/* Is Reserved Coupon Checkbox */}
@ -143,17 +195,66 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
<MyText style={tw`ml-2 text-sm font-medium text-gray-700`}>Is Reserved Coupon</MyText> <MyText style={tw`ml-2 text-sm font-medium text-gray-700`}>Is Reserved Coupon</MyText>
</View> </View>
{/* Coupon Code */} {/* Coupon Codes */}
<View style={tw`mb-4`}> <View style={tw`mb-4`}>
<Text style={tw`text-base font-bold mb-1`}>Coupon Codes</Text>
<Text style={tw`text-xs text-gray-500 mb-2`}>
Each code creates a separate coupon with the same settings.
</Text>
{(values.couponCodes || []).map((code: string, index: number) => {
const codeError = Array.isArray(errors.couponCodes)
? (errors.couponCodes as any)[index]
: errors.couponCodes;
return (
<View key={index} style={tw`flex-row items-center mb-2`}>
<View style={tw`flex-1`}>
<MyTextInput <MyTextInput
topLabel="Coupon Code" topLabel={`Code ${index + 1}`}
placeholder="e.g., SAVE20" placeholder="e.g., SECRET10"
value={values.couponCode || ''} value={code}
onChangeText={(text: string) => setFieldValue('couponCode', text.toUpperCase())} onChangeText={(text: string) => {
const next = [...(values.couponCodes || [])];
next[index] = text.toUpperCase();
setFieldValue('couponCodes', next);
}}
keyboardType="default" keyboardType="default"
autoCapitalize="characters" autoCapitalize="characters"
error={!!(touched.couponCode && errors.couponCode)} error={!!codeError}
/> />
{codeError && <Text style={tw`text-red-500 text-xs mt-1`}>{codeError}</Text>}
</View>
<TouchableOpacity
onPress={() => {
const next = (values.couponCodes || []).filter((_: string, i: number) => i !== index);
setFieldValue('couponCodes', next.length > 0 ? next : ['']);
}}
style={tw`ml-2 p-2`}
>
<Text style={tw`text-red-500 font-bold text-lg`}>✕</Text>
</TouchableOpacity>
</View>
);
})}
{(errors.couponCodes as any)?.message && (
<Text style={tw`text-red-500 text-xs mb-2`}>{(errors.couponCodes as any).message}</Text>
)}
<View style={tw`mt-2 flex-row self-start`}>
<TouchableOpacity
onPress={() => setFieldValue('couponCodes', [...(values.couponCodes || []), ''])}
style={tw`py-2 px-3 bg-blue-50 rounded-lg border border-blue-200`}
>
<Text style={tw`text-blue-600 font-medium`}>+ Add Code</Text>
</TouchableOpacity>
{patternCode && (
<TouchableOpacity
onPress={() => setMultiDialogOpen(true)}
style={tw`ml-2 py-2 px-3 bg-green-50 rounded-lg border border-green-200`}
>
<Text style={tw`text-green-600 font-medium`}>Add Multiple</Text>
</TouchableOpacity>
)}
</View>
</View> </View>
{/* Discount Type Selection */} {/* Discount Type Selection */}
@ -226,7 +327,8 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
/> />
</View> </View>
{/* Maximum Discount Value */} {/* Maximum Discount Value - only for percentage discounts */}
{values.flatDiscount === undefined && (
<View style={tw`mb-4`}> <View style={tw`mb-4`}>
<MyTextInput <MyTextInput
topLabel="Maximum Discount Value" topLabel="Maximum Discount Value"
@ -237,6 +339,7 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
error={!!(touched.maxValue && errors.maxValue)} error={!!(touched.maxValue && errors.maxValue)}
/> />
</View> </View>
)}
{/* Validity Period */} {/* Validity Period */}
<View style={tw`mb-4`}> <View style={tw`mb-4`}>
@ -365,7 +468,39 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
</View> </View>
</BottomDialog> </BottomDialog>
{/* Add Multiple Coupons Dialog */}
<BottomDialog open={multiDialogOpen} onClose={() => setMultiDialogOpen(false)}>
<View style={tw`p-4`}>
<Text style={tw`text-lg font-semibold mb-1`}>Add Multiple Coupons</Text>
<Text style={tw`text-sm text-gray-500 mb-4`}>
Generate {patternCode ? `${patternPrefix}${patternStart + 1}, ${patternPrefix}${patternStart + 2}, ...` : 'sequential'} codes from your pattern
</Text>
<MyTextInput
topLabel="How many?"
placeholder="e.g., 10"
value={multiCount}
onChangeText={setMultiCount}
keyboardType="numeric"
/>
<View style={tw`flex-row mt-4`}>
<TouchableOpacity
onPress={() => {
setMultiDialogOpen(false);
setMultiCount('');
}}
style={tw`flex-1 p-3 rounded bg-gray-100 mr-2`}
>
<Text style={tw`text-gray-700 text-center font-semibold`}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={handleAddMultiple}
style={tw`flex-1 p-3 rounded bg-green-500`}
>
<Text style={tw`text-white text-center font-semibold`}>Generate</Text>
</TouchableOpacity>
</View>
</View>
</BottomDialog>

View file

@ -1,128 +1,245 @@
import React, { useState, useEffect, useCallback, forwardRef, useImperativeHandle, useMemo } from 'react'; import React, { useState, useImperativeHandle, forwardRef, useMemo } from 'react'
import { View, TouchableOpacity } from 'react-native'; import { View, TouchableOpacity, ScrollView, Alert } from 'react-native'
import { Formik, FieldArray } from 'formik'; import { Formik, FieldArray } from 'formik'
import * as Yup from 'yup'; import * as Yup from 'yup'
import { MyTextInput, BottomDropdown, MyText, useTheme, DatePicker, tw, useFocusCallback, Checkbox, ImageUploaderNeo, ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'common-ui'; import { MyTextInput, BottomDropdown, MyText, tw, ImageUploaderNeo, ImageUploaderNeoItem, ImageUploaderNeoPayload, Checkbox, InfoDialog } from 'common-ui'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { trpc } from '../trpc-client'; import { trpc } from '../trpc-client'
interface ProductFormData { interface Attribute {
name: string; featureName: string | null
shortDescription: string; featureValue: string
longDescription: string;
unitId: number;
storeId: number;
price: string;
marketPrice: string;
isSuspended: boolean;
isFlashAvailable: boolean;
flashPrice: string;
deals: Deal[];
tagIds: number[];
productQuantity: number;
} }
interface Deal { interface Variant {
quantity: string; id?: number
price: string; name: string
validTill: Date | null; price: string
marketPrice: string
isFlashAvailable: boolean
flashPrice: string
isOffer: boolean
isComboOnly: boolean
isDeleted?: boolean
isSuspended: boolean
attributes: Attribute[]
comboItems: { skuId: number | string }[]
}
interface ProductFormData {
name: string
shortDescription: string
longDescription: string
storeId: number
productType: 'item' | 'combo'
variants: Variant[]
} }
export interface ProductFormRef { export interface ProductFormRef {
clearImages: () => void; clearImages: () => void
} }
interface ProductFormProps { interface ProductFormProps {
mode: 'create' | 'edit'; mode: 'create' | 'edit'
initialValues: ProductFormData; initialValues: ProductFormData
onSubmit: (values: ProductFormData, images: ImageUploaderNeoPayload[], imagesToDelete: string[]) => void; onSubmit: (values: ProductFormData, variantImages: ImageUploaderNeoPayload[][], deletedImageKeys: string[]) => void
isLoading: boolean; isLoading: boolean
existingImages?: ImageUploaderNeoItem[]; existingVariantImages?: ImageUploaderNeoItem[][]
existingImageKeys?: string[]; existingVariantImageKeys?: string[][]
} }
const unitOptions = [ const defaultAttribute = (): Attribute => ({ featureName: '', featureValue: '' })
{ label: 'Kg', value: 1 },
{ label: 'Litre', value: 2 }, // The quantity feature is auto-added as the first attribute of every SKU.
{ label: 'Dozen', value: 3 }, const quantityAttribute = (): Attribute => ({ featureName: 'quantity', featureValue: '' })
{ label: 'Unit Piece', value: 4 },
]; const isQuantityFeature = (attr: Attribute): boolean =>
(attr.featureName ?? '').trim().toLowerCase() === 'quantity'
const defaultVariant = (): Variant => ({
id: undefined,
name: '',
price: '',
marketPrice: '',
isFlashAvailable: false,
flashPrice: '',
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
attributes: [quantityAttribute()],
comboItems: [],
})
const variantSignature = (attributes: Attribute[]): string =>
attributes
.map((a) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
.sort()
.join('|')
const productValidationSchema = Yup.object().shape({
name: Yup.string().required('Product name is required'),
storeId: Yup.number().required('Store is required').min(1, 'Store is required'),
productType: Yup.string().oneOf(['item', 'combo'], 'Product type is required').required('Product type is required'),
variants: Yup.array()
.min(1, 'At least one variant is required')
.of(
Yup.object().shape({
price: Yup.number()
.typeError('Price must be a number')
.positive('Price must be a positive number')
.required('Price is required'),
marketPrice: Yup.number()
.typeError('Market price must be a number')
.min(0, 'Market price cannot be negative')
.nullable()
.transform((value, originalValue) => (originalValue === '' ? null : value))
.optional(),
flashPrice: Yup.number()
.typeError('Flash price must be a number')
.min(0, 'Flash price cannot be negative')
.nullable()
.transform((value, originalValue) => (originalValue === '' ? null : value))
.optional(),
attributes: Yup.array()
.min(1, 'At least one attribute is required')
.of(
Yup.object().shape({
featureValue: Yup.string().required('Value is required'),
})
),
})
)
.test('unique-variants', 'Two variants have the same attributes', function (variants) {
if (!Array.isArray(variants)) return true
const seen = new Set<string>()
for (const variant of variants) {
const attrs = variant?.attributes || []
const signature = variantSignature(attrs as Attribute[])
if (seen.has(signature)) {
return this.createError({ message: 'Two variants have the same attributes' })
}
seen.add(signature)
}
return true
})
.test('quantity-feature', 'Each SKU must have exactly one quantity feature', function (variants) {
if (!Array.isArray(variants)) return true
for (const variant of variants) {
const attrs = variant?.attributes || []
const quantityCount = attrs.filter(
(a) => ((a as Attribute)?.featureName ?? '').trim().toLowerCase() === 'quantity'
).length
if (quantityCount === 0) {
return this.createError({ message: 'Every SKU must have a quantity feature' })
}
if (quantityCount > 1) {
return this.createError({ message: 'Each SKU can have only one quantity feature' })
}
}
return true
}),
})
// Collect every string message from a Formik errors tree (objects, arrays, strings).
// Variant-level errors (e.g. 'Each SKU can have only one quantity feature') can get
// hidden by Formik when index-level errors are also present, so we walk everything.
const collectErrorMessages = (errors: unknown, depth = 0): string[] => {
if (depth > 6) return []
if (typeof errors === 'string') return [errors]
if (Array.isArray(errors)) return errors.flatMap((e) => collectErrorMessages(e, depth + 1))
if (errors && typeof errors === 'object') {
return Object.values(errors).flatMap((e) => collectErrorMessages(e, depth + 1))
}
return []
}
const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
mode, mode,
initialValues, initialValues,
onSubmit, onSubmit,
isLoading, isLoading,
existingImages:existingImagesRaw, existingVariantImages = [],
existingImageKeys = [], existingVariantImageKeys = [],
}, ref) => { }, ref) => {
const { theme } = useTheme(); const [variantImages, setVariantImages] = useState<ImageUploaderNeoItem[][]>(() =>
const [images, setImages] = useState<ImageUploaderNeoItem[]>([]); initialValues.variants.length > 0
? initialValues.variants.map((_, i) => existingVariantImages[i] || [])
: [[]]
)
const existingImages = existingImagesRaw || [] useImperativeHandle(ref, () => ({
// Sync images state when existingImages prop changes (e.g., when async query data arrives) clearImages: () => setVariantImages(initialValues.variants.map(() => [])),
useEffect(() => { }), [initialValues.variants])
setImages(existingImages);
}, [existingImagesRaw]);
const { data: storesData } = trpc.common.getStoresSummary.useQuery(); const { data: storesData } = trpc.common.getStoresSummary.useQuery()
const storeOptions = storesData?.stores.map(store => ({ const storeOptions = storesData?.stores.map((store) => ({
label: store.name, label: store.name,
value: store.id, value: store.id,
})) || []; })) || []
const { data: tagsData } = trpc.admin.product.getProductTags.useQuery(); const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery({})
const tagOptions = tagsData?.tags.map(tag => ({ const skuOptions = (skusData?.skus || []).map((sku) => ({
label: tag.tagName, label: sku.label,
value: tag.id.toString(), value: sku.id.toString(),
})) || []; }))
// Build signed URL -> S3 key mapping for existing images // Make sure every SKU starts with a 'quantity' feature (auto-added at the
const signedUrlToKey = useMemo(() => { // beginning if the provided initial values don't have one).
const map: Record<string, string> = {}; const formInitialValues = useMemo(() => {
existingImages.forEach((img, i) => { return {
if (existingImageKeys[i]) { ...initialValues,
map[img.imgUrl] = existingImageKeys[i]; variants: (initialValues.variants || []).map((v) => {
const hasQuantity = (v.attributes || []).some(
(a) => (a.featureName ?? '').trim().toLowerCase() === 'quantity'
)
if (hasQuantity) return v
return { ...v, attributes: [quantityAttribute(), ...(v.attributes || [])] }
}),
} }
}); }, [initialValues])
return map;
}, [existingImages, existingImageKeys]);
return ( return (
<Formik <Formik
initialValues={initialValues} initialValues={formInitialValues}
validationSchema={productValidationSchema}
onSubmit={(values) => { onSubmit={(values) => {
// New images have mimeType set, existing images have mimeType === null // Normalize feature names before sending to backend: the mandatory
const newImages = images.filter(img => img.mimeType !== null); // 'quantity' feature must always go out lowercase (case-insensitive
const deletedImageKeys = existingImages // matching means 'Quantity'/'QUANTITY' are treated the same), and
.filter(existing => !images.some(current => current.imgUrl === existing.imgUrl)) // names are trimmed like the backend does.
.map(deleted => signedUrlToKey[deleted.imgUrl]) const normalizedValues: ProductFormData = {
.filter(Boolean); ...values,
variants: values.variants.map((v) => ({
onSubmit( ...v,
values, attributes: v.attributes.map((a) => ({
newImages.map(img => ({ url: img.imgUrl, mimeType: img.mimeType })), ...a,
deletedImageKeys, featureName: isQuantityFeature(a) ? 'quantity' : (a.featureName ?? '').trim() || null,
); })),
})),
}
const images = variantImages.map((imgs) =>
imgs.map((img) => ({ url: img.imgUrl, mimeType: img.mimeType }))
)
const deletedKeys: string[] = []
if (mode === 'edit') {
variantImages.forEach((currentImgs, vIndex) => {
const existing = existingVariantImages[vIndex] || []
existing.forEach((existingImg) => {
if (!currentImgs.some((cur) => cur.imgUrl === existingImg.imgUrl)) {
const key = existingVariantImageKeys[vIndex]?.[existingVariantImages[vIndex]?.indexOf(existingImg)]
if (key) deletedKeys.push(key)
}
})
})
}
onSubmit(normalizedValues, images, deletedKeys)
}} }}
enableReinitialize enableReinitialize
> >
{({ handleChange, handleSubmit, values, setFieldValue, resetForm }) => { {({ handleChange, handleSubmit, values, setFieldValue, validateForm }) => {
const clearForm = useCallback(() => {
setImages([]);
resetForm();
}, [resetForm]);
useFocusCallback(clearForm);
useImperativeHandle(ref, () => ({
clearImages: clearForm,
}), [clearForm]);
const submit = () => handleSubmit();
return ( return (
<View> <ScrollView style={tw`flex-1`} contentContainerStyle={tw`pb-10`}>
<MyTextInput <MyTextInput
topLabel="Product Name" topLabel="Product Name"
placeholder="Enter product name" placeholder="Enter product name"
@ -148,31 +265,6 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
onChangeText={handleChange('longDescription')} onChangeText={handleChange('longDescription')}
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
/> />
<ImageUploaderNeo
images={images}
onImageAdd={(payloads) => setImages(prev => [...prev, ...payloads.map(p => ({ imgUrl: p.url, mimeType: p.mimeType }))])}
onImageRemove={(payload) => setImages(prev => prev.filter(img => img.imgUrl !== payload.url))}
allowMultiple={true}
/>
<BottomDropdown
topLabel='Unit'
label="Unit"
value={values.unitId}
options={unitOptions}
onValueChange={(value) => setFieldValue('unitId', value)}
placeholder="Select unit"
style={{ marginBottom: 16 }}
/>
<MyTextInput
topLabel="Product Quantity"
placeholder="Enter product quantity"
keyboardType="numeric"
value={values.productQuantity.toString()}
onChangeText={(text) => setFieldValue('productQuantity', text)}
style={{ marginBottom: 16 }}
/>
<BottomDropdown <BottomDropdown
topLabel="Store" topLabel="Store"
label="Store" label="Store"
@ -182,81 +274,345 @@ const ProductForm = forwardRef<ProductFormRef, ProductFormProps>(({
placeholder="Select store" placeholder="Select store"
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
/> />
<BottomDropdown <BottomDropdown
topLabel="Tags" topLabel="Product Type"
label="Tags" label="Product Type"
value={values.tagIds.map(id => id.toString())} value={values.productType}
options={tagOptions} options={[
onValueChange={(value) => setFieldValue('tagIds', (value as string[]).map(id => parseInt(id)))} { label: 'Item', value: 'item' },
multiple={true} { label: 'Combo', value: 'combo' },
placeholder="Select tags" ]}
style={{ marginBottom: 16 }} onValueChange={(value) => setFieldValue('productType', value)}
/> placeholder="Select product type"
<MyTextInput
topLabel="Unit Price"
placeholder="Enter unit price"
keyboardType="numeric"
value={values.price}
onChangeText={handleChange('price')}
style={{ marginBottom: 16 }}
/>
<MyTextInput
topLabel="Market Price (Optional)"
placeholder="Enter market price"
keyboardType="numeric"
value={values.marketPrice}
onChangeText={handleChange('marketPrice')}
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
/> />
<View style={tw`flex-row items-center mb-4`}> <FieldArray name="variants">
<Checkbox {({ push, remove }) => (
checked={values.isSuspended} <View>
onPress={() => setFieldValue('isSuspended', !values.isSuspended)} <View style={tw`flex-row justify-between items-center mb-3`}>
style={tw`mr-3`} <MyText style={tw`text-lg font-bold text-gray-800`}>Variants</MyText>
/> <TouchableOpacity
<MyText style={tw`text-gray-700 font-medium`}>Suspend Product</MyText> onPress={() => {
push(defaultVariant())
setVariantImages((prev) => [...prev, []])
}}
style={tw`bg-blue-500 px-3 py-1 rounded-lg flex-row items-center`}
>
<MaterialIcons name="add" size={18} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Add Variant</MyText>
</TouchableOpacity>
</View> </View>
<View style={tw`flex-row items-center mb-4`}> {values.variants.map((variant, vIndex) => {
<Checkbox const isExistingSku = variant.id != null
checked={values.isFlashAvailable} const isMarkedDeleted = !!variant.isDeleted
return (
<View key={vIndex} style={[tw`border border-gray-300 rounded-xl p-4 mb-4`, isMarkedDeleted && tw`border-red-300 bg-red-50/50 opacity-80`]}>
<View style={tw`flex-row justify-between items-center mb-3`}>
<View style={tw`flex-row items-center`}>
<MyText style={tw`font-bold text-gray-700`}>Variant {vIndex + 1}</MyText>
{isMarkedDeleted && (
<View style={tw`ml-2 px-2 py-0.5 rounded-full bg-red-100 border border-red-200`}>
<MyText style={tw`text-[10px] font-bold text-red-700 uppercase`}>Deleted</MyText>
</View>
)}
</View>
{(values.variants.length > 1 || isExistingSku) && (
<TouchableOpacity
onPress={() => { onPress={() => {
setFieldValue('isFlashAvailable', !values.isFlashAvailable); if (isExistingSku) {
if (values.isFlashAvailable) setFieldValue('flashPrice', ''); // Mark existing SKU as deleted (sent to backend on save).
setFieldValue(`variants.${vIndex}.isDeleted`, !isMarkedDeleted)
} else {
remove(vIndex)
setVariantImages((prev) => prev.filter((_, i) => i !== vIndex))
}
}}
>
<MaterialIcons
name={isMarkedDeleted ? 'restore' : 'delete'}
size={20}
color={isMarkedDeleted ? '#10B981' : '#EF4444'}
/>
</TouchableOpacity>
)}
</View>
<MyTextInput
topLabel="SKU Name (optional)"
placeholder="Overrides the auto-generated name"
value={variant.name ?? ''}
onChangeText={handleChange(`variants.${vIndex}.name`)}
style={{ marginBottom: 12 }}
/>
<FieldArray name={`variants.${vIndex}.attributes`}>
{({ push: pushAttr, remove: removeAttr }) => (
<View style={tw`mb-3`}>
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`font-medium text-gray-600`}>Attributes</MyText>
<TouchableOpacity
onPress={() => pushAttr(defaultAttribute())}
style={tw`bg-gray-200 px-2 py-0.5 rounded flex-row items-center`}
>
<MaterialIcons name="add" size={14} color="#4B5563" />
<MyText style={tw`text-gray-600 text-xs ml-0.5`}>Add</MyText>
</TouchableOpacity>
</View>
{variant.attributes.map((attr, aIndex) => {
const quantityCount = variant.attributes.filter(isQuantityFeature).length
// Quantity features are locked (non-editable), but if there
// are duplicates (e.g. 'quantity' + 'Quantity') the user must
// be able to delete the extras to fix the form.
const canDelete = variant.attributes.length > 1 && (!isQuantityFeature(attr) || quantityCount > 1)
return (
<View key={aIndex} style={tw`flex-row items-center mb-2 gap-2`}>
<View style={tw`flex-1`}>
<MyTextInput
placeholder="Name"
value={attr.featureName ?? ''}
onChangeText={(text) =>
setFieldValue(
`variants.${vIndex}.attributes.${aIndex}.featureName`,
text.trim().toLowerCase() === 'quantity' ? 'quantity' : text
)
}
editable={!isQuantityFeature(attr)}
style={isQuantityFeature(attr) ? tw`text-gray-400` : undefined}
/>
</View>
<View style={tw`flex-1`}>
<MyTextInput
placeholder={isQuantityFeature(attr) ? 'e.g. 0.5 kg' : 'Value'}
value={attr.featureValue}
onChangeText={handleChange(`variants.${vIndex}.attributes.${aIndex}.featureValue`)}
/>
</View>
{canDelete && (
<TouchableOpacity onPress={() => removeAttr(aIndex)}>
<MaterialIcons name="close" size={18} color="#EF4444" />
</TouchableOpacity>
)}
</View>
)
})}
<View style={tw`flex-row items-center self-start`}>
<TouchableOpacity
onPress={() => pushAttr(defaultAttribute())}
style={tw`bg-gray-200 px-2 py-0.5 rounded flex-row items-center`}
>
<MaterialIcons name="add" size={14} color="#4B5563" />
<MyText style={tw`text-gray-600 text-xs ml-0.5`}>Add Feature</MyText>
</TouchableOpacity>
<InfoDialog
message="Quantity is mandatory feature. Add other features optionally with name. Features become part of name — ex: a feature with Mini as value becomes <ItemName> Mini"
style={tw`ml-1`}
/>
</View>
</View>
)}
</FieldArray>
<View style={tw`flex-row gap-2 mb-3`}>
<View style={tw`flex-1`}>
<MyTextInput
topLabel="Market Price"
placeholder="MRP"
keyboardType="numeric"
value={variant.marketPrice}
onChangeText={handleChange(`variants.${vIndex}.marketPrice`)}
/>
</View>
<View style={tw`flex-1`}>
<MyTextInput
topLabel="Our Price"
placeholder="Selling price"
keyboardType="numeric"
value={variant.price}
onChangeText={handleChange(`variants.${vIndex}.price`)}
/>
</View>
</View>
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
checked={variant.isFlashAvailable}
onPress={() => {
setFieldValue(`variants.${vIndex}.isFlashAvailable`, !variant.isFlashAvailable)
if (variant.isFlashAvailable) setFieldValue(`variants.${vIndex}.flashPrice`, '')
}} }}
style={tw`mr-3`} style={tw`mr-3`}
/> />
<MyText style={tw`text-gray-700 font-medium`}>Flash Available</MyText> <MyText style={tw`text-gray-700 font-medium`}>Flash Available</MyText>
</View> </View>
{values.isFlashAvailable && ( <View style={tw`flex-row items-center mb-3`}>
<Checkbox
checked={variant.isOffer}
onPress={() => setFieldValue(`variants.${vIndex}.isOffer`, !variant.isOffer)}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Offer SKU</MyText>
</View>
{!(values.productType === 'combo' && (variant.comboItems?.length || 0) > 0) && (
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
checked={variant.isComboOnly}
onPress={() => setFieldValue(`variants.${vIndex}.isComboOnly`, !variant.isComboOnly)}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Combo Only SKU</MyText>
</View>
)}
{mode === 'edit' && (
<View style={tw`flex-row items-center mb-3`}>
<Checkbox
checked={variant.isSuspended}
onPress={() => setFieldValue(`variants.${vIndex}.isSuspended`, !variant.isSuspended)}
style={tw`mr-3`}
/>
<MyText style={tw`text-gray-700 font-medium`}>Suspend SKU</MyText>
</View>
)}
{variant.isFlashAvailable && (
<MyTextInput <MyTextInput
topLabel="Flash Price" topLabel="Flash Price"
placeholder="Enter flash price" placeholder="Enter flash price"
keyboardType="numeric" keyboardType="numeric"
value={values.flashPrice} value={variant.flashPrice}
onChangeText={handleChange('flashPrice')} onChangeText={handleChange(`variants.${vIndex}.flashPrice`)}
style={{ marginBottom: 16 }} style={{ marginBottom: 12 }}
/> />
)} )}
<ImageUploaderNeo
images={variantImages[vIndex] || []}
onImageAdd={(payloads) =>
setVariantImages((prev) => {
const next = [...prev]
next[vIndex] = [...(next[vIndex] || []), ...payloads.map((p) => ({ imgUrl: p.url, mimeType: p.mimeType }))]
return next
})
}
onImageRemove={(payload) =>
setVariantImages((prev) => {
const next = [...prev]
next[vIndex] = (next[vIndex] || []).filter((img) => img.imgUrl !== payload.url)
return next
})
}
allowMultiple={true}
/>
{values.productType === 'combo' && (
<View style={tw`mt-3 pt-3 border-t border-gray-100`}>
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`font-medium text-gray-600`}>Included Items</MyText>
<TouchableOpacity <TouchableOpacity
onPress={submit} onPress={() => {
disabled={isLoading} const items = variant.comboItems || []
style={tw`px-4 py-2 rounded-lg shadow-lg items-center mt-2 ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`} items.push({ skuId: '' })
setFieldValue(`variants.${vIndex}.comboItems`, items)
}}
style={tw`bg-gray-200 px-2 py-0.5 rounded flex-row items-center`}
> >
<MyText style={tw`text-white text-lg font-bold`}> <MaterialIcons name="add" size={14} color="#4B5563" />
{isLoading ? (mode === 'create' ? 'Creating...' : 'Updating...') : (mode === 'create' ? 'Create Product' : 'Update Product')} <MyText style={tw`text-gray-600 text-xs ml-0.5`}>Add</MyText>
</MyText>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
); {variant.comboItems?.map((ci, cIndex) => (
<View key={cIndex} style={tw`flex-row items-center gap-2 mb-2`}>
<View style={tw`flex-1`}>
<BottomDropdown
label="SKU"
value={ci.skuId}
options={skuOptions.map((opt: { label: string; value: string }) => ({
...opt,
// Disable SKUs already picked in another row of this combo.
disabled: (variant.comboItems || []).some(
(item, idx) => idx !== cIndex && String(item.skuId) === String(opt.value)
),
}))}
onValueChange={(val) => {
const current = variant.comboItems || []
const isDuplicate = current.some(
(item, idx) => idx !== cIndex && String(item.skuId) === String(val)
)
if (isDuplicate) {
Alert.alert('Duplicate', 'This product is already in the combo')
return
}
setFieldValue(`variants.${vIndex}.comboItems.${cIndex}.skuId`, val)
}}
placeholder="Select SKU"
/>
</View>
<TouchableOpacity
onPress={() => {
const items = variant.comboItems.filter((_, i) => i !== cIndex)
setFieldValue(`variants.${vIndex}.comboItems`, items)
}}
>
<MaterialIcons name="close" size={18} color="#EF4444" />
</TouchableOpacity>
</View>
))}
</View>
)}
</View>
)
})}
<TouchableOpacity
onPress={() => {
push(defaultVariant())
setVariantImages((prev) => [...prev, []])
}}
style={tw`bg-blue-500 px-3 py-2 rounded-lg flex-row items-center justify-center mb-4`}
>
<MaterialIcons name="add" size={18} color="white" />
<MyText style={tw`text-white font-semibold ml-1`}>Add Variant</MyText>
</TouchableOpacity>
</View>
)}
</FieldArray>
<TouchableOpacity
onPress={async () => {
const validationErrors = await validateForm()
if (Object.keys(validationErrors).length > 0) {
const variantsMessages = collectErrorMessages(validationErrors.variants)
const allMessages = collectErrorMessages(validationErrors)
const message = variantsMessages[0] || allMessages[0] || 'Please fix the highlighted fields'
Alert.alert('Check your form', String(message))
return
}
handleSubmit()
}}
disabled={isLoading}
style={tw`px-4 py-3 rounded-lg shadow-lg items-center mt-4 ${isLoading ? 'bg-gray-400' : 'bg-blue-500'}`}
>
<MyText style={tw`text-white text-lg font-bold`}>
{(() => {
if (mode === 'edit') {
return isLoading ? 'Saving...' : 'Save Changes'
}
return isLoading ? 'Creating...' : 'Create Product'
})()}
</MyText>
</TouchableOpacity>
</ScrollView>
)
}} }}
</Formik> </Formik>
); )
}); })
ProductForm.displayName = 'ProductForm'; ProductForm.displayName = 'ProductForm'
export default ProductForm; export default ProductForm

View file

@ -1,9 +1,14 @@
import React, { useState, useEffect, forwardRef, useCallback } from 'react'; import React, { useState, useEffect, forwardRef, useCallback } from 'react';
import { View, TouchableOpacity } from 'react-native'; import { View, TouchableOpacity, StyleSheet } from 'react-native';
import { Formik } from 'formik'; import { Formik } from 'formik';
import * as Yup from 'yup'; import * as Yup from 'yup';
import { MyTextInput, MyText, Checkbox, ImageUploaderNeo, tw, useFocusCallback, BottomDropdown, type ImageUploaderNeoItem, type ImageUploaderNeoPayload } from 'common-ui'; import { MyTextInput, MyText, Checkbox, ImageUploaderNeo, tw, useFocusCallback, BottomDropdown, type ImageUploaderNeoItem, type ImageUploaderNeoPayload } from 'common-ui';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { TouchableOpacity as GHTouchableOpacity } from 'react-native-gesture-handler';
import DraggableFlatList, { ScaleDecorator } from 'react-native-draggable-flatlist';
import { Image } from 'expo-image';
import ProductsSelector from '@/components/ProductsSelector';
import { trpc } from '@/src/trpc-client';
interface StoreOption { interface StoreOption {
id: number; id: number;
@ -15,6 +20,7 @@ interface TagFormData {
tagDescription: string; tagDescription: string;
isDashboardTag: boolean; isDashboardTag: boolean;
relatedStores: number[]; relatedStores: number[];
productIds: number[];
} }
interface TagFormProps { interface TagFormProps {
@ -26,6 +32,13 @@ interface TagFormProps {
stores?: StoreOption[]; stores?: StoreOption[];
} }
interface SelectedProduct {
skuId: number;
productId: number;
label: string;
imageUrl?: string | null;
}
const TagForm = forwardRef<any, TagFormProps>(({ const TagForm = forwardRef<any, TagFormProps>(({
mode, mode,
initialValues, initialValues,
@ -37,10 +50,35 @@ const TagForm = forwardRef<any, TagFormProps>(({
const [images, setImages] = useState<ImageUploaderNeoItem[]>([]) const [images, setImages] = useState<ImageUploaderNeoItem[]>([])
const [removedExisting, setRemovedExisting] = useState(false) const [removedExisting, setRemovedExisting] = useState(false)
const [isDashboardTagChecked, setIsDashboardTagChecked] = useState<boolean>(Boolean(initialValues.isDashboardTag)); const [isDashboardTagChecked, setIsDashboardTagChecked] = useState<boolean>(Boolean(initialValues.isDashboardTag));
const [selectedProducts, setSelectedProducts] = useState<SelectedProduct[]>([]);
const existingImageUrl = existingImageUrlRaw || '' const existingImageUrl = existingImageUrlRaw || ''
const stores = storesRaw || [] const stores = storesRaw || []
const { data: skusData } = trpc.common.product.getAllSkusSummary.useQuery();
const allSkus: SelectedProduct[] = (skusData?.skus || []).map((sku: any) => ({
skuId: sku.id,
productId: sku.productId,
label: sku.label,
imageUrl: sku.images?.[0] || null,
}));
// Build the ordered list from initialValues.productIds (product ids, in sortOrder).
useEffect(() => {
const ordered: SelectedProduct[] = [];
const skuMap = new Map<number, SelectedProduct>();
for (const sku of allSkus) {
skuMap.set(sku.productId, sku);
}
for (const productId of initialValues.productIds || []) {
const sku = skuMap.get(productId);
if (sku) ordered.push(sku);
else ordered.push({ skuId: 0, productId, label: `Product #${productId}`, imageUrl: null });
}
setSelectedProducts(ordered);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialValues.productIds, skusData]);
// Update checkbox when initial values change // Update checkbox when initial values change
useEffect(() => { useEffect(() => {
setIsDashboardTagChecked(Boolean(initialValues.isDashboardTag)); setIsDashboardTagChecked(Boolean(initialValues.isDashboardTag));
@ -52,7 +90,6 @@ const TagForm = forwardRef<any, TagFormProps>(({
setRemovedExisting(false) setRemovedExisting(false)
}, [existingImageUrlRaw, initialValues.isDashboardTag]); }, [existingImageUrlRaw, initialValues.isDashboardTag]);
const validationSchema = Yup.object().shape({ const validationSchema = Yup.object().shape({
tagName: Yup.string() tagName: Yup.string()
.required('Tag name is required') .required('Tag name is required')
@ -62,21 +99,74 @@ const TagForm = forwardRef<any, TagFormProps>(({
.max(500, 'Description must be less than 500 characters'), .max(500, 'Description must be less than 500 characters'),
}); });
// When a product is picked in the selector, add it to the ordered list (if not already present).
const handleProductSelect = (value: number | number[]) => {
const skuIds = Array.isArray(value) ? value : [value];
setSelectedProducts((prev) => {
const next = [...prev];
for (const skuId of skuIds) {
if (next.some((p) => p.skuId === skuId)) continue;
const sku = allSkus.find((s) => s.skuId === skuId);
if (sku) next.push(sku);
}
return next;
});
};
const handleDragEnd = useCallback(({ data }: { data: SelectedProduct[] }) => {
setSelectedProducts(data);
}, []);
const handleRemoveProduct = (productId: number) => {
setSelectedProducts((prev) => prev.filter((p) => p.productId !== productId));
};
const renderSelectedItem = useCallback(({ item, drag, isActive }: { item: SelectedProduct; drag: () => void; isActive: boolean }) => (
<ScaleDecorator>
<GHTouchableOpacity
onLongPress={drag}
disabled={isActive}
activeOpacity={1}
style={[styles.item, isActive && styles.activeItem]}
>
<View style={styles.dragHandle}>
<MaterialIcons name="drag-indicator" size={24} color={isActive ? '#3b82f6' : '#9ca3af'} />
</View>
{item.imageUrl ? (
<Image source={{ uri: item.imageUrl }} style={styles.image} contentFit="cover" />
) : (
<View style={styles.placeholderImage}>
<MaterialIcons name="image" size={24} color="#9ca3af" />
</View>
)}
<MyText style={styles.name} numberOfLines={1}>
{item.label}
</MyText>
<TouchableOpacity onPress={() => handleRemoveProduct(item.productId)} style={styles.removeButton}>
<MaterialIcons name="close" size={18} color="#9ca3af" />
</TouchableOpacity>
</GHTouchableOpacity>
</ScaleDecorator>
), []);
return ( return (
<Formik <Formik
initialValues={initialValues} initialValues={initialValues}
validationSchema={validationSchema} validationSchema={validationSchema}
onSubmit={(values) => onSubmit(values, images, removedExisting)} onSubmit={(values) => onSubmit({ ...values, productIds: selectedProducts.map((p) => p.productId) }, images, removedExisting)}
enableReinitialize enableReinitialize
> >
{({ handleChange, handleSubmit, values, setFieldValue, errors, touched, setFieldValue: formikSetFieldValue, resetForm }) => { {({ handleChange, handleSubmit, values, setFieldValue, errors, touched, resetForm }) => {
// Clear form when screen comes into focus // Clear form when screen comes into focus (create mode only — edit keeps its loaded products)
const clearForm = useCallback(() => { const clearForm = useCallback(() => {
setImages([]) setImages([])
setRemovedExisting(false) setRemovedExisting(false)
setIsDashboardTagChecked(false); setIsDashboardTagChecked(false);
if (mode === 'create') {
setSelectedProducts([]);
}
resetForm(); resetForm();
}, [resetForm]); }, [resetForm, mode]);
useFocusCallback(clearForm); useFocusCallback(clearForm);
@ -106,7 +196,6 @@ const TagForm = forwardRef<any, TagFormProps>(({
Tag Image {mode === 'edit' ? '(Upload new to replace)' : '(Optional)'} Tag Image {mode === 'edit' ? '(Upload new to replace)' : '(Optional)'}
</MyText> </MyText>
<ImageUploaderNeo <ImageUploaderNeo
images={images} images={images}
onImageAdd={(payload: ImageUploaderNeoPayload[]) => { onImageAdd={(payload: ImageUploaderNeoPayload[]) => {
@ -132,7 +221,7 @@ const TagForm = forwardRef<any, TagFormProps>(({
onPress={() => { onPress={() => {
const newValue = !isDashboardTagChecked; const newValue = !isDashboardTagChecked;
setIsDashboardTagChecked(newValue); setIsDashboardTagChecked(newValue);
formikSetFieldValue('isDashboardTag', newValue); setFieldValue('isDashboardTag', newValue);
}} }}
/> />
<MyText style={tw`ml-3 text-gray-800`}>Mark as Dashboard Tag</MyText> <MyText style={tw`ml-3 text-gray-800`}>Mark as Dashboard Tag</MyText>
@ -153,12 +242,53 @@ const TagForm = forwardRef<any, TagFormProps>(({
}))} }))}
onValueChange={(selectedValues) => { onValueChange={(selectedValues) => {
const numericValues = (selectedValues as string[]).map(v => parseInt(v)); const numericValues = (selectedValues as string[]).map(v => parseInt(v));
formikSetFieldValue('relatedStores', numericValues); setFieldValue('relatedStores', numericValues);
}} }}
multiple={true} multiple={true}
/> />
</View> </View>
{/* Products Section: selector + reorderable list */}
<View style={tw`mb-6`}>
<MyText style={tw`text-lg font-bold mb-2 text-gray-800`}>
Products
</MyText>
<ProductsSelector
value={[]}
onChange={handleProductSelect}
multiple
label="Select Products"
placeholder="Search and select products..."
showGroups={false}
/>
<View style={tw`mt-4`}>
{selectedProducts.length > 0 && (
<View style={tw`bg-blue-50 px-4 py-2 mb-2 rounded-lg`}>
<MyText style={tw`text-blue-700 text-xs text-center`}>
Long press and drag to reorder • {selectedProducts.length} items
</MyText>
</View>
)}
{selectedProducts.length > 0 ? (
<DraggableFlatList
data={selectedProducts}
renderItem={renderSelectedItem}
keyExtractor={(item) => item.productId.toString()}
onDragEnd={handleDragEnd}
showsVerticalScrollIndicator={false}
contentContainerStyle={{ paddingBottom: 20 }}
keyboardShouldPersistTaps="handled"
activationDistance={10}
/>
) : (
<View style={tw`bg-gray-50 p-6 rounded-xl border border-gray-200 border-dashed items-center justify-center`}>
<MaterialIcons name="inventory" size={32} color="#9CA3AF" />
<MyText style={tw`text-gray-500 mt-2 text-sm`}>No products selected yet</MyText>
</View>
)}
</View>
</View>
<TouchableOpacity <TouchableOpacity
onPress={() => handleSubmit()} onPress={() => handleSubmit()}
disabled={isLoading} disabled={isLoading}
@ -175,6 +305,62 @@ const TagForm = forwardRef<any, TagFormProps>(({
); );
}); });
const styles = StyleSheet.create({
item: {
backgroundColor: 'white',
borderRadius: 8,
borderWidth: 1,
borderColor: '#e5e7eb',
padding: 10,
flexDirection: 'row',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 2,
marginVertical: 4,
},
activeItem: {
shadowColor: '#3b82f6',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 8,
borderColor: '#3b82f6',
transform: [{ scale: 1.02 }],
},
dragHandle: {
marginRight: 8,
padding: 2,
},
image: {
width: 30,
height: 30,
borderRadius: 6,
marginRight: 10,
},
placeholderImage: {
width: 30,
height: 30,
borderRadius: 6,
backgroundColor: '#f3f4f6',
marginRight: 10,
alignItems: 'center',
justifyContent: 'center',
},
name: {
flex: 1,
fontSize: 13,
color: '#111827',
fontWeight: '500',
marginRight: 4,
},
removeButton: {
padding: 2,
},
});
TagForm.displayName = 'TagForm'; TagForm.displayName = 'TagForm';
export default TagForm; export default TagForm;

View file

@ -34,7 +34,7 @@ export const TagMenu: React.FC<TagMenuProps> = ({
const handleEditTag = () => { const handleEditTag = () => {
setIsOpen(false); setIsOpen(false);
router.push(`/product-tags/edit?tagId=${tagId}`); router.push(`/(drawer)/dashboard/product-tags/edit?tagId=${tagId}`);
}; };
const handleDeleteTag = () => { const handleDeleteTag = () => {

View file

@ -8,7 +8,7 @@ export interface VendorSnippet {
snippetCode: string; snippetCode: string;
slotId: number | null; slotId: number | null;
isPermanent: boolean; isPermanent: boolean;
productIds: number[]; skuIds: number[];
products: VendorSnippetProduct[]; products: VendorSnippetProduct[];
validTill: string | null; validTill: string | null;
createdAt: string; createdAt: string;
@ -28,7 +28,7 @@ export interface VendorSnippetForm {
snippetCode: string; snippetCode: string;
slotId: number; slotId: number;
isPermanent: boolean; isPermanent: boolean;
productIds: number[]; skuIds: number[];
validTill: string | null; validTill: string | null;
createdAt: string; createdAt: string;
} }

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -5,11 +5,9 @@ import { createApp } from '@/src/app'
// import signedUrlCache from '@/src/lib/signed-url-cache'; // import signedUrlCache from '@/src/lib/signed-url-cache';
import { seed } from '@/src/lib/seed'; import { seed } from '@/src/lib/seed';
import '@/src/jobs/jobs-index'; import '@/src/jobs/jobs-index';
import { startAutomatedJobs } from '@/src/lib/automatedJobs';
seed() seed()
initFunc() initFunc()
startAutomatedJobs()
// signedUrlCache.loadFromDisk(); // Disabled for Workers compatibility // signedUrlCache.loadFromDisk(); // Disabled for Workers compatibility

View file

@ -15,7 +15,8 @@
"deploy:dev": "wrangler deploy --config wrangler.dev.toml", "deploy:dev": "wrangler deploy --config wrangler.dev.toml",
"wrangler:dev": "wrangler dev worker.ts --config wrangler.toml", "wrangler:dev": "wrangler dev worker.ts --config wrangler.toml",
"wrangler:deploy": "wrangler deploy worker.ts --config wrangler.toml", "wrangler:deploy": "wrangler deploy worker.ts --config wrangler.toml",
"pull_db": "wrangler d1 export freshyo-dev --config wrangler.prod.toml --remote --output ./dumps/latest.sql && bash ./scripts/populate_localdb.sh", "pull_db": "rm -rf .wrangler/state/v3/d1/* && wrangler d1 export freshyo-dev --config wrangler.prod.toml --remote --output ./dumps/latest.sql && bash ./scripts/populate_localdb.sh",
"pull_dev_db": "rm -rf .wrangler/state/v3/d1/* && wrangler d1 export freshyo-backend-dev --config wrangler.dev.toml --remote --output ./dumps/latest.sql && bash ./scripts/populate_localdb.sh --dev",
"docker:build": "cd .. && docker buildx build --platform linux/amd64 -t mohdshafiuddin54/health_petal:latest --progress=plain -f backend/Dockerfile .", "docker:build": "cd .. && docker buildx build --platform linux/amd64 -t mohdshafiuddin54/health_petal:latest --progress=plain -f backend/Dockerfile .",
"docker:push": "docker push mohdshafiuddin54/health_petal:latest" "docker:push": "docker push mohdshafiuddin54/health_petal:latest"
}, },

View file

@ -3,8 +3,14 @@ set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)" ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
DUMP_FILE="$ROOT_DIR/dumps/latest.sql" DUMP_FILE="$ROOT_DIR/dumps/latest.sql"
WRANGLER_CONFIG="$ROOT_DIR/wrangler.dev.toml"
DB_NAME="freshyo-dev" if [ "${1:-}" = "--dev" ]; then
WRANGLER_CONFIG="$ROOT_DIR/wrangler.dev.toml"
DB_NAME="freshyo-backend-dev"
else
WRANGLER_CONFIG="$ROOT_DIR/wrangler.prod.toml"
DB_NAME="freshyo-dev"
fi
if [ ! -f "$DUMP_FILE" ]; then if [ ! -f "$DUMP_FILE" ]; then
echo "Dump file not found: $DUMP_FILE" echo "Dump file not found: $DUMP_FILE"

View file

@ -51,9 +51,7 @@ export type {
AdminProductListResponse, AdminProductListResponse,
AdminProductResponse, AdminProductResponse,
AdminDeleteProductResult, AdminDeleteProductResult,
AdminToggleOutOfStockResult,
AdminUpdateSlotProductsResult, AdminUpdateSlotProductsResult,
AdminSlotProductIdsResult,
AdminSlotsProductIdsResult, AdminSlotsProductIdsResult,
AdminProductReview, AdminProductReview,
AdminProductReviewWithSignedUrls, AdminProductReviewWithSignedUrls,
@ -100,9 +98,6 @@ export type {
UserAddressDeleteResponse, UserAddressDeleteResponse,
UserBanner, UserBanner,
UserBannersResponse, UserBannersResponse,
UserCartProduct,
UserCartItem,
UserCartResponse,
UserComplaint, UserComplaint,
UserComplaintsResponse, UserComplaintsResponse,
UserRaiseComplaintResponse, UserRaiseComplaintResponse,
@ -124,7 +119,6 @@ export type {
UserCreateReviewResponse, UserCreateReviewResponse,
UserSlotProduct, UserSlotProduct,
UserSlotWithProducts, UserSlotWithProducts,
UserSlotData,
UserSlotAvailability, UserSlotAvailability,
UserDeliverySlot, UserDeliverySlot,
UserSlotsResponse, UserSlotsResponse,
@ -138,7 +132,6 @@ export type {
UserAuthResult, UserAuthResult,
UserOtpVerifyResponse, UserOtpVerifyResponse,
UserPasswordUpdateResponse, UserPasswordUpdateResponse,
UserProfileResponse,
UserDeleteAccountResponse, UserDeleteAccountResponse,
UserCouponUsage, UserCouponUsage,
UserCouponApplicableUser, UserCouponApplicableUser,
@ -158,8 +151,6 @@ export type {
UserOrderDetail, UserOrderDetail,
UserCancelOrderResponse, UserCancelOrderResponse,
UserUpdateNotesResponse, UserUpdateNotesResponse,
UserRecentProduct,
UserRecentProductsResponse,
// Store types // Store types
StoreSummary, StoreSummary,
StoresSummaryResponse, StoresSummaryResponse,

View file

@ -1,137 +0,0 @@
// import * as cron from 'node-cron';
const cron:any = {}
import { toggleFlashDeliveryForItems, toggleKeyVal } from '@/src/dbService';
import { CONST_KEYS } from '@/src/lib/const-keys'
import { computeConstants } from '@/src/lib/const-store'
const MUTTON_ITEMS = [
12, //Lamb mutton
14, // Mutton Boti
35, //Mutton Kheema
84, //Mutton Brain
4, //Mutton
86, //Mutton Chops
87, //Mutton Soup bones
85 //Mutton paya
];
export const startAutomatedJobs = () => {
// Job to disable flash delivery for mutton at 12 PM daily
cron.schedule('0 12 * * *', async () => {
try {
console.log('Disabling flash delivery for products at 12 PM');
await toggleFlashDeliveryForItems(false, MUTTON_ITEMS);
console.log('Flash delivery disabled successfully');
} catch (error) {
console.error('Error disabling flash delivery:', error);
}
});
// Job to enable flash delivery for mutton at 6 AM daily
cron.schedule('0 6 * * *', async () => {
try {
console.log('Enabling flash delivery for products at 5 AM');
await toggleFlashDeliveryForItems(true, MUTTON_ITEMS);
console.log('Flash delivery enabled successfully');
} catch (error) {
console.error('Error enabling flash delivery:', error);
}
});
// Job to disable flash delivery feature at 9 PM daily
cron.schedule('0 21 * * *', async () => {
try {
console.log('Disabling flash delivery feature at 9 PM');
await toggleKeyVal(CONST_KEYS.isFlashDeliveryEnabled, false);
await computeConstants(); // Refresh Redis cache
console.log('Flash delivery feature disabled successfully');
} catch (error) {
console.error('Error disabling flash delivery feature:', error);
}
});
// Job to enable flash delivery feature at 6 AM daily
cron.schedule('0 6 * * *', async () => {
try {
console.log('Enabling flash delivery feature at 6 AM');
await toggleKeyVal(CONST_KEYS.isFlashDeliveryEnabled, true);
await computeConstants(); // Refresh Redis cache
console.log('Flash delivery feature enabled successfully');
} catch (error) {
console.error('Error enabling flash delivery feature:', error);
}
});
console.log('Automated jobs scheduled');
};
/*
// Old implementation - direct DB queries:
import { db } from '@/src/db/db_index'
import { productInfo, keyValStore } from '@/src/db/schema'
import { inArray, eq } from 'drizzle-orm';
// Job to disable flash delivery for mutton at 12 PM daily
cron.schedule('0 12 * * *', async () => {
try {
console.log('Disabling flash delivery for products at 12 PM');
await db
.update(productInfo)
.set({ isFlashAvailable: false })
.where(inArray(productInfo.id, MUTTON_ITEMS));
console.log('Flash delivery disabled successfully');
} catch (error) {
console.error('Error disabling flash delivery:', error);
}
});
// Job to enable flash delivery for mutton at 6 AM daily
cron.schedule('0 6 * * *', async () => {
try {
console.log('Enabling flash delivery for products at 5 AM');
await db
.update(productInfo)
.set({ isFlashAvailable: true })
.where(inArray(productInfo.id, MUTTON_ITEMS));
console.log('Flash delivery enabled successfully');
} catch (error) {
console.error('Error enabling flash delivery:', error);
}
});
// Job to disable flash delivery feature at 9 PM daily
cron.schedule('0 21 * * *', async () => {
try {
console.log('Disabling flash delivery feature at 9 PM');
await db
.update(keyValStore)
.set({ value: false })
.where(eq(keyValStore.key, CONST_KEYS.isFlashDeliveryEnabled));
await computeConstants(); // Refresh Redis cache
console.log('Flash delivery feature disabled successfully');
} catch (error) {
console.error('Error disabling flash delivery feature:', error);
}
});
// Job to enable flash delivery feature at 6 AM daily
cron.schedule('0 6 * * *', async () => {
try {
console.log('Enabling flash delivery feature at 6 AM');
await db
.update(keyValStore)
.set({ value: true })
.where(eq(keyValStore.key, CONST_KEYS.isFlashDeliveryEnabled));
await computeConstants(); // Refresh Redis cache
console.log('Flash delivery feature enabled successfully');
} catch (error) {
console.error('Error enabling flash delivery feature:', error);
}
});
*/
// Optional: Call on import if desired, or export and call in main app
// startAutomatedJobs();

View file

@ -1,11 +1,11 @@
import { Buffer } from 'buffer' import { Buffer } from 'buffer'
import { scaffoldProducts } from '@/src/trpc/apis/common-apis/common' import { scaffoldProducts, scaffoldAvailability } from '@/src/trpc/apis/common-apis/common'
import { scaffoldEssentialConsts } from '@/src/trpc/apis/common-apis/common-trpc-index' import { scaffoldEssentialConsts } from '@/src/trpc/apis/common-apis/common-trpc-index'
import { scaffoldStores } from '@/src/trpc/apis/user-apis/apis/stores' import { scaffoldStores } from '@/src/trpc/apis/user-apis/apis/stores'
import { scaffoldSlotsWithProducts } from '@/src/trpc/apis/user-apis/apis/slots' import { scaffoldSlotsWithProducts } from '@/src/trpc/apis/user-apis/apis/slots'
import { scaffoldBanners } from '@/src/trpc/apis/user-apis/apis/banners' import { scaffoldBanners } from '@/src/trpc/apis/user-apis/apis/banners'
import { scaffoldStoreWithProducts } from '@/src/trpc/apis/user-apis/apis/stores' import { scaffoldStoreWithProducts } from '@/src/trpc/apis/user-apis/apis/stores'
import { getStoresSummary, incrementCacheVersion } from '@/src/dbService' import { getStoresSummary, incrementCacheVersion, incrementAvailabilityVersionNum, incrementSlotsVersionNum } from '@/src/dbService'
import { imageUploadS3 } from '@/src/lib/s3-client' import { imageUploadS3 } from '@/src/lib/s3-client'
import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter' import { getApiCacheKey, getCloudflareApiToken, getCloudflareZoneId, getAssetsDomain } from '@/src/lib/env-exporter'
import { CACHE_FILENAMES } from '@packages/shared' import { CACHE_FILENAMES } from '@packages/shared'
@ -13,16 +13,29 @@ import { retryWithExponentialBackoff } from '@/src/lib/retry'
const buildCachePath = (path: string, version: number) => `v-${version}/${path}` const buildCachePath = (path: string, version: number) => `v-${version}/${path}`
const buildAvailabilityPath = (version: number) => `av-${version}/${CACHE_FILENAMES.availability}`
const buildSlotsPath = (version: number) => `slots/v-${version}/${CACHE_FILENAMES.slots}`
function constructCacheUrl(path: string, version: number): string { function constructCacheUrl(path: string, version: number): string {
return `${getAssetsDomain()}${getApiCacheKey()}/${buildCachePath(path, version)}` return `${getAssetsDomain()}${getApiCacheKey()}/${buildCachePath(path, version)}`
} }
function constructAvailabilityUrl(version: number): string {
return `${getAssetsDomain()}${buildAvailabilityPath(version)}`
}
function constructSlotsUrl(version: number): string {
return `${getAssetsDomain()}${buildSlotsPath(version)}`
}
export interface CreateAllCacheFilesResult { export interface CreateAllCacheFilesResult {
cacheVersion: number cacheVersion: number
products: string products: string
essentialConsts: string essentialConsts: string
stores: string stores: string
slots: string slotsVersion: number
availabilityVersion: number
banners: string banners: string
individualStores: string[] individualStores: string[]
} }
@ -37,14 +50,16 @@ export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult>
productsKey, productsKey,
essentialConstsKey, essentialConstsKey,
storesKey, storesKey,
slotsKey, slotsVersion,
availabilityVersion,
bannersKey, bannersKey,
individualStoreKeys, individualStoreKeys,
] = await Promise.all([ ] = await Promise.all([
createProductsFileInternal(cacheVersion), createProductsFileInternal(cacheVersion),
createEssentialConstsFileInternal(cacheVersion), createEssentialConstsFileInternal(cacheVersion),
createStoresFileInternal(cacheVersion), createStoresFileInternal(cacheVersion),
createSlotsFileInternal(cacheVersion), createSlotsCacheFile(),
createAvailabilityCacheFile(),
createBannersFileInternal(cacheVersion), createBannersFileInternal(cacheVersion),
createAllStoresFilesInternal(cacheVersion), createAllStoresFilesInternal(cacheVersion),
]) ])
@ -56,7 +71,8 @@ export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult>
constructCacheUrl(CACHE_FILENAMES.products, cacheVersion), constructCacheUrl(CACHE_FILENAMES.products, cacheVersion),
constructCacheUrl(CACHE_FILENAMES.essentialConsts, cacheVersion), constructCacheUrl(CACHE_FILENAMES.essentialConsts, cacheVersion),
constructCacheUrl(CACHE_FILENAMES.stores, cacheVersion), constructCacheUrl(CACHE_FILENAMES.stores, cacheVersion),
constructCacheUrl(CACHE_FILENAMES.slots, cacheVersion), constructSlotsUrl(slotsVersion),
constructAvailabilityUrl(availabilityVersion),
constructCacheUrl(CACHE_FILENAMES.banners, cacheVersion), constructCacheUrl(CACHE_FILENAMES.banners, cacheVersion),
...stores.map((store) => constructCacheUrl(`stores/${store.id}.json`, cacheVersion)), ...stores.map((store) => constructCacheUrl(`stores/${store.id}.json`, cacheVersion)),
] ]
@ -76,7 +92,8 @@ export async function createAllCacheFiles(): Promise<CreateAllCacheFilesResult>
products: productsKey, products: productsKey,
essentialConsts: essentialConstsKey, essentialConsts: essentialConstsKey,
stores: storesKey, stores: storesKey,
slots: slotsKey, slotsVersion,
availabilityVersion,
banners: bannersKey, banners: bannersKey,
individualStores: individualStoreKeys, individualStores: individualStoreKeys,
} }
@ -98,6 +115,23 @@ async function createProductsFileInternal(version: number): Promise<string> {
} }
export async function createAvailabilityCacheFile(): Promise<number> {
const version = await incrementAvailabilityVersionNum()
const availabilityData = await scaffoldAvailability()
const jsonContent = JSON.stringify(availabilityData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8')
const filePath = buildAvailabilityPath(version)
console.log(filePath)
await imageUploadS3(
buffer,
'application/json',
filePath
)
return version
}
async function createEssentialConstsFileInternal(version: number): Promise<string> { async function createEssentialConstsFileInternal(version: number): Promise<string> {
const essentialConstsData = await scaffoldEssentialConsts() const essentialConstsData = await scaffoldEssentialConsts()
const jsonContent = JSON.stringify(essentialConstsData, null, 2) const jsonContent = JSON.stringify(essentialConstsData, null, 2)
@ -120,15 +154,21 @@ async function createStoresFileInternal(version: number): Promise<string> {
) )
} }
async function createSlotsFileInternal(version: number): Promise<string> { export async function createSlotsCacheFile(): Promise<number> {
const version = await incrementSlotsVersionNum()
const slotsData = await scaffoldSlotsWithProducts() const slotsData = await scaffoldSlotsWithProducts()
const jsonContent = JSON.stringify(slotsData, null, 2) const jsonContent = JSON.stringify(slotsData, null, 2)
const buffer = Buffer.from(jsonContent, 'utf-8') const buffer = Buffer.from(jsonContent, 'utf-8')
return await imageUploadS3( const filePath = buildSlotsPath(version)
console.log(filePath)
await imageUploadS3(
buffer, buffer,
'application/json', 'application/json',
`${getApiCacheKey()}/${buildCachePath(CACHE_FILENAMES.slots, version)}` filePath
) )
return version
} }
async function createBannersFileInternal(version: number): Promise<string> { async function createBannersFileInternal(version: number): Promise<string> {

View file

@ -17,6 +17,7 @@ export const CONST_KEYS = {
appStoreUrl: 'appStoreUrl', appStoreUrl: 'appStoreUrl',
popularItems: 'popularItems', popularItems: 'popularItems',
allItemsOrder: 'allItemsOrder', allItemsOrder: 'allItemsOrder',
tagsOrder: 'tagsOrder',
isFlashDeliveryEnabled: 'isFlashDeliveryEnabled', isFlashDeliveryEnabled: 'isFlashDeliveryEnabled',
supportMobile: 'supportMobile', supportMobile: 'supportMobile',
supportEmail: 'supportEmail', supportEmail: 'supportEmail',
@ -41,6 +42,7 @@ export const CONST_LABELS: Record<ConstKey, string> = {
appStoreUrl: 'App Store URL', appStoreUrl: 'App Store URL',
popularItems: 'Popular Items', popularItems: 'Popular Items',
allItemsOrder: 'All Items Order', allItemsOrder: 'All Items Order',
tagsOrder: 'Tags Order',
isFlashDeliveryEnabled: 'Enable Flash Delivery', isFlashDeliveryEnabled: 'Enable Flash Delivery',
supportMobile: 'Support Mobile', supportMobile: 'Support Mobile',
supportEmail: 'Support Email', supportEmail: 'Support Email',
@ -71,6 +73,7 @@ export const CONST_TYPES: Record<ConstKey, ConstValueType> = {
appStoreUrl: 'string', appStoreUrl: 'string',
popularItems: 'string', popularItems: 'string',
allItemsOrder: 'string', allItemsOrder: 'string',
tagsOrder: 'string',
isFlashDeliveryEnabled: 'boolean', isFlashDeliveryEnabled: 'boolean',
supportMobile: 'string', supportMobile: 'string',
supportEmail: 'string', supportEmail: 'string',
@ -95,6 +98,7 @@ export const CONST_VISIBILITY: Record<ConstKey, boolean> = {
appStoreUrl: true, appStoreUrl: true,
popularItems: true, popularItems: true,
allItemsOrder: true, allItemsOrder: true,
tagsOrder: false,
isFlashDeliveryEnabled: true, isFlashDeliveryEnabled: true,
supportMobile: true, supportMobile: true,
supportEmail: true, supportEmail: true,

View file

@ -1,4 +1,6 @@
import type { KVNamespace } from '@cloudflare/workers-types'
// Old env loading (Node only) // Old env loading (Node only)
// export const appUrl = process.env.APP_URL as string; // export const appUrl = process.env.APP_URL as string;
// //
@ -109,6 +111,11 @@ export const getRazorpaySecret = () => getRuntimeEnv().RAZORPAY_SECRET as string
export const getOtpSenderAuthToken = () => getRuntimeEnv().OTP_SENDER_AUTH_TOKEN as string export const getOtpSenderAuthToken = () => getRuntimeEnv().OTP_SENDER_AUTH_TOKEN as string
export const getOtpKvNamespace = () => {
const env = getRuntimeEnv()
return (env.freshyo_otp || env.freshyo_otp_dev) as KVNamespace | undefined
}
export const getMinOrderValue = () => Number(getRuntimeEnv().MIN_ORDER_VALUE as string) export const getMinOrderValue = () => Number(getRuntimeEnv().MIN_ORDER_VALUE as string)
export const getDeliveryCharge = () => Number(getRuntimeEnv().DELIVERY_CHARGE as string) export const getDeliveryCharge = () => Number(getRuntimeEnv().DELIVERY_CHARGE as string)

View file

@ -1,26 +1,37 @@
import { ApiError } from '@/src/lib/api-error' import { ApiError } from '@/src/lib/api-error'
import { getOtpSenderAuthToken } from '@/src/lib/env-exporter' import { getOtpSenderAuthToken, getOtpKvNamespace } from '@/src/lib/env-exporter'
import type { KVNamespace } from '@cloudflare/workers-types'
const otpStore = new Map<string, string>(); const OTP_TTL_SECONDS = 300
const otpKey = (phone: string) => `otp:${phone}`
const getKv = (): KVNamespace => {
const kv = getOtpKvNamespace()
if (!kv) {
throw new ApiError('OTP service not configured', 500)
}
return kv
}
const setOtpCreds = (phone: string, verificationId: string) => { const setOtpCreds = (phone: string, verificationId: string) => {
otpStore.set(phone, verificationId); return getKv().put(otpKey(phone), verificationId, { expirationTtl: OTP_TTL_SECONDS })
}; }
export function getOtpCreds(mobile: string) { export async function getOtpCreds(mobile: string) {
const authKey = otpStore.get(mobile); const authKey = await getKv().get(otpKey(mobile))
return authKey || null; return authKey || null;
} }
const clearOtpCreds = (phone: string) => {
return getKv().delete(otpKey(phone))
}
export const sendOtp = async (phone: string) => { export const sendOtp = async (phone: string) => {
if (!phone) { if (!phone) {
throw new ApiError("Phone number is required", 400); throw new ApiError("Phone number is required", 400);
} }
if (phone === '9676651496') {
setOtpCreds(phone, 'DEV_BYPASS_VERIFICATION_ID');
return { success: true, message: 'OTP sent successfully (dev bypass)' };
}
const reqUrl = `https://cpaas.messagecentral.com/verification/v3/send?countryCode=91&flowType=SMS&mobileNumber=${phone}&timeout=300`; const reqUrl = `https://cpaas.messagecentral.com/verification/v3/send?countryCode=91&flowType=SMS&mobileNumber=${phone}&timeout=300`;
const resp = await fetch(reqUrl, { const resp = await fetch(reqUrl, {
headers: { headers: {
@ -30,8 +41,9 @@ export const sendOtp = async (phone: string) => {
}); });
const data = await resp.json(); const data = await resp.json();
console.log({data})
if (data.message === "SUCCESS") { if (data.message === "SUCCESS") {
setOtpCreds(phone, data.data.verificationId); await setOtpCreds(phone, data.data.verificationId);
return { success: true, message: "OTP sent successfully", verificationId: data.data.verificationId }; return { success: true, message: "OTP sent successfully", verificationId: data.data.verificationId };
} }
if (data.message === "REQUEST_ALREADY_EXISTS") { if (data.message === "REQUEST_ALREADY_EXISTS") {
@ -42,9 +54,6 @@ export const sendOtp = async (phone: string) => {
}; };
export async function verifyOtpUtil(mobile: string, otp: string, verifId: string):Promise<boolean> { export async function verifyOtpUtil(mobile: string, otp: string, verifId: string):Promise<boolean> {
if (mobile === '9676651496') {
return otp === '1234';
}
const reqUrl = `https://cpaas.messagecentral.com/verification/v3/validateOtp?&verificationId=${verifId}&code=${otp}`; const reqUrl = `https://cpaas.messagecentral.com/verification/v3/validateOtp?&verificationId=${verifId}&code=${otp}`;
const resp = await fetch(reqUrl, { const resp = await fetch(reqUrl, {
method: "GET", method: "GET",
@ -56,6 +65,7 @@ export async function verifyOtpUtil(mobile: string, otp: string, verifId: string
const rawData = await resp.json(); const rawData = await resp.json();
if (rawData.data?.verificationStatus === "VERIFICATION_COMPLETED") { if (rawData.data?.verificationStatus === "VERIFICATION_COMPLETED") {
// delete the verificationId from the local storage // delete the verificationId from the local storage
await clearOtpCreds(mobile);
return true; return true;
} }
return false; return false;

View file

@ -1,6 +1,8 @@
import { import {
getOrdersByIdsWithFullData, getOrdersByIdsWithFullData,
getOrderByIdWithFullData, getOrderByIdWithFullData,
composeSkuName,
composeUnitNotation,
} from '@/src/dbService' } from '@/src/dbService'
import { sendTelegramMessage } from '@/src/lib/telegram-service' import { sendTelegramMessage } from '@/src/lib/telegram-service'
import { queueDataPusher } from '@/src/lib/queue-data-pusher' import { queueDataPusher } from '@/src/lib/queue-data-pusher'
@ -48,9 +50,12 @@ const formatOrderMessageWithFullData = (ordersData: any[]): string => {
message += '📦 <b>Items:</b>\n'; message += '📦 <b>Items:</b>\n';
order.orderItems?.forEach((item: any) => { order.orderItems?.forEach((item: any) => {
message += ` • ${item.product?.name || 'Unknown'} • ${item.product.productQuantity}${item.product.unit?.shortNotation}x${item.quantity}\n`; const sku = item.sku
const features = sku?.features || []
const name = composeSkuName(sku?.product?.name || 'Unknown', features)
const unit = composeUnitNotation(features)
message += ` • ${name} ${unit} x${item.quantity}\n`;
}); });
message += `\n💰 <b>Total:</b> ₹${order.totalAmount}\n`; message += `\n💰 <b>Total:</b> ₹${order.totalAmount}\n`;
message += `🚚 <b>Delivery:</b> ${ message += `🚚 <b>Delivery:</b> ${
@ -87,7 +92,7 @@ const formatCancellationMessage = (orderData: any, cancellationData: Cancellatio
📞 <b>Phone:</b> ${orderData.address?.phone || 'N/A'} 📞 <b>Phone:</b> ${orderData.address?.phone || 'N/A'}
📦 <b>Items:</b> 📦 <b>Items:</b>
${orderData.orderItems?.map((item: any) => ` • ${item.product?.name || 'Unknown'} x${item.quantity}`).join('\n') || ' N/A'} ${orderData.orderItems?.map((item: any) => ` • ${item.sku?.product?.name || 'Unknown'} x${item.quantity}`).join('\n') || ' N/A'}
💰 <b>Total:</b> ₹${orderData.totalAmount} 💰 <b>Total:</b> ₹${orderData.totalAmount}
💳 <b>Refund:</b> ${orderData.refundStatus === 'na' ? 'N/A (COD)' : orderData.refundStatus || 'Pending'} 💳 <b>Refund:</b> ${orderData.refundStatus === 'na' ? 'N/A (COD)' : orderData.refundStatus || 'Pending'}

View file

@ -64,7 +64,6 @@
// replaceProductTags, // replaceProductTags,
// toggleProductOutOfStock, // toggleProductOutOfStock,
// updateSlotProducts, // updateSlotProducts,
// getSlotProductIds,
// getSlotsProductIds, // getSlotsProductIds,
// getAllUnits, // getAllUnits,
// getAllProductTags, // getAllProductTags,
@ -158,15 +157,6 @@
// hasOngoingOrdersForAddress, // hasOngoingOrdersForAddress,
// // User - Banners // // User - Banners
// getUserActiveBanners, // getUserActiveBanners,
// // User - Cart
// getUserCartItemsWithProducts,
// getUserProductById,
// getUserCartItemByUserProduct,
// incrementUserCartItemQuantity,
// insertUserCartItem,
// updateUserCartItemQuantity,
// deleteUserCartItem,
// clearUserCart,
// // User - Complaint // // User - Complaint
// getUserComplaints, // getUserComplaints,
// createUserComplaint, // createUserComplaint,
@ -236,9 +226,6 @@
// getUserOrderBasic, // getUserOrderBasic,
// cancelUserOrderTransaction, // cancelUserOrderTransaction,
// updateUserOrderNotes, // updateUserOrderNotes,
// getUserRecentlyDeliveredOrderIds,
// getUserProductIdsFromOrders,
// getUserProductsForRecentOrders,
// // Store Helpers // // Store Helpers
// getAllBannersForCache, // getAllBannersForCache,
// getAllProductsForCache, // getAllProductsForCache,

View file

@ -69,12 +69,12 @@ export {
checkProductExistsByName, checkProductExistsByName,
checkUnitExists, checkUnitExists,
getProductImagesById, getProductImagesById,
createSpecialDealsForProduct, createSpecialDealsForSku,
updateProductDeals, updateSkuDeals,
replaceProductTags, replaceProductTags,
toggleProductOutOfStock, replaceTagProducts,
mergeSkus,
updateSlotProducts, updateSlotProducts,
getSlotProductIds,
getSlotsProductIds, getSlotsProductIds,
getAllUnits, getAllUnits,
getAllProductTags, getAllProductTags,
@ -94,6 +94,8 @@ export {
addProductToGroup, addProductToGroup,
removeProductFromGroup, removeProductFromGroup,
updateProductPrices, updateProductPrices,
// Merge duplicate products into multi-SKU products
mergeDuplicateProducts,
// Admin - Slots // Admin - Slots
getActiveSlotsWithProducts, getActiveSlotsWithProducts,
getActiveSlots, getActiveSlots,
@ -169,15 +171,6 @@ export {
hasOngoingOrdersForAddress, hasOngoingOrdersForAddress,
// User - Banners // User - Banners
getUserActiveBanners, getUserActiveBanners,
// User - Cart
getUserCartItemsWithProducts,
getUserProductById,
getUserCartItemByUserProduct,
incrementUserCartItemQuantity,
insertUserCartItem,
updateUserCartItemQuantity,
deleteUserCartItem,
clearUserCart,
// User - Complaint // User - Complaint
getUserComplaints, getUserComplaints,
createUserComplaint, createUserComplaint,
@ -247,12 +240,10 @@ export {
getUserOrderBasic, getUserOrderBasic,
cancelUserOrderTransaction, cancelUserOrderTransaction,
updateUserOrderNotes, updateUserOrderNotes,
getUserRecentlyDeliveredOrderIds,
getUserProductIdsFromOrders,
getUserProductsForRecentOrders,
// Store Helpers // Store Helpers
getAllBannersForCache, getAllBannersForCache,
getAllProductsForCache, getAllProductsForCache,
getAvailabilityForCache,
getAllStoresForCache, getAllStoresForCache,
getAllDeliverySlotsForCache, getAllDeliverySlotsForCache,
getAllSpecialDealsForCache, getAllSpecialDealsForCache,
@ -273,7 +264,6 @@ export {
type SlotWithProductsData, type SlotWithProductsData,
type UserNegativityData, type UserNegativityData,
// Automated Jobs // Automated Jobs
toggleFlashDeliveryForItems,
toggleKeyVal, toggleKeyVal,
getAllKeyValStore, getAllKeyValStore,
// Post-order handler helpers // Post-order handler helpers
@ -282,7 +272,7 @@ export {
type OrderWithFullData, type OrderWithFullData,
type OrderWithCancellationData, type OrderWithCancellationData,
// Common API helpers // Common API helpers
getSuspendedProductIds, getSuspendedSkuIds,
getNextDeliveryDateWithCapacity, getNextDeliveryDateWithCapacity,
getStoresSummary, getStoresSummary,
healthCheck, healthCheck,

View file

@ -13,7 +13,7 @@ interface Banner {
name: string name: string
imageUrl: string | null imageUrl: string | null
serialNum: number | null serialNum: number | null
productIds: number[] | null skuIds: number[] | null
createdAt: Date createdAt: Date
} }
@ -46,7 +46,7 @@ export async function initializeBannerStore(): Promise<void> {
// name: banner.name, // name: banner.name,
// imageUrl: signedImageUrl, // imageUrl: signedImageUrl,
// serialNum: banner.serialNum, // serialNum: banner.serialNum,
// productIds: banner.productIds, // skuIds: banner.skuIds,
// createdAt: banner.createdAt, // createdAt: banner.createdAt,
// } // }
// //
@ -78,7 +78,7 @@ export async function getBannerById(id: number): Promise<Banner | null> {
name: banner.name, name: banner.name,
imageUrl: signedImageUrl, imageUrl: signedImageUrl,
serialNum: banner.serialNum, serialNum: banner.serialNum,
productIds: banner.productIds, skuIds: banner.skuIds,
createdAt: banner.createdAt, createdAt: banner.createdAt,
} }
} catch (error) { } catch (error) {
@ -121,7 +121,7 @@ export async function getAllBanners(): Promise<Banner[]> {
name: banner.name, name: banner.name,
imageUrl: signedImageUrl, imageUrl: signedImageUrl,
serialNum: banner.serialNum, serialNum: banner.serialNum,
productIds: banner.productIds, skuIds: banner.skuIds,
createdAt: banner.createdAt, createdAt: banner.createdAt,
} }
}) })

View file

@ -6,17 +6,20 @@ import {
getAllSpecialDealsForCache, getAllSpecialDealsForCache,
getAllProductTagsForCache, getAllProductTagsForCache,
getProductById as getProductByIdFromDb, getProductById as getProductByIdFromDb,
getAllProductCombosForCache,
type ProductBasicData, type ProductBasicData,
type StoreBasicData, type StoreBasicData,
type DeliverySlotData, type DeliverySlotData,
type SpecialDealData, type SpecialDealData,
type ProductTagData, type ProductTagData,
type ProductComboCacheData,
} from '@/src/dbService' } from '@/src/dbService'
import { scaffoldAssetUrl } from '@/src/lib/s3-client' import { scaffoldAssetUrl } from '@/src/lib/s3-client'
// Uniform Product Type (matches getProductDetails return) // Uniform Product Type (matches getProductDetails return)
interface Product { interface Product {
id: number id: number
productId: number
name: string name: string
shortDescription: string | null shortDescription: string | null
longDescription: string | null longDescription: string | null
@ -33,6 +36,18 @@ interface Product {
deliverySlots: Array<{ id: number; deliveryTime: Date; freezeTime: Date; isCapacityFull: boolean }> deliverySlots: Array<{ id: number; deliveryTime: Date; freezeTime: Date; isCapacityFull: boolean }>
specialDeals: Array<{ quantity: string; price: string; validTill: Date }> specialDeals: Array<{ quantity: string; price: string; validTill: Date }>
productTags: string[] productTags: string[]
productType: string
isComboOnly: boolean
isOffer: boolean
comboItems: Array<{
skuId: number
skuName: string | null
unitNotation: string
productName: string
images: string[] | null
price: string
isOffer: boolean
}>
} }
export async function initializeProducts(): Promise<void> { export async function initializeProducts(): Promise<void> {
@ -76,18 +91,18 @@ export async function initializeProducts(): Promise<void> {
const allDeliverySlots = await getAllDeliverySlotsForCache() const allDeliverySlots = await getAllDeliverySlotsForCache()
const deliverySlotsMap = new Map<number, DeliverySlotData[]>() const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
for (const slot of allDeliverySlots) { for (const slot of allDeliverySlots) {
if (!deliverySlotsMap.has(slot.productId)) if (!deliverySlotsMap.has(slot.skuId))
deliverySlotsMap.set(slot.productId, []) deliverySlotsMap.set(slot.skuId, [])
deliverySlotsMap.get(slot.productId)!.push(slot) deliverySlotsMap.get(slot.skuId)!.push(slot)
} }
// Fetch all special deals // Fetch all special deals
const allSpecialDeals = await getAllSpecialDealsForCache() const allSpecialDeals = await getAllSpecialDealsForCache()
const specialDealsMap = new Map<number, SpecialDealData[]>() const specialDealsMap = new Map<number, SpecialDealData[]>()
for (const deal of allSpecialDeals) { for (const deal of allSpecialDeals) {
if (!specialDealsMap.has(deal.productId)) if (!specialDealsMap.has(deal.skuId))
specialDealsMap.set(deal.productId, []) specialDealsMap.set(deal.skuId, [])
specialDealsMap.get(deal.productId)!.push(deal) specialDealsMap.get(deal.skuId)!.push(deal)
} }
// Fetch all product tags // Fetch all product tags
@ -153,70 +168,11 @@ export async function initializeProducts(): Promise<void> {
export async function getProductById(id: number): Promise<Product | null> { export async function getProductById(id: number): Promise<Product | null> {
try { try {
// const key = `product:${id}` const allProducts = await getAllProducts()
// const data = await redisClient.get(key) const product = allProducts.find(p => p.id === id)
// if (!data) return null return product || null
// return JSON.parse(data) as Product
const product = await getProductByIdFromDb(id)
if (!product) return null
const signedImages = scaffoldAssetUrl(
(product.images as string[]) || []
)
// Fetch store info
const allStores = await getAllStoresForCache()
const store = product.storeId
? allStores.find(s => s.id === product.storeId) || null
: null
// Fetch delivery slots for this product
const allDeliverySlots = await getAllDeliverySlotsForCache()
const productSlots = allDeliverySlots.filter(s => s.productId === id)
// Fetch special deals for this product
const allSpecialDeals = await getAllSpecialDealsForCache()
const productDeals = allSpecialDeals.filter(d => d.productId === id)
// Fetch product tags for this product
const allProductTags = await getAllProductTagsForCache()
const productTagNames = allProductTags
.filter(t => t.productId === id)
.map(t => t.tagName)
return {
id: product.id,
name: product.name,
shortDescription: product.shortDescription,
longDescription: product.longDescription,
price: product.price.toString(),
marketPrice: product.marketPrice?.toString() || null,
unitNotation: product.unit.shortNotation,
images: signedImages,
isOutOfStock: product.isOutOfStock,
store: store
? { id: store.id, name: store.name, description: store.description }
: null,
incrementStep: product.incrementStep,
productQuantity: product.productQuantity,
isFlashAvailable: product.isFlashAvailable,
flashPrice: product.flashPrice?.toString() || null,
deliverySlots: productSlots.map((s) => ({
id: s.id,
deliveryTime: s.deliveryTime,
freezeTime: s.freezeTime,
isCapacityFull: s.isCapacityFull,
})),
specialDeals: productDeals.map((d) => ({
quantity: d.quantity.toString(),
price: d.price.toString(),
validTill: d.validTill,
})),
productTags: productTagNames,
}
} catch (error) { } catch (error) {
console.error(`Error getting product ${id}:`, error) console.error('Error getting product by ID:', error)
return null return null
} }
} }
@ -250,17 +206,17 @@ export async function getAllProducts(): Promise<Product[]> {
const allDeliverySlots = await getAllDeliverySlotsForCache() const allDeliverySlots = await getAllDeliverySlotsForCache()
const deliverySlotsMap = new Map<number, DeliverySlotData[]>() const deliverySlotsMap = new Map<number, DeliverySlotData[]>()
for (const slot of allDeliverySlots) { for (const slot of allDeliverySlots) {
if (!deliverySlotsMap.has(slot.productId)) if (!deliverySlotsMap.has(slot.skuId))
deliverySlotsMap.set(slot.productId, []) deliverySlotsMap.set(slot.skuId, [])
deliverySlotsMap.get(slot.productId)!.push(slot) deliverySlotsMap.get(slot.skuId)!.push(slot)
} }
const allSpecialDeals = await getAllSpecialDealsForCache() const allSpecialDeals = await getAllSpecialDealsForCache()
const specialDealsMap = new Map<number, SpecialDealData[]>() const specialDealsMap = new Map<number, SpecialDealData[]>()
for (const deal of allSpecialDeals) { for (const deal of allSpecialDeals) {
if (!specialDealsMap.has(deal.productId)) if (!specialDealsMap.has(deal.skuId))
specialDealsMap.set(deal.productId, []) specialDealsMap.set(deal.skuId, [])
specialDealsMap.get(deal.productId)!.push(deal) specialDealsMap.get(deal.skuId)!.push(deal)
} }
const allProductTags = await getAllProductTagsForCache() const allProductTags = await getAllProductTagsForCache()
@ -272,6 +228,14 @@ export async function getAllProducts(): Promise<Product[]> {
} }
const products: Product[] = [] const products: Product[] = []
const allProductCombos = await getAllProductCombosForCache()
const productCombosMap = new Map<number, ProductComboCacheData[]>()
for (const comboItem of allProductCombos) {
if (!productCombosMap.has(comboItem.comboSkuId))
productCombosMap.set(comboItem.comboSkuId, [])
productCombosMap.get(comboItem.comboSkuId)!.push(comboItem)
}
for (const product of productsData) { for (const product of productsData) {
const signedImages = scaffoldAssetUrl( const signedImages = scaffoldAssetUrl(
(product.images as string[]) || [] (product.images as string[]) || []
@ -281,16 +245,26 @@ export async function getAllProducts(): Promise<Product[]> {
: null : null
const deliverySlots = deliverySlotsMap.get(product.id) || [] const deliverySlots = deliverySlotsMap.get(product.id) || []
const specialDeals = specialDealsMap.get(product.id) || [] const specialDeals = specialDealsMap.get(product.id) || []
const productTags = productTagsMap.get(product.id) || [] const productTags = productTagsMap.get(product.productId) || []
const comboItems = (productCombosMap.get(product.id) || []).map((ci) => ({
skuId: ci.skuId,
skuName: ci.skuName,
unitNotation: ci.unitNotation,
productName: ci.productName,
images: ci.images ? scaffoldAssetUrl((ci.images as string[]) || []) : null,
price: ci.price,
isOffer: ci.isOffer,
}))
products.push({ products.push({
id: product.id, id: product.id,
productId: product.productId,
name: product.name, name: product.name,
shortDescription: product.shortDescription, shortDescription: product.shortDescription,
longDescription: product.longDescription, longDescription: product.longDescription,
price: product.price.toString(), price: product.price.toString(),
marketPrice: product.marketPrice?.toString() || null, marketPrice: product.marketPrice?.toString() || null,
unitNotation: product.unitShortNotation, unitNotation: product.unitNotation,
images: signedImages, images: signedImages,
isOutOfStock: product.isOutOfStock, isOutOfStock: product.isOutOfStock,
store: store store: store
@ -312,6 +286,10 @@ export async function getAllProducts(): Promise<Product[]> {
validTill: d.validTill, validTill: d.validTill,
})), })),
productTags: productTags, productTags: productTags,
productType: product.productType || 'item',
isComboOnly: product.isComboOnly,
isOffer: product.isOffer,
comboItems: comboItems,
}) })
} }

Some files were not shown because too many files have changed in this diff Show more