From 651e68216fc347fb4c9296e4bab8080dd95feefe Mon Sep 17 00:00:00 2001 From: Mehrdad Shirvani Date: Sun, 29 Jun 2025 13:49:40 +0330 Subject: [PATCH] vault backup: 2025-06-29 13:49:40 --- ...ctions.md => Session09 Additional Info.md} | 9 + .../Session09/Session09 Backend.md | 135 +++++++++- .../Session09/Session09 Frontend.md | 111 ++++++++ .../Session10/Docker – Overview.md | 243 ++++++++++++++++++ ProjectOrientedSessions/Session10/Docker.md | 186 -------------- 5 files changed, 489 insertions(+), 195 deletions(-) rename ProjectOrientedSessions/Session09/{Database Transactions.md => Session09 Additional Info.md} (98%) create mode 100644 ProjectOrientedSessions/Session09/Session09 Frontend.md create mode 100644 ProjectOrientedSessions/Session10/Docker – Overview.md delete mode 100644 ProjectOrientedSessions/Session10/Docker.md diff --git a/ProjectOrientedSessions/Session09/Database Transactions.md b/ProjectOrientedSessions/Session09/Session09 Additional Info.md similarity index 98% rename from ProjectOrientedSessions/Session09/Database Transactions.md rename to ProjectOrientedSessions/Session09/Session09 Additional Info.md index b30efc5..f6ed9d5 100644 --- a/ProjectOrientedSessions/Session09/Database Transactions.md +++ b/ProjectOrientedSessions/Session09/Session09 Additional Info.md @@ -1,3 +1,12 @@ + +### ⚠ Important Tip +If your `agent.ts` uses `useAuthStore().token` **at the top level**, remember: +- On very first load, Zustand will **rehydrate** from storage _after_ initial render, so token may be `null` until rehydration is done. +- Fix: either delay access until after `hasHydrated`, or refactor `agent` to inject token per request. + + + + To **safely handle concurrency** in your `CreateTicketOrderAsync` method — particularly for **seat reservation** on the same `Transportation` — you need to **prevent race conditions** where two users might reserve the same seat or oversell capacity. This is a **classic critical section problem**, and you can solve it using **application-level locking**, **database-level locking**, or both. diff --git a/ProjectOrientedSessions/Session09/Session09 Backend.md b/ProjectOrientedSessions/Session09/Session09 Backend.md index 5ba5e61..37c565a 100644 --- a/ProjectOrientedSessions/Session09/Session09 Backend.md +++ b/ProjectOrientedSessions/Session09/Session09 Backend.md @@ -1,14 +1,131 @@ -Endpoint for increasing balance -Endpoint for reserving ticket(s) + updating transportation remaining count + adding transaction -Endpoint for getting seats + seeing if each is reserved or not -Creating and sending a pdf downloadable ticket +Here's a **structured checklist document**, broken into **sections by feature area**. Each section contains tasks in implementation order (oldest to newest), rephrased as clear action items with contextual notes for implementation. +These are created based on this commit messages: +https://github.com/MehrdadShirvani/AlibabaClone-Backend/commits/develop/ + +--- +# Miscellaneous / Fixes + +- [ ] Fix GUID generation and async handling in ticket creation. (Use `Guid.NewGuid()` instead of `new Guid()`) +- [ ] Make `SerialNumber`, `TicketOrderId`, `BaseAmount` publicly settable in DTOs. +- [ ] Fix issues in seat mappings and transportation queries. +# Fixes and Missing Parts from Session 08 + +## 👤 Person & Account Info + +- [ ] Add `Person`, `BankAccountDetail`, and navigation properties. +- [ ] Add `UpsertPersonAsync` and `UpsertBankAccountDetailAsync` in `IAccountService`. +- [ ] Add `UpsertPerson`, `UpsertBankDetail` endpoints in `AccountController`. +- [ ] Add `GetPeople`, `GetProfileAsync`, and DTOs (`ProfileDto`, `PersonDto`, `BankAccountDetailDto`). +- [ ] Handle person editing logic via `UpsertPerson` and adjust classes that used it the old way. +## 🔐 Auth & Settings + +- [ ] Complete the error handling of `EditEmailDto`, `EditPasswordDto`. +- [ ] Add `GetByEmailAsync` in `AccountRepository`. -### ⚠ Important Tip +# Branching +- [ ] Create the feature/ticket-reservation branch based on develop + +# Ticket Ordering System + +## 🧱 Domain and Infrastructure Setup + +- [ ] Check out new ERD: [Here](https://github.com/TheOrderOfPhoenix/ASP.NET/blob/main/ProjectOrientedSessions/docs/AlibabaERD-Version02.pdf) +- [ ] Create `TicketOrder`, `Ticket`, and `Transaction` entities. +- [ ] Add configurations for `TicketOrder`, `Ticket`, and `Transaction` (relationships, constraints). +- [ ] Adjust `Transportation` entity configuration to support ticketing. +- [ ] Add migrations for the above database changes. + +## 🧑‍💼 Service Layer + +- [ ] Create `ITicketOrderService`, `TicketOrderService` and implement: + - [ ] `CreateTicketOrderAsync` + - [ ] `GenerateTicketsPdfAsync` +- [ ] Register `TicketOrderService` in DI container. + +## 🎯 Controller Layer + +- [ ] Create `TicketOrderController` with the following endpoints: + - [ ] `POST /CreateTicketOrder` + - [ ] `GET /DownloadPdf` + +## 🔁 DTOs & Mappings + +- [ ] Add `CreateTicketOrderDto`, `CreateTravelerTicketDto`. +- [ ] Add `TicketOrderSummaryDto`, `TravelerTicketDto`. +- [ ] Add mappings in `MappingProfile`. + +## 🗃️ Repository Layer + +- [ ] Create `ITicketOrderRepository`, `TicketOrderRepository`. +- [ ] Implement: + - [ ] `FindAndLoadAllDetails` + - [ ] `GetAllByBuyerId` + +--- + +# Transportation and Seat Selection + +- [ ] Add `TransportationSeatDto`. +- [ ] Add method `GetSeatsByVehicleId` in `ISeatRepository` and implement it. +- [ ] Add mapping from `Seat` to `TransportationSeatDto`. +- [ ] Add `GetTransportationSeatsAsync` in `ITransportationService` and implement. +- [ ] Add `GetTransportationSeats` endpoint in `TransportationController`. +- [ ] Fix vehicle and seat-related mapping issues (e.g., missing `VehicleTypeId`, logic errors). +- [ ] Ensure `RemainingCapacity` is treated as calculated (ignored in EF, removed from schema). + +--- + +# Coupon System + +## 🏗️ Domain & Infrastructure +- [ ] Add `Coupon` entity with `IsExpired`, `CouponCode` (unique). +- [ ] Add `ICouponRepository`, `CouponRepository`. +- [ ] Add `DiscountDto`, `CouponValidationRequestDto`. +- [ ] Add migrations for new `Coupon` table. + +### 🧑‍💼 Service & Logic +- [ ] Create `ICouponService`, implement validation logic. +- [ ] Add coupon validation in `TicketOrderService`. +### 🎯 Controller +- [ ] Add `ValidateCoupon` endpoint in `CouponController`. + +--- + +# Payment & Transactions + +- [ ] Add `CouponId` to `PayForTicketOrderAsync` in `IAccountService` & implementation. +- [ ] Add `CouponId` to `TransactionDto` (adjusted to `CouponCode` later). +- [ ] Add `TopUpAccount` logic (DTO, Controller, Service). +- [ ] Add `Transaction` relationship to `TicketOrder` as one-to-one. +- [ ] Add logic for creating transactions with tickets. +- [ ] Add endpoint `GetMyTransactions` and DTOs (`TransactionDto`). + +--- + +## ✅ Ticket Review & Confirmation + +- [ ] Add `TicketOrderSummaryDto`, map details: from/to city, company, vehicle, time. +- [ ] Implement `GetTravelOrderDetails` endpoint to fetch ticket summary. +- [ ] Display number of travelers, per-seat price, and total cost. +- [ ] Include coupon entry and balance payment option. +- [ ] Use ticket + person data (via `GetTicketOrderTravelersDetails`). + +--- + +## ✅ PDF Generation + +- [ ] Install `QuestPDF` in infrastructure. +- [ ] Create `IPdfGenerator`, implement with QuestPDF. +- [ ] Register `IPdfGenerator` service. +- [ ] Create `PdfGenerator` logic to render ticket PDFs. +- [ ] Add PDF download endpoint (`DownloadPdf`) in `TicketOrderController`. +--- +# Merge +- [ ] Create a PR and merge the current branch with develop + + +--- -If your `agent.ts` uses `useAuthStore().token` **at the top level**, remember: -- On very first load, Zustand will **rehydrate** from storage _after_ initial render, so token may be `null` until rehydration is done. - -- Fix: either delay access until after `hasHydrated`, or refactor `agent` to inject token per request. diff --git a/ProjectOrientedSessions/Session09/Session09 Frontend.md b/ProjectOrientedSessions/Session09/Session09 Frontend.md new file mode 100644 index 0000000..9f2a554 --- /dev/null +++ b/ProjectOrientedSessions/Session09/Session09 Frontend.md @@ -0,0 +1,111 @@ +# Reservation System Development Guide + +This guide helps developers understand how to implement, update, and maintain the ticket reservation system. It summarizes changes from commits and provides step-by-step actions, grouped by feature area. +https://github.com/MehrdadShirvani/AlibabaClone-Frontend/commits/develop/ +--- + +# Fixes and Missing Things from Session 08 +## Authentication & Protected Routes + +- [ ] Store `showLoginModal` state in `authStore` and adjust navbar +- [ ] Add `ProtectedRoute` component +- [ ] Adjust main `App` to route authenticated pages through protection layer +- [ ] Add session persistence in `authStore` to store token more persistently + +--- +## Profile and User Info Enhancements + +- [ ] Fix and align `birthDate` types in `PersonDto`, `transportationSearchResult`, and `ListOfTravelers` +## Agent +- [ ] Add `topUpDto` and its method in `agent.ts` +- [ ] Add optional config parameter to `request()` in `agent.ts` + +# Branching +- [ ] Create the feature/themes branch based on develop +# 🎨 Theming and UI Styling +- [ ] Install and import `preline` +- [ ] Add theme colors and global styles (index.css) +- [ ] Add `ThemeSwitcher` and integrate it into the navbar +- [ ] If you decide to do this part after implementing pages, make sure to add theme support to the following components: + - [ ] `transportationCard`, `transportationSearchForm`, `ReviewAndConfirm` + - [ ] All modals: `LoginModal`, `RegisterModal`, `SelectFromPeopleModal` + - [ ] Profile section: `ProfilePage`, `ProfileSummary`, `PersonalInformation`, `AccountInfo`, `PersonalAccountInfo`, `BankAccountDetails`, `MyTravels`, `MyTransactions`, `ListOfTravelers` + - [ ] Reservation views and components + +# Merge +- [ ] Create a PR and merge the current branch with develop +--- +# Branching +- [ ] Create the feature/ticket-reservation branch based on develop +# Backend Agent Methods +- [ ] Add `createTicketOrderDto` and `createTravelerTicketDto` +- [ ] Add `transportationSeatDto` +- [ ] Add related methods in `TicketOrder` and add it to agent + +# Reservation Process & Step Management + +- [ ] Implement `useReservationStore` using `zustand` to manage reservation state +- [ ] Create step-based routing using `ReservationLayout` +- [ ] Add routing for reservation steps in `App.tsx` +- [ ] Add `StepIndicator` component to show step progress visually +- [ ] Add `stepGuard` logic to prevent accessing future steps prematurely +- [ ] Add logic to skip back only if previous steps are completed +- [ ] Create `TravelerForm` to gather passenger info, with the possibility to load data from the related people of the account. +- [ ] Create `TravelerDetailsForm` to gather passengers info with `TravelerForm` integration +- [ ] Create `ReviewAndConfirm` page to review selections +- [ ] Create `PaymentForm` for transaction process +- [ ] Create `TicketIssued` page for confirmation +- [ ] Add validation to show error if `seatId` is missing + +--- +# Seat Selection +- [ ] Add DTO: +```tsx +export interface transportationSeatDto{ +    id : number, +    vehicleId : number, +    row : number, +    column : number, +    isVIP : boolean, +    isAvailable : boolean, +    description : string | null, +    isReserved : boolean, +    genderId : number | null +} +``` +- [ ] Add `getSeats()` method to `agent.ts` +- [ ] Add `SeatGridSelector` component for graphical seat layout in `TravelerDetailForm` and integrate it with traveler list, only for Buses +- [ ] Modify `transportationCard` to integrate with seat selection +- [ ] Add `SeatOnlyGridSeatMap` for simpler seat-only display +--- +# Coupon Integration + +- [ ] Add `couponValidationRequestDto` and `discountDto` +- [ ] Add `validateCoupon()` method to `agent.ts` +- [ ] Update `useReservationStore` to include `couponCode` +- [ ] Ensure `createTicketOrderDto` uses `couponCode` instead of `couponId` +- [ ] Connect coupon validation flow in `ReviewAndConfirm` + +--- +# Search, Filter, and Sort Functionality + +- [ ] Add filters (company) and sorting (time or price) UI to `SearchResultPage` +- [ ] Add company logo support in result cards and filters +- [ ] Add `previous/next day` buttons for time navigation +- [ ] Add remaining capacity check to transportation cards +- [ ] Add refund policy info display +- [ ] Implement showing seat map in `TransportaionCard` using `ReadOnlySeatMap` + +## 📎 Notes + +- Ensure you run a full theme test after UI changes. +- Test step transitions with various invalid scenarios. +- Confirm persistent session and coupon behavior across refreshes. +- Validate all filters, sort, and search navigation works. +- Test seat selection and proper rendering of rotated layouts. + +--- + +# Merge +- [ ] Create a PR and merge the current branch with develop + diff --git a/ProjectOrientedSessions/Session10/Docker – Overview.md b/ProjectOrientedSessions/Session10/Docker – Overview.md new file mode 100644 index 0000000..17ee575 --- /dev/null +++ b/ProjectOrientedSessions/Session10/Docker – Overview.md @@ -0,0 +1,243 @@ + +## What is Docker? + +Docker is a platform that allows you to package applications with all their dependencies into a standardized unit called a **container**. These containers are portable, isolated, and consistent across environments. + +--- + +## What is a Container? + +A container is a lightweight, standalone executable package that includes everything needed to run an application: code, runtime, libraries, and configurations. + +Containers are stored in **container repositories**: +- Public repositories: [Docker Hub](https://hub.docker.com) +- Private repositories: Used by organizations for internal deployments + +--- + +## Why Containers? + +### Before Containers: +- Developers shared artifacts (e.g., `.jar` files) with setup instructions. +- Operators had to install dependencies manually. +- Setup was error-prone and inconsistent across OS environments. + +### With Containers: +- Everything is bundled together and works the same everywhere. +- No need to install dependencies manually. +- Runs in its own isolated environment. +- Easy to version, share, and deploy (just one command). +- Multiple versions of the same app can run simultaneously. + +--- + +## Image vs. Container + +|Term|Description| +|---|---| +|**Image**|A snapshot or package (the blueprint). Immutable.| +|**Container**|A running instance of an image. Has its own file system, environment, and process.| +Running an image creates a container. + +--- + +## Docker vs Virtual Machine + +| Feature | Docker | Virtual Machine | +| --------------- | ------------------ | ------------------ | +| Virtualizes | Application layer | Full OS kernel | +| Startup time | Seconds | Minutes | +| Size | MBs | GBs | +| Isolation | OS-level | Hardware-level | +| Performance | Near-native | Heavier overhead | +| Host dependency | Shares host kernel | Has its own kernel | + +Docker runs natively on Linux; on Windows/macOS it uses **Docker Desktop**, which runs Linux under WSL2 or HyperKit. + +--- + +## Docker Architecture + +### Layers of a Docker Image: + +- Base Layer: Usually a minimal Linux distribution (e.g., `alpine`) +- Application Layer: Your app and its dependencies + +Each image is made of **layers** stacked on top of each other. + +--- + +## Docker Installation + +To use Docker on: + +- **Linux**: Install Docker engine directly. +- **Windows/macOS**: Use Docker Desktop, which includes WSL2 integration or virtualization backend. + +--- + +## Docker Commands: Basics + +```bash +# Run a container from an image +docker run image-name + +# List running containers +docker ps + +# List all containers (running and stopped) +docker ps -a + +# Stop a running container +docker stop CONTAINER_ID + +# Start a stopped container +docker start CONTAINER_ID +``` + +### Port Binding + +```bash +docker run -p HOST_PORT:CONTAINER_PORT image-name +``` + +This binds a container’s port to a specific port on your machine. + +--- + +## Debugging Containers + +```bash +# View logs +docker logs CONTAINER_ID + +# Start a container with detached mode and port +docker run -d -p 3000:3000 image-name + +# Open an interactive shell inside a running container +docker exec -it CONTAINER_ID /bin/bash +``` + +You can assign names to containers using `--name`. + +--- + +## Docker Networking + +### Concept: + +Containers can communicate with each other over a virtual network. + +```bash +# List networks +docker network ls + +# Create a new network +docker network create my-network + +# Run container in a network +docker run --net my-network ... +``` + +Example: MongoDB + Mongo Express on same network can communicate via service name. + +--- + +## Docker WSL2 Error (Windows) + +### Issue: + +``` +Failed to configure network (networkingMode Nat)... +``` + +### Fix: + +Create or edit the file at: + +``` +C:\Users\LENOVO\.wslconfig +``` + +Add: + +``` +[wsl2] +networkingMode=None +``` + +Then restart Docker Desktop. + +--- + +## Docker Compose + +Docker Compose lets you define and run multi-container apps using YAML. + +### Example: + +```yaml +version: '3' +services: + app: + image: my-app + ports: + - "3000:3000" + environment: + - NODE_ENV=production + + mongodb: + image: mongo + ports: + - "27017:27017" + environment: + - MONGO_INITDB_ROOT_USERNAME=admin + - MONGO_INITDB_ROOT_PASSWORD=secret +``` + +### Commands: + +```bash +docker-compose -f docker-compose.yml up +docker-compose down +``` + +- All services run in the same default Docker network. +- Indentation in YAML is **critical**. + +--- + +## `Dockerfile` + +A `Dockerfile` is a script used to build Docker images. + +### Example: + +```Dockerfile +FROM node:18 + +ENV NODE_ENV=production + +# Inside container +RUN mkdir -p /home/app + +# Copy from host into container +COPY ./home/app /home/app + +WORKDIR /home/app + +CMD ["node", "server.js"] +``` + +Build with: + +```bash +docker build -t my-node-app . +``` + +Then run it with: + +```bash +docker run -p 3000:3000 my-node-app +``` + diff --git a/ProjectOrientedSessions/Session10/Docker.md b/ProjectOrientedSessions/Session10/Docker.md deleted file mode 100644 index f305a1c..0000000 --- a/ProjectOrientedSessions/Session10/Docker.md +++ /dev/null @@ -1,186 +0,0 @@ - - -# Docker? - -# Container? -A way to package application with everything they need inside the package. that package is portable and can be shared and moved around. - -The place of containers? they live in a **container repository** -Some companies have private repositories -There is a public repository for Docker: DockerHub - -# How Containers Helped? -Before container, people had to install all the things stuff -Problems: Installation process is different on different OS. There are many steps for installing applications and this is prone to errors -With Container: You do not have to install anything -The container is in its own isolated environment. -everything needed is packaged with all needed configuration. -the download is just one command -You can also some 2 different versions of the same app - - -## Deployment: -before: -people would produce artificats with a set of instructions on how to do it. -you would have a jar file or stuff -development would give it to operators and all -problem: you need to install everything... -misunderstandings... -after: -No envioronmental configuration needed on server - except docker runtime - -# Container: -## Layers of images -## Mostly Linux Base Image, because small in size (alpine) -## Application image on top - -# Docker Image vs Container -Image: actual package. artifact that can be moved around -Container: actually start the application. container envioronment is created - -# Docker vs VM? - -Docker works on OS level. - -OS Layers: OS Kernel -> Application - -Docker: virtualizes the application layer -VM: virtualizes OS Kernel as well - -Size of docker images are much smaller -Speed of docker is much faster -Compatibility: VM of any OS can be run on any other... there should be kernel compatibility. -Need to use docker DESKTOP - -# Docker Installation -# Image vs Container - - -Container is a running environment for IMAGE -Container: File System, Environment configs, application image(postgres, radis, mongo) -Container has a port binded. -The file system in Container is virtual - -All the artificts in docker hub are images, not containers - - -Running an image will create a container I guess. - - -docker ps -> list containers - -docker run -> start new container with a command - -docker stop CONTAINER_ID -docker start CONTAINER_ID - -docker ps -a => will show all, running or not running - - -How to use different versions of stuff -Run the containers with different versions - -# Container Port vs Host port: - -# Binding between laptop and container port: -during the run command => -docker run -pHOSTPORT:CONTAINERPORT - - -# Debugging Containers - -docker run -d -p - -docker logs CONTAINER_ID/NAME - -you can give names to containers, or some random thing is given - - -docker exec -it [CONTAINERID/NAME] /bin/bash -(interactive terminal) -use exit to exit - - -# Demo - - ## Docker Network - MongoDb - MongoExpress -Those packages in the same isolated docker network can connect directly to each othe or something - - -docker network ls - -## Creating docker network -docker network create mongo-network -docker run -p ... : .... -d [userpass... view documentation on docker hub] -net mongo-network -mongo - -## Error: -``` -deploying WSL2 distributions -ensuring main distro is deployed: deploying "docker-desktop": importing WSL distro "Failed to configure network (networkingMode Nat). To disable networking, set `wsl2.networkingMode=None` in C:\\Users\\LENOVO\\.wslconfig\r\nError code: Wsl/Service/RegisterDistro/CreateVm/ConfigureNetworking/HNS/0xffffffff\r\n" output="docker-desktop": exit code: 4294967295: running WSL command wsl.exe C:\WINDOWS\System32\wsl.exe --import docker-desktop \AppData\Local\Docker\wsl\main C:\Program Files\Docker\Docker\resources\wsl\wsl-bootstrap.tar --version 2: Failed to configure network (networkingMode Nat). To disable networking, set `wsl2.networkingMode=None` in \.wslconfig -Error code: Wsl/Service/RegisterDistro/CreateVm/ConfigureNetworking/HNS/0xffffffff -: exit status 0xffffffff -checking if isocache exists: CreateFile \\wsl$\docker-desktop-data\isocache\: The network name cannot be found. -``` - - -save - -``` -[wsl2] -networkingMode=None -``` -in Users/Lenovo as .wslconfig - - -# Compose -``` -version:'3' -services: - name: - image:[image] - ports: - - HOST:CONTAINER - environment: - - SOMETHING=value - mongodb: - image:mongo - ports: - - 27017:27017 - environment: - - MONGO..._USERNAME=admin - -``` -Docker compose handles the same network thing -Indentation is important - - -``` -docker-compose -f ... up/down -``` - - -# Dockerfile -dockerfile -> image - -copy artifacts (jar, war, bundle.js) - -blueprint for building images - -``` -FROM node -(Alternative to the one in the docker compose file... that one is better) -ENV ...=... - ...=... - -(Directory is built INSIDE of a container) -RUN mkdir -p /home/app - -(This one is on HOST) -COPY ./home/app - -CMD ["node", "server.js"] -``` - -The name MUST be: Dockerfile \ No newline at end of file