Compare commits

...
6 Commits
Author SHA1 Message Date
Hamed bf6cb67fcf Merge branch 'develop' of ssh://git.my-rm.com:2222/Robot-Market/static-front into develop
Build & Deploy (develop) / build-and-deploy (push) Successful in 3m7s
2026-10-13 14:00:37 +03:30
Hamed 54c387bf73 chore: update device prices on website 2026-10-13 13:58:36 +03:30
Hamed 57b0cfeac8 refactor dashboard feature boundaries and add test setup 2026-09-30 12:27:57 +03:30
Hamed fb2c394433 fix(styles): include feature modules in Tailwind content scan 2026-09-30 12:02:08 +03:30
Ryan 0381c8b73c refac:updated ci/cd pipeline to create docker images with timestamp and commit sha
Build & Deploy (develop) / build-and-deploy (push) Successful in 2m11s
2026-09-29 11:05:36 +03:30
Ryan b93c780fea refac:updated ci/cd pipeline to create docker images with timestamp and commit sha
Build & Deploy (develop) / build-and-deploy (push) Successful in 2m17s
2026-09-29 10:59:09 +03:30
44 changed files with 8591 additions and 5101 deletions
+9 -6
View File
@@ -20,17 +20,20 @@ jobs:
- name: Checkout code
uses: actions/checkout@v4
- name: Resolve commit SHA
- name: Resolve image tag
id: vars
run: |
# For PRs, gitea.sha is a temporary merge commit — use the real
# PR head commit instead so tags map to actual git history.
FULL_SHA="${{ gitea.event.pull_request.head.sha || gitea.sha }}"
echo "sha=${FULL_SHA:0:7}" >> "$GITHUB_OUTPUT"
SHORT_SHA="${FULL_SHA:0:7}"
BUILD_TIME=$(date -u +%Y-%m-%d_%H-%M-%S)
echo "sha=${SHORT_SHA}" >> "$GITHUB_OUTPUT"
echo "tag=${BUILD_TIME}-${SHORT_SHA}" >> "$GITHUB_OUTPUT"
- name: Build Docker image (tagged by commit SHA)
- name: Build Docker image (tagged by UTC build time and commit SHA)
run: |
docker build -t robot-market:${{ steps.vars.outputs.sha }} .
docker build -t robot-market:${{ steps.vars.outputs.tag }} .
- name: Save previous tag for rollback
id: backup
@@ -42,7 +45,7 @@ jobs:
- name: Point compose at this build
run: |
echo "IMAGE_TAG=${{ steps.vars.outputs.sha }}" > /opt/robot-market-front/.env
echo "IMAGE_TAG=${{ steps.vars.outputs.tag }}" > /opt/robot-market-front/.env
- name: Deploy via compose
id: deploy
@@ -85,7 +88,7 @@ jobs:
- name: Clean up dangling (untagged) layers
run: docker image prune -f
- name: Prune old SHA-tagged images (keep last 5)
- name: Prune old build-tagged images (keep last 5)
run: |
KEEP=5
CURRENT_TAG=$(grep IMAGE_TAG /opt/robot-market-front/.env 2>/dev/null | cut -d= -f2)
+11 -2
View File
@@ -2,7 +2,8 @@ name: Rollback (develop)
# Trigger manually from the Gitea Actions UI.
# Leave "sha" empty to roll back to the previous deploy.
# Fill "sha" in (short 7-char form, e.g. a3f9c21) to roll back to a specific past build.
# Fill "sha" in (short 7-char form, e.g. a3f9c21) to roll back to the newest
# build for that commit. Build tags include a UTC timestamp and commit SHA.
on:
workflow_dispatch:
inputs:
@@ -18,7 +19,15 @@ jobs:
- name: Determine target tag
run: |
if [ -n "${{ gitea.event.inputs.sha }}" ]; then
TAG="${{ gitea.event.inputs.sha }}"
SHA="${{ gitea.event.inputs.sha }}"
TAG=$(docker images robot-market --format '{{.Tag}}' \
| grep -E "-${SHA}$" \
| sort -r \
| head -n 1)
# Keep accepting legacy SHA-only tags created before timestamped tags.
if [ -z "$TAG" ]; then
TAG="$SHA"
fi
else
TAG=$(grep IMAGE_TAG /opt/robot-market-front/.env.previous | cut -d= -f2)
fi
+105 -87
View File
@@ -4,9 +4,9 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="bb7b50a5-be9c-4cd7-a05b-979f0e91b173" name="Changes" comment="refactor(products): organize product showcase into feature module">
<list default="true" id="bb7b50a5-be9c-4cd7-a05b-979f0e91b173" name="Changes" comment="fix(styles): include feature modules in Tailwind content scan">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/tailwind.config.ts" beforeDir="false" afterPath="$PROJECT_DIR$/tailwind.config.ts" afterDir="false" />
<change beforePath="$PROJECT_DIR$/data/content.ts" beforeDir="false" afterPath="$PROJECT_DIR$/data/content.ts" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -29,60 +29,60 @@
<component name="NextEditCompletionFeaturesState">
<decayedCancelled>
<entry key="MS100" value="1.0" />
<entry key="MS500" value="1.000008943214075" />
<entry key="S2" value="1.2607914241876252" />
<entry key="S5" value="3.6321166926353086" />
<entry key="S10" value="7.187879480049254" />
<entry key="S30" value="12.833490057716963" />
<entry key="S60" value="15.367124944343653" />
<entry key="M2" value="17.200465165116825" />
<entry key="M5" value="18.867586649419653" />
<entry key="M10" value="19.889539626550388" />
<entry key="M15" value="20.405494126294794" />
<entry key="M30" value="21.08410736765042" />
<entry key="H1" value="21.75882388976373" />
<entry key="H2" value="25.19651197545119" />
<entry key="H4" value="34.79882663024789" />
<entry key="D1" value="61.184565108820564" />
<entry key="W1" value="69.45949632611399" />
<entry key="MS500" value="1.0" />
<entry key="S2" value="1.000087252972038" />
<entry key="S5" value="1.0245081193731238" />
<entry key="S10" value="1.2033303929041042" />
<entry key="S30" value="2.526416819401647" />
<entry key="S60" value="4.055177645414961" />
<entry key="M2" value="6.613842117661979" />
<entry key="M5" value="13.292786284149477" />
<entry key="M10" value="19.047637193847063" />
<entry key="M15" value="21.88400324113337" />
<entry key="M30" value="25.442136814414752" />
<entry key="H1" value="27.80466751680738" />
<entry key="H2" value="32.05099449690078" />
<entry key="H4" value="42.01119466369274" />
<entry key="D1" value="68.95561233852308" />
<entry key="W1" value="77.42240766540701" />
</decayedCancelled>
<decayedSelected>
<entry key="MS100" value="7.962034587841035E-12" />
<entry key="MS500" value="0.006028438183823964" />
<entry key="S2" value="0.2786449669589018" />
<entry key="S5" value="0.5998193629466475" />
<entry key="S10" value="0.7744876138562475" />
<entry key="S30" value="0.9379611448586518" />
<entry key="S60" value="1.098380535936316" />
<entry key="M2" value="1.3551692202762455" />
<entry key="M5" value="1.7492815083633066" />
<entry key="M10" value="2.1050752944469457" />
<entry key="M15" value="2.3102267135979067" />
<entry key="M30" value="2.595453075209157" />
<entry key="H1" value="2.792248246685056" />
<entry key="H2" value="3.0438541717577623" />
<entry key="H4" value="3.5050645308767083" />
<entry key="D1" value="4.609559468032772" />
<entry key="W1" value="4.939182358578843" />
<entry key="MS100" value="0.0" />
<entry key="MS500" value="6.173165109562985E-278" />
<entry key="S2" value="4.98456166633934E-70" />
<entry key="S5" value="1.9013006178680956E-28" />
<entry key="S10" value="1.3788900274450676E-14" />
<entry key="S30" value="2.4491942588613115E-5" />
<entry key="S60" value="0.00561270246753653" />
<entry key="M2" value="0.09687308384134666" />
<entry key="M5" value="0.6088965925604509" />
<entry key="M10" value="1.2419655618123104" />
<entry key="M15" value="1.625109194802163" />
<entry key="M30" value="2.1768432348200197" />
<entry key="H1" value="2.557178317988167" />
<entry key="H2" value="2.9129118025914487" />
<entry key="H4" value="3.4288442997263706" />
<entry key="D1" value="4.592699670680046" />
<entry key="W1" value="4.936597530104908" />
</decayedSelected>
<decayedShown>
<entry key="MS100" value="3.2612493671796914E-8" />
<entry key="MS500" value="0.03182913112034664" />
<entry key="S2" value="0.7198587400143126" />
<entry key="S5" value="3.605555500545043" />
<entry key="S10" value="7.540560604413133" />
<entry key="S30" value="13.59016436886081" />
<entry key="S60" value="16.363500468632758" />
<entry key="M2" value="18.498243290148842" />
<entry key="M5" value="20.590803130608784" />
<entry key="M10" value="21.980529817792103" />
<entry key="M15" value="22.705973658811303" />
<entry key="M30" value="23.6744528413458" />
<entry key="H1" value="24.548438225385052" />
<entry key="H2" value="28.238985379440273" />
<entry key="H4" value="38.30313469133441" />
<entry key="D1" value="65.7939710746819" />
<entry key="W1" value="74.39865557179122" />
<entry key="MS100" value="0.4444213405832851" />
<entry key="MS500" value="0.8502741600641959" />
<entry key="S2" value="0.9603446084215367" />
<entry key="S5" value="1.0078897996704945" />
<entry key="S10" value="1.1930999599005467" />
<entry key="S30" value="2.5186943108989044" />
<entry key="S60" value="4.054093611688289" />
<entry key="M2" value="6.702385865993853" />
<entry key="M5" value="13.890469482072719" />
<entry key="M10" value="20.28012126997275" />
<entry key="M15" value="23.50144975042241" />
<entry key="M30" value="27.614279851343763" />
<entry key="H1" value="30.359221991616337" />
<entry key="H2" value="34.96247820400055" />
<entry key="H4" value="45.43924535528764" />
<entry key="D1" value="73.5481501056019" />
<entry key="W1" value="82.35898081352131" />
</decayedShown>
</component>
<component name="ProjectColorInfo">{
@@ -97,39 +97,39 @@
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"ASKED_MARK_IGNORED_FILES_AS_EXCLUDED": "true",
"ModuleVcsDetector.initialDetectionPerformed": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
"RunOnceActivity.git.unshallow": "true",
"RunOnceActivity.typescript.service.memoryLimit.init": "true",
"codeWithMe.voiceChat.enabledByDefault": "false",
"com.intellij.ml.llm.matterhorn.ej.ui.settings.DefaultModelSelectionForGA.v1": "true",
"git-widget-placeholder": "develop",
"javascript.nodejs.core.library.configured.version": "24.20.0",
"javascript.nodejs.core.library.typings.version": "24.13.3",
"javascript.preferred.runtime.type.id": "node",
"js.debugger.nextJs.config.created.client": "true",
"js.debugger.nextJs.config.created.server": "true",
"junie.onboarding.icon.badge.shown": "true",
"kronk.content.tree.expanded.paths": "",
"last_opened_file_path": "/home/hamed/Documents/Projects/GItLabRepo/device_web",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.jshint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.jshint": "",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"prettierjs.PrettierConfiguration.Package": "/home/hamed/Documents/Projects/GIthubRepo/robot-market-landing/node_modules/prettier",
"settings.editor.selected.configurable": "settings.javascript.prettier",
"to.speed.mode.migration.done": "true",
"ts.external.directory.path": "/home/hamed/Documents/Projects/GIthubRepo/robot-market-landing/node_modules/typescript/lib",
"vue.rearranger.settings.migration": "true"
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;ASKED_MARK_IGNORED_FILES_AS_EXCLUDED&quot;: &quot;true&quot;,
&quot;ModuleVcsDetector.initialDetectionPerformed&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252&quot;: &quot;true&quot;,
&quot;RunOnceActivity.git.unshallow&quot;: &quot;true&quot;,
&quot;RunOnceActivity.typescript.service.memoryLimit.init&quot;: &quot;true&quot;,
&quot;codeWithMe.voiceChat.enabledByDefault&quot;: &quot;false&quot;,
&quot;com.intellij.ml.llm.matterhorn.ej.ui.settings.DefaultModelSelectionForGA.v1&quot;: &quot;true&quot;,
&quot;git-widget-placeholder&quot;: &quot;develop&quot;,
&quot;javascript.nodejs.core.library.configured.version&quot;: &quot;24.20.0&quot;,
&quot;javascript.nodejs.core.library.typings.version&quot;: &quot;24.13.3&quot;,
&quot;javascript.preferred.runtime.type.id&quot;: &quot;node&quot;,
&quot;js.debugger.nextJs.config.created.client&quot;: &quot;true&quot;,
&quot;js.debugger.nextJs.config.created.server&quot;: &quot;true&quot;,
&quot;junie.onboarding.icon.badge.shown&quot;: &quot;true&quot;,
&quot;kronk.content.tree.expanded.paths&quot;: &quot;&quot;,
&quot;last_opened_file_path&quot;: &quot;/home/hamed/Documents/Projects/GItLabRepo/device_web&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.jshint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.jshint&quot;: &quot;&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;prettierjs.PrettierConfiguration.Package&quot;: &quot;/home/hamed/Documents/Projects/GIthubRepo/robot-market-landing/node_modules/prettier&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;preferences.lookFeel&quot;,
&quot;to.speed.mode.migration.done&quot;: &quot;true&quot;,
&quot;ts.external.directory.path&quot;: &quot;/home/hamed/Documents/Projects/GIthubRepo/robot-market-landing/node_modules/typescript/lib&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
}
}]]></component>
}</component>
<component name="RecentsManager">
<key name="MoveFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$" />
@@ -225,7 +225,8 @@
<workItem from="1790568898974" duration="91000" />
<workItem from="1790569032481" duration="788000" />
<workItem from="1790573950198" duration="16000" />
<workItem from="1790660862579" duration="2098000" />
<workItem from="1790660862579" duration="6418000" />
<workItem from="1790756879141" duration="396000" />
</task>
<task id="LOCAL-00001" summary="update">
<option name="closed" value="true" />
@@ -595,7 +596,23 @@
<option name="project" value="LOCAL" />
<updated>1790662596270</updated>
</task>
<option name="localTasksCounter" value="47" />
<task id="LOCAL-00047" summary="fix(styles): include feature modules in Tailwind content scan">
<option name="closed" value="true" />
<created>1790663421347</created>
<option name="number" value="00047" />
<option name="presentableId" value="LOCAL-00047" />
<option name="project" value="LOCAL" />
<updated>1790663421347</updated>
</task>
<task id="LOCAL-00048" summary="fix(styles): include feature modules in Tailwind content scan">
<option name="closed" value="true" />
<created>1790757130578</created>
<option name="number" value="00048" />
<option name="presentableId" value="LOCAL-00048" />
<option name="project" value="LOCAL" />
<updated>1790757130578</updated>
</task>
<option name="localTasksCounter" value="49" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
@@ -626,6 +643,7 @@
<MESSAGE value="Improve featured products layout and add support CTA" />
<MESSAGE value="Replace desktop showcase video with scroll-driven color backgrounds" />
<MESSAGE value="refactor(products): organize product showcase into feature module" />
<option name="LAST_COMMIT_MESSAGE" value="refactor(products): organize product showcase into feature module" />
<MESSAGE value="fix(styles): include feature modules in Tailwind content scan" />
<option name="LAST_COMMIT_MESSAGE" value="fix(styles): include feature modules in Tailwind content scan" />
</component>
</project>
@@ -0,0 +1,991 @@
# Next.js Project Development Rules
You are working on a production Next.js application using the App Router.
The codebase must remain:
- simple
- readable
- maintainable
- testable
- scalable
- junior-developer friendly
Always prefer the simplest maintainable solution.
Do not introduce Clean Architecture, repositories, use-cases, factories, dependency-injection systems, adapters, presenters, interactors, or unnecessary architectural layers unless they solve a real current problem.
Avoid over-engineering.
---
# Technology Stack
Use:
- Next.js
- App Router
- React
- JavaScript and TypeScript
- Tailwind CSS
- Redux Toolkit
- Vitest
- React Testing Library
- Playwright
Do not introduce additional libraries without a clear reason.
Before adding a dependency:
1. Check whether Next.js, React, JavaScript, TypeScript, or the existing stack can solve the problem.
2. Prefer existing project dependencies.
3. Add a dependency only when it clearly improves maintainability, reliability, or developer experience.
4. Briefly explain why it is necessary.
Do not introduce Zod or another validation library unless explicitly requested.
---
# App Router Only
Use the Next.js App Router.
Do not introduce Pages Router patterns into a new App Router project.
Use:
```text
app/
layout.tsx
page.tsx
loading.tsx
error.tsx
not-found.tsx
route.ts
```
when appropriate.
Use route groups for organization where helpful.
Example:
```text
app/
├── (public)/
├── (auth)/
└── (dashboard)/
```
Remember that route groups should organize the project without changing the URL.
---
# Server Components by Default
Server Components are the default.
Do not add:
```ts
'use client';
```
unless the component actually requires client-side functionality.
Client Components are appropriate when using things such as:
- useState
- useEffect
- browser APIs
- localStorage
- event handlers
- interactive client-side libraries
- Redux hooks
Keep Client Component boundaries as small as practical.
Do not convert an entire page into a Client Component just because one small child component needs interactivity.
Prefer:
```text
Server Page
↓
Server Components
↓
Small Client Component
```
rather than:
```text
Entire Page
↓
"use client"
```
---
# General Project Structure
Recommended structure:
```text
src/
├── app/
├── features/
├── components/
│ ├── ui/
│ └── layout/
├── hooks/
├── lib/
├── config/
├── constants/
├── types/
├── utils/
└── styles/
```
Keep routing in `app/`.
Keep business and feature-specific code in `features/`.
Keep generic reusable UI in `components/ui/`.
Keep infrastructure and reusable technical utilities in `lib/`.
Do not force every project to have every directory.
Create directories only when useful.
---
# Keep Pages Thin
`page.tsx` should primarily:
- define the route entry
- load route-level data when appropriate
- compose feature components
- pass necessary data
Avoid putting hundreds of lines of business logic inside `page.tsx`.
Prefer:
```tsx
import {ProductList} from '@/features/products/components/ProductList';
/**
* Displays the product-management page.
*/
export default async function ProductsPage() {
return <ProductList />;
}
```
over a very large page containing:
- data fetching
- filtering
- business rules
- forms
- modals
- API calls
- transformations
- UI rendering
all together.
---
# Feature-Based Architecture
Organize business functionality by feature.
Example:
```text
features/
├── auth/
├── products/
├── users/
├── machines/
├── sales/
└── reports/
```
A feature may contain:
```text
features/products/
├── components/
├── hooks/
├── services/
├── store/
├── utils/
├── types/
└── tests/
```
Do not create empty folders.
Only introduce a folder when there is actual code that belongs there.
---
# Shared UI vs Feature UI
Generic reusable components belong in:
```text
components/ui/
```
Examples:
```text
Button
Input
Modal
Table
Card
Badge
Spinner
```
Feature-specific components stay inside their feature.
Examples:
```text
features/products/components/ProductCard.tsx
features/machines/components/MachineStatus.tsx
features/sales/components/SalesTable.tsx
```
Generic UI components must not contain feature-specific business logic.
---
# Components
Each component should have one clear responsibility.
Keep components small enough to understand easily.
Split a component when it:
- handles unrelated responsibilities
- contains large amounts of business logic
- contains several independent UI sections
- becomes difficult to test
- becomes difficult to read
Do not split components unnecessarily.
Avoid creating wrappers that provide no meaningful behavior.
---
# Functions
Functions should be:
- focused
- descriptive
- short enough to understand
- easy to test
Prefer meaningful names:
```ts
calculateSaleTotal();
formatMachineStatus();
canUserEditProduct();
getAvailableProducts();
```
Avoid vague names:
```ts
handleData();
processStuff();
doWork();
helper();
func1();
```
---
# Function Documentation
Write English documentation comments for important and non-trivial functions.
Explain:
- what the function does
- important assumptions
- important business behavior
- non-obvious side effects
Example:
```ts
/**
* Returns true when a product is enabled and still has stock available.
*/
function canSellProduct(product: Product): boolean {
return product.enabled && product.stock > 0;
}
```
Do not comment obvious syntax or trivial statements.
Comments should explain intent, not translate code into English.
---
# Business Logic
Keep important business rules outside JSX when practical.
Bad:
```tsx
{
machine.enabled &&
machine.status === 'online' &&
machine.products.length > 0 &&
user.permissions.includes('manage_machine') && <ManageButton />;
}
```
Prefer:
```ts
/**
* Determines whether the current user can manage the given machine.
*/
function canManageMachine(machine: Machine, user: User): boolean {
return (
machine.enabled &&
machine.status === 'online' &&
machine.products.length > 0 &&
user.permissions.includes('manage_machine')
);
}
```
Then:
```tsx
{
canManageMachine(machine, user) && <ManageButton />;
}
```
This improves:
- readability
- testing
- reuse
- maintainability
---
# Redux Toolkit
Use Redux Toolkit as the project's global state-management solution.
Do not store every value in Redux.
Use local React state for local UI concerns.
Examples:
```text
modal open/close
dropdown state
form input
selected tab
temporary UI state
```
Use Redux for meaningful shared application state.
Examples:
```text
authentication
current user
shared settings
cross-page feature state
global workflow state
```
Keep Redux state feature-oriented.
Example:
```text
features/auth/store/authSlice.ts
features/machines/store/machineSlice.ts
```
Avoid a single giant application slice.
---
# Redux in Next.js
Redux requires Client Components.
Keep Redux Provider boundaries explicit.
Do not turn unrelated Server Components into Client Components just to access Redux.
Prefer passing server-fetched data into client boundaries when practical.
Example:
```text
Server Page
↓
Server data loading
↓
Client Feature Component
↓
Redux / interactive state
```
Do not unnecessarily duplicate server data into Redux.
Use Redux mainly for client-side shared state.
---
# Data Fetching
Prefer Server Components for server-side data fetching when appropriate.
Example:
```tsx
/**
* Loads the available products and renders the product list.
*/
export default async function ProductsPage() {
const products = await getProducts();
return <ProductList products={products} />;
}
```
Do not automatically use `useEffect` for every API request.
Use client-side fetching only when the feature requires client-side re-fetching, polling, user-triggered requests, or interactive behavior.
---
# Service Layer
Centralize backend communication.
Example:
```text
features/products/services/productService.ts
```
Example:
```ts
/**
* Loads all products from the backend.
*/
export async function getProducts(): Promise<Product[]> {
const response = await fetch(`${API_URL}/products`);
if (!response.ok) {
throw new Error('Failed to load products.');
}
return response.json();
}
```
Do not scatter backend URLs throughout pages and components.
Keep HTTP concerns away from presentation components when possible.
---
# Server and Client Boundaries
Be deliberate about the boundary between server and client code.
Server-side code may handle:
- server-side data loading
- secure environment variables
- server-only APIs
- protected backend communication
- route handlers
- server actions when appropriate
Client-side code may handle:
- interaction
- browser APIs
- local UI state
- Redux
- event listeners
- client-only libraries
Never expose secrets to Client Components.
---
# Environment Variables
Do not access environment variables randomly throughout the project.
Centralize configuration when useful.
Example:
```text
config/env.ts
```
Never expose secrets using:
```text
NEXT_PUBLIC_*
```
Only values intentionally accessible in the browser should use `NEXT_PUBLIC_`.
---
# Error Handling
Use Next.js error boundaries where appropriate.
Examples:
```text
error.tsx
not-found.tsx
```
Handle expected failures explicitly.
Do not silently swallow errors.
Provide user-friendly messages for recoverable failures.
Log technical information where appropriate without exposing sensitive data to end users.
---
# Loading States
Use:
```text
loading.tsx
```
when route-level loading UI is appropriate.
For local interactive operations, use explicit loading state.
Avoid blocking unrelated parts of the UI unnecessarily.
---
# State Derived from Existing State
Do not duplicate values that can be calculated.
Bad:
```ts
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [fullName, setFullName] = useState('');
```
Prefer:
```ts
const fullName = `${firstName} ${lastName}`;
```
Keep state minimal.
---
# useEffect
Do not use `useEffect` to calculate values that can be derived during rendering.
Use `useEffect` primarily for synchronizing with external systems.
Examples:
- WebSocket
- browser APIs
- subscriptions
- external widgets
- timers
- event listeners
Always clean up resources when required.
---
# Avoid Deep Nesting
Prefer guard clauses and early returns.
Bad:
```ts
if (session) {
if (session.user) {
if (session.user.active) {
// logic
}
}
}
```
Prefer:
```ts
if (!session?.user) return;
if (!session.user.active) return;
// Main logic
```
Keep the happy path visible.
---
# Avoid Magic Values
Bad:
```ts
if (status === 4) {
}
```
Prefer:
```ts
if (status === MachineStatus.Offline) {
}
```
Bad:
```ts
if (retryCount > 3) {
}
```
Prefer:
```ts
const MAX_RETRY_COUNT = 3;
if (retryCount > MAX_RETRY_COUNT) {
}
```
Use descriptive constants where they improve understanding.
---
# Naming
Names should explain intent.
Prefer:
```ts
selectedProduct;
currentUser;
isMachineOnline;
canEditSale;
hasAdminPermission;
shouldReloadProducts;
```
Avoid vague names such as:
```ts
data;
info;
item2;
temp;
res2;
obj;
value1;
stuff;
```
unless the surrounding context makes the meaning completely obvious.
---
# TypeScript and JavaScript
JavaScript and TypeScript may coexist.
Prefer TypeScript for new important logic where practical.
Do not perform unnecessary project-wide TypeScript migrations during unrelated work.
Avoid `any` where useful types can be defined.
Keep feature-specific types close to their feature.
Use global/shared types only when genuinely shared.
---
# Tailwind CSS
Use Tailwind CSS for styling.
Keep styles close to components.
Avoid creating excessive abstraction only to hide Tailwind classes.
If a visual pattern is reused meaningfully, extract a reusable component.
Maintain readable class structures.
Avoid unnecessarily complex conditional class expressions.
---
# Testing
Tests are required for meaningful behavior.
Use:
```text
Vitest
React Testing Library
Playwright
```
Use Vitest for:
- utilities
- business logic
- selectors
- reducers
- non-UI modules
Use React Testing Library for:
- interactive components
- forms
- user behavior
- conditional rendering
Use Playwright for critical user flows.
Examples:
```text
login
logout
create product
edit machine
view report
critical dashboard navigation
```
Test behavior rather than implementation details.
---
# Comments
All project comments must be written in English.
Use comments to explain:
- intent
- business rules
- important decisions
- limitations
- unusual behavior
- non-obvious workarounds
Do not use excessive comments for obvious code.
Important functions should have short English documentation comments.
---
# File Organization
Keep related code close together.
Avoid giant generic folders containing hundreds of unrelated files.
Bad:
```text
components/
ProductCard
LoginForm
SalesChart
MachineStatus
UserAvatar
ReportFilter
...
```
Prefer:
```text
features/products/components/
features/auth/components/
features/sales/components/
features/machines/components/
```
Use global component directories only for truly shared components.
---
# Refactoring Rules
When refactoring an existing Next.js project:
1. First understand the existing behavior.
2. Preserve functionality unless a behavior change is requested.
3. Identify duplicated logic.
4. Identify large pages and components.
5. Identify unclear naming.
6. Identify unnecessary Client Components.
7. Identify unnecessary `useEffect` usage.
8. Identify duplicated state.
9. Identify business logic buried in JSX.
10. Identify API calls scattered across UI code.
11. Refactor incrementally.
12. Add or update tests.
13. Remove dead code when safe.
14. Do not rewrite working code only to match a theoretical architecture.
15. Do not introduce unnecessary layers.
16. Keep the final result understandable to junior developers.
---
# New Features
When implementing a feature:
1. Find or create the correct feature directory.
2. Reuse existing shared components.
3. Keep the page thin.
4. Prefer Server Components by default.
5. Create Client Components only where needed.
6. Put API communication into a service when it improves separation.
7. Keep Redux only for meaningful shared client state.
8. Keep business rules testable.
9. Add appropriate tests.
10. Keep names explicit.
11. Avoid introducing abstractions before they are needed.
---
# New Projects
For a new Next.js project:
- use App Router
- use Tailwind CSS
- configure Redux Toolkit
- configure Vitest
- configure React Testing Library
- configure Playwright
- configure linting
- establish useful path aliases
- create only necessary directories
- keep Server Components as the default
- create a clear README
- avoid empty architecture folders
- avoid unnecessary dependencies
---
# Junior-Friendly Development Rules
Always ask:
"Can a junior developer understand this file without knowing hidden architectural conventions?"
Prefer explicit code.
Prefer:
```ts
const product = await getProduct(productId);
if (!product) {
return null;
}
return product;
```
over clever compressed expressions.
Avoid:
- excessive abstractions
- unnecessary generics
- complex type tricks
- deeply nested callbacks
- deeply nested conditions
- complicated ternaries
- hidden side effects
- unnecessary factories
- unnecessary inheritance
- excessive indirection
- premature reusable frameworks
A small amount of duplication is better than a confusing abstraction.
Refactor duplication when a clear reusable concept actually emerges.
---
# Final Decision Rule
When multiple implementations are valid, prefer the one that is:
1. simplest
2. easiest to read
3. easiest to test
4. easiest to debug
5. easiest to extend
6. easiest for a junior developer to understand
Do not optimize for impressive architecture.
Optimize for clarity, predictability, and maintainability.
-599
View File
@@ -1,599 +0,0 @@
# Next.js Frontend Architecture Guide
## Objective
This document defines the architecture rules for this Next.js project.
Before implementing new features, refactoring existing code, or creating new modules, read and follow this architecture.
The goal is to create a scalable, production-ready frontend suitable for a professional development team.
---
# Technology Stack
The project must use:
- Next.js (App Router)
- React
- TypeScript
- Redux Toolkit
- Axios
- Tailwind CSS
- Ant Design
Do not introduce alternative frameworks or libraries unless explicitly requested.
---
# Architecture Pattern
Use:
## Feature-Based Architecture
Organize code around business features, not technical file types.
Avoid:
```
src/
components/
pages/
services/
utils/
```
as the main structure.
Use:
```
src/
├── app/
│ ├── (routes)/
│ ├── api/
│ ├── providers/
│ ├── layout.tsx
│ ├── loading.tsx
│ ├── error.tsx
│ └── globals.css
│
├── features/
│ ├── auth/
│ ├── users/
│ ├── products/
│ ├── companies/
│ └── ...
│
├── components/
│ ├── ui/
│ ├── common/
│ └── layouts/
│
├── services/
│ ├── api/
│ ├── storage/
│ └── websocket/
│
├── store/
│
├── hooks/
│
├── lib/
│
├── types/
│
├── utils/
│
└── config/
```
---
# Next.js App Router Rules
Use Next.js App Router.
Routes must be created using:
```
app/
```
Example:
```
app/dashboard/page.tsx
```
creates:
```
/dashboard
```
Do not use React Router.
Do not manually create routing logic.
---
# Server Components vs Client Components
## Default Rule
All components should be Server Components by default.
Example:
```tsx
export default function UsersPage() {
return <div>Users</div>;
}
```
---
## Client Components
Use Client Components only when required.
Examples:
- useState
- useEffect
- Redux hooks
- Browser APIs
- Event handlers
Then add:
```tsx
'use client';
```
at the top.
Example:
```tsx
'use client';
export default function LoginForm() {}
```
Do not add `"use client"` unnecessarily.
---
# Feature Structure
Each business feature must be isolated.
Example:
```
features/auth/
├── api/
│ └── auth.api.ts
│
├── components/
│ └── LoginForm.tsx
│
├── hooks/
│ └── useLogin.ts
│
├── store/
│ └── auth.slice.ts
│
├── schemas/
│ └── auth.schema.ts
│
├── types.ts
│
└── index.ts
```
Example business features:
```
features/
auth
users
companies
machines
inventory
sales
payments
reports
settings
```
---
# Component Architecture
## Shared Components
Reusable components belong here:
```
components/ui/
```
Examples:
```
Button
Modal
Input
Table
Dropdown
Form
```
These components must not contain business logic.
---
Business components belong inside features:
Example:
```
features/products/components/ProductCard.tsx
```
Not:
```
components/ProductCard.tsx
```
---
# API Architecture
All API communication must go through Axios.
Never call Axios directly inside components.
Wrong:
```tsx
function Users() {
axios.get('/users');
}
```
Correct:
```
Component
↓
Hook
↓
Feature API
↓
Axios Service
↓
Backend API
```
---
Axios configuration:
```
services/api/
axios.ts
interceptors.ts
endpoints.ts
```
Example:
```ts
export const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
});
```
---
# Redux Toolkit Rules
Redux Toolkit is used only for global client state.
Examples:
- Authentication state
- User preferences
- Application settings
- Global UI state
Structure:
```
store/
├── index.ts
├── provider.tsx
└── slices/
```
Feature state:
```
features/auth/store/
auth.slice.ts
auth.selector.ts
```
---
Do not store everything in Redux.
Use:
```
useState
```
for local component state.
Use Redux only for shared application state.
---
# Redux Provider in Next.js
Redux Provider must be a Client Component.
Example:
```
store/provider.tsx
```
```tsx
'use client';
import {Provider} from 'react-redux';
export function ReduxProvider({children}) {
return <Provider store={store}>{children}</Provider>;
}
```
Register it in:
```
app/layout.tsx
```
---
# TypeScript Rules
The project must be strongly typed.
Avoid:
```ts
any;
```
Prefer:
```ts
interface;
type;
generics;
unknown;
```
Each feature owns its types:
Example:
```
features/users/types.ts
```
---
# Tailwind CSS Rules
Use Tailwind for:
- Layout
- Spacing
- Responsive design
- Custom styling
Example:
```tsx
<div className="flex items-center gap-4">
```
Avoid unnecessary CSS files.
Global CSS should only contain:
- Variables
- Theme
- Global styles
---
# Ant Design Rules
Use Ant Design for complex UI components:
Examples:
- Tables
- Forms
- Modal
- DatePicker
- Dropdown
- Pagination
- Notification
Use Tailwind for:
- Layout
- Positioning
- Spacing
- Responsive behavior
Do not rewrite Ant Design components unless required.
---
# Data Fetching Rules
Follow this structure:
```
Page
↓
Feature Component
↓
Custom Hook
↓
API Layer
↓
Axios
↓
Backend
```
Never put business API logic inside UI components.
---
# Dependency Rules
Features should remain independent.
Wrong:
```
features/products
imports
features/auth
```
Correct:
```
features/products
↓
services
components
utils
```
Shared logic belongs in:
```
components/
services/
utils/
lib/
```
---
# Refactoring Rules
When refactoring an existing project:
1. Analyze the current structure first.
2. Do not rewrite everything immediately.
3. Move code gradually into feature folders.
4. Preserve existing functionality.
5. Improve:
- Type safety
- Separation of concerns
- API abstraction
- Component reuse
- State management
---
# Code Quality Rules
Every file should have one responsibility.
Avoid:
```
User.tsx
- UI
- API
- Validation
- State
```
Prefer:
```
UserCard.tsx
user.api.ts
useUser.ts
user.schema.ts
```
---
# Final Architecture Goal
The final project must be:
- Scalable
- Maintainable
- Team-friendly
- Type-safe
- Easy to test
- Ready for future features
Always prefer clean architecture over fast implementation.
Before creating code, understand where the code belongs in this architecture.
+2 -34
View File
@@ -1,37 +1,5 @@
'use client';
import {useEffect, useState} from 'react';
import {Empty, Skeleton} from 'antd';
import type {CustomerOrder} from '@/types/account';
import {useAuth} from '@/app/context/AuthContext';
import {useLanguage} from '@/app/context/LanguageContext';
import {accountCopy} from '@/data/account';
import {getOrders} from '@/services/orders';
import OrderCard from '@/components/dashboard/OrderCard';
import OrdersList from '@/features/dashboard/components/OrdersList';
export default function OrdersPage() {
const auth = useAuth();
const {locale} = useLanguage();
const copy = accountCopy[locale];
const [orders, setOrders] = useState<CustomerOrder[] | null>(null);
useEffect(() => {
if (auth.session) getOrders(auth.session.profile).then(setOrders);
}, [auth.session]);
return (
<>
<h1 className="text-3xl font-extrabold text-primary">{copy.orders}</h1>
<p className="text-secondary mt-3 mb-7">{copy.dashboardDescription}</p>
{!orders ? (
<Skeleton active />
) : orders.length ? (
<div className="space-y-4">
{orders.map(order => (
<OrderCard key={order.id} order={order} />
))}
</div>
) : (
<Empty description={copy.emptyOrders} />
)}
</>
);
return <OrdersList />;
}
+2 -81
View File
@@ -1,84 +1,5 @@
'use client';
import {useEffect, useMemo, useState} from 'react';
import Link from 'next/link';
import {Progress, Skeleton} from 'antd';
import {CheckCircleOutlined, ClockCircleOutlined, FileTextOutlined} from '@ant-design/icons';
import type {CustomerOrder} from '@/types/account';
import {useAuth} from '@/app/context/AuthContext';
import {useLanguage} from '@/app/context/LanguageContext';
import {accountCopy} from '@/data/account';
import {getOrders} from '@/services/orders';
import OrderCard from '@/components/dashboard/OrderCard';
import DashboardOverview from '@/features/dashboard/components/DashboardOverview';
export default function DashboardPage() {
const auth = useAuth();
const {locale} = useLanguage();
const copy = accountCopy[locale];
const [orders, setOrders] = useState<CustomerOrder[] | null>(null);
useEffect(() => {
if (auth.session) getOrders(auth.session.profile).then(setOrders);
}, [auth.session]);
const completion = useMemo(() => {
if (!auth.session) return 0;
const profile = auth.session.profile;
const required = [
profile.firstName,
profile.lastName,
profile.province,
profile.city,
profile.address,
profile.postalCode,
];
return Math.round((required.filter(Boolean).length / required.length) * 100);
}, [auth.session]);
if (!orders) return <Skeleton active />;
const activeOrders = orders.filter(order => !['delivered', 'cancelled'].includes(order.status)).length;
const cards = [
{
label: copy.profileCompletion,
value: `${completion.toLocaleString(locale === 'fa' ? 'fa-IR' : 'en-US')}٪`,
icon: <CheckCircleOutlined />,
extra: <Progress percent={completion} showInfo={false} size="small" />,
},
{
label: copy.activeOrders,
value: activeOrders.toLocaleString(locale === 'fa' ? 'fa-IR' : 'en-US'),
icon: <ClockCircleOutlined />,
},
{
label: copy.totalOrders,
value: orders.length.toLocaleString(locale === 'fa' ? 'fa-IR' : 'en-US'),
icon: <FileTextOutlined />,
},
];
return (
<>
<h1 className="text-3xl font-extrabold text-primary">
{copy.welcome} {auth.session?.profile.firstName}
</h1>
<p className="text-secondary mt-3">{copy.dashboardDescription}</p>
<div className="grid sm:grid-cols-3 gap-4 mt-8">
{cards.map(card => (
<div key={card.label} className="rounded-2xl border border-subtle bg-elevated p-5">
<div className="text-brand-400 text-2xl">{card.icon}</div>
<p className="text-secondary text-sm mt-4">{card.label}</p>
<strong className="text-2xl text-primary block mt-1">{card.value}</strong>
{card.extra && <div className="mt-3">{card.extra}</div>}
</div>
))}
</div>
<div className="flex items-center justify-between gap-4 mt-10 mb-5">
<h2 className="text-xl font-bold text-primary">{copy.recentOrders}</h2>
<Link href="/dashboard/orders" className="text-brand-400">
{copy.viewAll}
</Link>
</div>
<div className="space-y-4">
{orders.slice(0, 2).map(order => (
<OrderCard key={order.id} order={order} />
))}
</div>
</>
);
return <DashboardOverview />;
}
+2 -3
View File
@@ -4,6 +4,7 @@ import Link from 'next/link';
import type {CustomerOrder} from '@/types/account';
import {useLanguage} from '@/app/context/LanguageContext';
import {accountCopy, paymentStatusLabels} from '@/data/account';
import {getOrderItemQuantity} from '@/features/dashboard/lib/orderSummary';
import OrderStatusTag from './OrderStatusTag';
export default function OrderCard({order}: {order: CustomerOrder}) {
@@ -32,9 +33,7 @@ export default function OrderCard({order}: {order: CustomerOrder}) {
<div>
<span className="text-secondary block">{copy.orderItems}</span>
<span className="text-primary">
{order.items
.reduce((sum, item) => sum + item.quantity, 0)
.toLocaleString(locale === 'fa' ? 'fa-IR' : 'en-US')}
{getOrderItemQuantity(order).toLocaleString(locale === 'fa' ? 'fa-IR' : 'en-US')}
</span>
</div>
</div>
+12 -12
View File
@@ -12,8 +12,8 @@ const machinesFa: Machine[] = [
category: 'warm-vending',
name: 'روبات مارکت ۳۵ کانال',
shortLabel: '۳۵ کانال',
priceLabel: '4,180,000,000 ریال',
priceNumeric: 4180000000,
priceLabel: '4,680,000,000 ریال',
priceNumeric: 4680000000,
description: 'یخچالدار، ۳۵ کانال اختصاصی، سیستم خنک‌کننده قدرتمند، تحویل نرم، مدیریت آنلاین ۲۴ ساعته.',
highlights: ['یخچالدار', '۳۵ کانال اختصاصی', 'تحویل نرم', 'مدیریت آنلاین ۲۴ ساعته'],
image: '/images/machine-35-base.webp',
@@ -25,8 +25,8 @@ const machinesFa: Machine[] = [
category: 'warm-vending',
name: 'روبات مارکت ۴۸ کانال',
shortLabel: '۴۸ کانال',
priceLabel: '4,980,000,000 ریال',
priceNumeric: 4980000000,
priceLabel: '5,480,000,000 ریال',
priceNumeric: 5480000000,
description: 'یخچالدار، ۴۸ کانال اختصاصی، قابلیت‌های پیشرفته مدیریت آنلاین و تحویل کالا.',
highlights: ['یخچالدار', '۴۸ کانال اختصاصی', 'مدیریت آنلاین پیشرفته', 'تحویل هوشمند کالا'],
image: '/images/machine-48-base.webp',
@@ -38,8 +38,8 @@ const machinesFa: Machine[] = [
category: 'warm-vending',
name: 'روبات مارکت ۶۰ کانال',
shortLabel: '۶۰ کانال',
priceLabel: '5,480,000,000 ریال',
priceNumeric: 5480000000,
priceLabel: '5,980,000,000 ریال',
priceNumeric: 5980000000,
description: 'یخچالدار، ۶۰ کانال اختصاصی برای کسب‌وکارهای پرتردد.',
highlights: ['یخچالدار', '۶۰ کانال اختصاصی', 'مناسب اماکن پرتردد', 'ظرفیت بالا'],
image: '/images/machine-60-base.webp',
@@ -54,8 +54,8 @@ const machinesEn: Machine[] = [
category: 'warm-vending',
name: 'Robot Market RM-35',
shortLabel: '35 Channels',
priceLabel: '4,180,000,000 Rials',
priceNumeric: 4180000000,
priceLabel: '4,680,000,000 Rials',
priceNumeric: 4680000000,
description:
'Refrigerated, 35 dedicated channels, powerful cooling system, soft delivery, 24/7 online management.',
highlights: ['Refrigerated', '35 dedicated channels', 'Soft delivery', '24/7 online management'],
@@ -68,8 +68,8 @@ const machinesEn: Machine[] = [
category: 'warm-vending',
name: 'Robot Market RM-48',
shortLabel: '48 Channels',
priceLabel: '4,980,000,000 Rials',
priceNumeric: 4980000000,
priceLabel: '5,480,000,000 Rials',
priceNumeric: 5480000000,
description: 'Refrigerated, 48 dedicated channels, advanced online management and delivery capabilities.',
highlights: ['Refrigerated', '48 dedicated channels', 'Advanced online management', 'Smart delivery'],
image: '/images/machine-48-base.webp',
@@ -81,8 +81,8 @@ const machinesEn: Machine[] = [
category: 'warm-vending',
name: 'Robot Market RM-60',
shortLabel: '60 Channels',
priceLabel: '5,480,000,000 Rials',
priceNumeric: 5480000000,
priceLabel: '5,980,000,000 Rials',
priceNumeric: 5980000000,
description: 'Refrigerated, 60 dedicated channels for high-traffic businesses.',
highlights: ['Refrigerated', '60 dedicated channels', 'Ideal for high-traffic venues', 'High capacity'],
image: '/images/machine-60-base.webp',
-1
View File
@@ -1 +0,0 @@
[{"eventName":"NEXT_CLI_SESSION_STOPPED","payload":{"nextVersion":"14.2.5","nodeVersion":"v26.3.0","cliCommand":"dev","durationMilliseconds":263824,"turboFlag":false,"pagesDir":false,"appDir":true}}]
-3
View File
@@ -1,3 +0,0 @@
{
"pages": {}
}
-16
View File
@@ -1,16 +0,0 @@
{
"polyfillFiles": [
"static/chunks/polyfills.js"
],
"devFiles": [],
"ampDevFiles": [],
"lowPriorityFiles": [
"static/development/_buildManifest.js",
"static/development/_ssgManifest.js"
],
"rootMainFiles": [],
"pages": {
"/_app": []
},
"ampFirstPages": []
}
Binary file not shown.
Binary file not shown.
-1
View File
@@ -1 +0,0 @@
{"type": "commonjs"}
-1
View File
@@ -1 +0,0 @@
{}
-1
View File
@@ -1 +0,0 @@
{}
@@ -1 +0,0 @@
self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST="[]"
-1
View File
@@ -1 +0,0 @@
self.__BUILD_MANIFEST={"polyfillFiles":["static/chunks/polyfills.js"],"devFiles":[],"ampDevFiles":[],"lowPriorityFiles":["static/development/_buildManifest.js","static/development/_ssgManifest.js"],"rootMainFiles":[],"pages":{"/_app":[]},"ampFirstPages":[]}
-6
View File
@@ -1,6 +0,0 @@
{
"version": 3,
"middleware": {},
"functions": {},
"sortedMiddleware": []
}
@@ -1 +0,0 @@
self.__REACT_LOADABLE_MANIFEST="{}"
-1
View File
@@ -1 +0,0 @@
self.__NEXT_FONT_MANIFEST="{\"pages\":{},\"app\":{},\"appUsingSizeAdjust\":false,\"pagesUsingSizeAdjust\":false}"
-1
View File
@@ -1 +0,0 @@
{"pages":{},"app":{},"appUsingSizeAdjust":false,"pagesUsingSizeAdjust":false}
-1
View File
@@ -1 +0,0 @@
{}
-1
View File
@@ -1 +0,0 @@
self.__RSC_SERVER_MANIFEST="{\n \"node\": {},\n \"edge\": {},\n \"encryptionKey\": \"OV7lo+xPvS/sDjLEddseUuhg7MfbZYxNg/IFGVNi66w=\"\n}"
@@ -1,5 +0,0 @@
{
"node": {},
"edge": {},
"encryptionKey": "OV7lo+xPvS/sDjLEddseUuhg7MfbZYxNg/IFGVNi66w="
}
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
self.__BUILD_MANIFEST = {__rewrites:{afterFiles:[],beforeFiles:[],fallback:[]},sortedPages:["\u002F_app"]};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()
-1
View File
@@ -1 +0,0 @@
self.__SSG_MANIFEST=new Set;self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()
-2
View File
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
{"type": "module"}
@@ -0,0 +1,56 @@
import {describe, expect, it} from 'vitest';
import type {CustomerOrder, CustomerProfile} from '@/types/account';
import {getActiveOrderCount, getOrderItemQuantity, getProfileCompletion} from '../lib/orderSummary';
const completeProfile: CustomerProfile = {
type: 'individual',
phone: '09123456789',
firstName: 'Sara',
lastName: 'Ahmadi',
email: 'sara@example.com',
province: 'Razavi Khorasan',
city: 'Mashhad',
address: 'Main street',
postalCode: '1234567890',
preferredCallTime: '',
companyName: '',
nationalId: '',
economicCode: '',
};
const makeOrder = (status: CustomerOrder['status'], quantities: number[] = [1]): CustomerOrder => ({
id: status,
number: `RM-${status}`,
createdAt: '1405/06/12',
updatedAt: '1405/06/15',
status,
paymentStatus: 'not_payable',
customer: completeProfile,
items: quantities.map((quantity, index) => ({
id: `item-${index}`,
name: 'Robot Market vending machine',
model: 'RM-48',
image: '/images/machine-48-base.webp',
quantity,
unitPrice: 100,
modules: [],
})),
events: [],
});
describe('dashboard order summary helpers', () => {
it('calculates required profile completion percentage', () => {
expect(getProfileCompletion(completeProfile)).toBe(100);
expect(getProfileCompletion({...completeProfile, city: '', postalCode: ''})).toBe(67);
});
it('counts active orders and excludes terminal statuses', () => {
const orders = [makeOrder('under_review'), makeOrder('delivered'), makeOrder('cancelled')];
expect(getActiveOrderCount(orders)).toBe(1);
});
it('totals item quantities for an order card', () => {
expect(getOrderItemQuantity(makeOrder('registered', [1, 2, 4]))).toBe(7);
});
});
@@ -0,0 +1,73 @@
'use client';
import Link from 'next/link';
import {CheckCircleOutlined, ClockCircleOutlined, FileTextOutlined} from '@ant-design/icons';
import {Progress, Skeleton} from 'antd';
import {useAuth} from '@/app/context/AuthContext';
import {useLanguage} from '@/app/context/LanguageContext';
import OrderCard from '@/components/dashboard/OrderCard';
import {accountCopy} from '@/data/account';
import {useCustomerOrders} from '../hooks/useCustomerOrders';
import {getActiveOrderCount, getProfileCompletion} from '../lib/orderSummary';
export default function DashboardOverview() {
const auth = useAuth();
const {locale} = useLanguage();
const copy = accountCopy[locale];
const numberLocale = locale === 'fa' ? 'fa-IR' : 'en-US';
const profile = auth.session?.profile;
const orders = useCustomerOrders(profile);
if (!profile || !orders) return <Skeleton active />;
const completion = getProfileCompletion(profile);
const activeOrders = getActiveOrderCount(orders);
const cards = [
{
label: copy.profileCompletion,
value: `${completion.toLocaleString(numberLocale)}٪`,
icon: <CheckCircleOutlined />,
extra: <Progress percent={completion} showInfo={false} size="small" />,
},
{
label: copy.activeOrders,
value: activeOrders.toLocaleString(numberLocale),
icon: <ClockCircleOutlined />,
},
{
label: copy.totalOrders,
value: orders.length.toLocaleString(numberLocale),
icon: <FileTextOutlined />,
},
];
return (
<>
<h1 className="text-3xl font-extrabold text-primary">
{copy.welcome} {profile.firstName}
</h1>
<p className="text-secondary mt-3">{copy.dashboardDescription}</p>
<div className="grid sm:grid-cols-3 gap-4 mt-8">
{cards.map(card => (
<div key={card.label} className="rounded-2xl border border-subtle bg-elevated p-5">
<div className="text-brand-400 text-2xl">{card.icon}</div>
<p className="text-secondary text-sm mt-4">{card.label}</p>
<strong className="text-2xl text-primary block mt-1">{card.value}</strong>
{card.extra && <div className="mt-3">{card.extra}</div>}
</div>
))}
</div>
<div className="flex items-center justify-between gap-4 mt-10 mb-5">
<h2 className="text-xl font-bold text-primary">{copy.recentOrders}</h2>
<Link href="/dashboard/orders" className="text-brand-400">
{copy.viewAll}
</Link>
</div>
<div className="space-y-4">
{orders.slice(0, 2).map(order => (
<OrderCard key={order.id} order={order} />
))}
</div>
</>
);
}
@@ -0,0 +1,34 @@
'use client';
import {Empty, Skeleton} from 'antd';
import {useAuth} from '@/app/context/AuthContext';
import {useLanguage} from '@/app/context/LanguageContext';
import OrderCard from '@/components/dashboard/OrderCard';
import {accountCopy} from '@/data/account';
import {useCustomerOrders} from '../hooks/useCustomerOrders';
export default function OrdersList() {
const auth = useAuth();
const {locale} = useLanguage();
const copy = accountCopy[locale];
const profile = auth.session?.profile;
const orders = useCustomerOrders(profile);
return (
<>
<h1 className="text-3xl font-extrabold text-primary">{copy.orders}</h1>
<p className="text-secondary mt-3 mb-7">{copy.dashboardDescription}</p>
{!orders ? (
<Skeleton active />
) : orders.length ? (
<div className="space-y-4">
{orders.map(order => (
<OrderCard key={order.id} order={order} />
))}
</div>
) : (
<Empty description={copy.emptyOrders} />
)}
</>
);
}
@@ -0,0 +1,28 @@
'use client';
import {useEffect, useState} from 'react';
import {getOrders} from '@/services/orders';
import type {CustomerOrder, CustomerProfile} from '@/types/account';
/**
* Loads the signed-in customer's orders after the browser auth profile is available.
*/
export function useCustomerOrders(profile: CustomerProfile | undefined) {
const [orders, setOrders] = useState<CustomerOrder[] | null>(null);
useEffect(() => {
if (!profile) return;
let active = true;
getOrders(profile).then(nextOrders => {
if (active) setOrders(nextOrders);
});
return () => {
active = false;
};
}, [profile]);
return orders;
}
+35
View File
@@ -0,0 +1,35 @@
import type {CustomerOrder, CustomerProfile} from '@/types/account';
const COMPLETE_PROFILE_FIELDS: Array<keyof CustomerProfile> = [
'firstName',
'lastName',
'province',
'city',
'address',
'postalCode',
];
const INACTIVE_ORDER_STATUSES = new Set<CustomerOrder['status']>(['delivered', 'cancelled']);
/**
* Calculates how much of the required buyer profile is ready for order processing.
*/
export function getProfileCompletion(profile: CustomerProfile): number {
const filledFields = COMPLETE_PROFILE_FIELDS.filter(field => Boolean(profile[field]));
return Math.round((filledFields.length / COMPLETE_PROFILE_FIELDS.length) * 100);
}
/**
* Counts orders that still need operational follow-up from the customer or sales team.
*/
export function getActiveOrderCount(orders: CustomerOrder[]): number {
return orders.filter(order => !INACTIVE_ORDER_STATUSES.has(order.status)).length;
}
/**
* Counts all units across an order, regardless of how many product lines it contains.
*/
export function getOrderItemQuantity(order: CustomerOrder): number {
return order.items.reduce((sum, item) => sum + item.quantity, 0);
}
+7163 -4228
View File
File diff suppressed because it is too large Load Diff
+12 -2
View File
@@ -10,7 +10,10 @@
"build": "next build",
"start": "next start",
"lint": "next lint",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:e2e": "playwright test"
},
"dependencies": {
"@ant-design/icons": "5.3.7",
@@ -27,13 +30,20 @@
"react-redux": "9.1.2"
},
"devDependencies": {
"@playwright/test": "^1.49.1",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.2",
"@types/node": "20.19.43",
"@types/react": "18.3.31",
"@types/react-dom": "18.3.7",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "10.4.19",
"jsdom": "^25.0.1",
"postcss": "8.4.39",
"prettier": "3.9.6",
"tailwindcss": "3.4.6",
"typescript": "5.9.3"
"typescript": "5.9.3",
"vitest": "^3.2.4"
}
}
+20
View File
@@ -0,0 +1,20 @@
import {defineConfig, devices} from '@playwright/test';
export default defineConfig({
testDir: './tests/e2e',
webServer: {
command: 'npx next dev -H 127.0.0.1',
url: 'http://127.0.0.1:3000',
reuseExistingServer: !process.env.CI,
},
use: {
baseURL: 'http://127.0.0.1:3000',
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: {...devices['Desktop Chrome']},
},
],
});
+3
View File
@@ -2,6 +2,9 @@ import type {CustomerOrder, CustomerProfile} from '@/types/account';
const wait = () => new Promise(resolve => setTimeout(resolve, 300));
/**
* Builds demo orders with the latest profile fields until the real orders API is connected.
*/
function createOrders(customer: CustomerProfile): CustomerOrder[] {
const buyer = {
...customer,
+9
View File
@@ -0,0 +1,9 @@
import {expect, test} from '@playwright/test';
test('home page exposes the primary shopping journey', async ({page}) => {
await page.goto('/');
await expect(page).toHaveTitle(/Robot Market|روبات مارکت/);
await expect(page.locator('a[href="#showcase"]').first()).toBeVisible();
await expect(page.locator('a[href="https://panel.my-rm.com"]').first()).toBeVisible();
});
+6
View File
@@ -23,10 +23,16 @@
"app/**/*.tsx",
"components/**/*.tsx",
"data/**/*.ts",
"features/**/*.ts",
"features/**/*.tsx",
"lib/**/*.ts",
"tests/**/*.ts",
"store/**/*.ts",
"types/**/*.ts",
"tailwind.config.ts",
"vitest.config.ts",
"vitest.setup.ts",
"playwright.config.ts",
".next/types/**/*.ts"
],
"exclude": ["node_modules", "docs", "out"]
+17
View File
@@ -0,0 +1,17 @@
import react from '@vitejs/plugin-react';
import {defineConfig} from 'vitest/config';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./vitest.setup.ts'],
include: ['features/**/*.test.ts', 'features/**/*.test.tsx', 'components/**/*.test.tsx'],
},
resolve: {
alias: {
'@': new URL('.', import.meta.url).pathname,
},
},
});
+1
View File
@@ -0,0 +1 @@
import '@testing-library/jest-dom/vitest';