Skip to content

Latest commit

 

History

History
964 lines (687 loc) · 27.4 KB

File metadata and controls

964 lines (687 loc) · 27.4 KB

KhoAI Developer Setup Guide

A complete, beginner-friendly guide to set up and run the KhoAI inventory management system on your local Windows machine with Xe Kem (Vietnamese Ice Cream & Dessert Shop) test data.

Estimated time: 45-60 minutes for first-time setup.


Table of Contents

  1. What You Will Set Up
  2. Install Required Software
  3. Download the KhoAI Source Code
  4. Start Infrastructure Services (Docker)
  5. Set Up the Backend (Python API)
  6. Run Database Migrations
  7. Start the Backend API Server
  8. Start the Celery Worker
  9. Set Up Odoo ERP
  10. Load Xe Kem Test Data
  11. Set Up the Web App
  12. Set Up the Mobile App (Optional)
  13. Verify Everything Works
  14. Daily Development Workflow
  15. Troubleshooting
  16. Service Ports Quick Reference

1. What You Will Set Up

KhoAI has several services that work together:

+------------------+     +------------------+     +------------------+
|   Web App        |     |   Mobile App     |     |   Odoo ERP       |
|   (React)        |     |   (Expo)         |     |   (Docker)       |
|   Port 3000      |     |   Port 8081      |     |   Port 8069      |
+--------+---------+     +--------+---------+     +--------+---------+
         |                         |                        |
         +------------+------------+                        |
                      |                                     |
              +-------v--------+                            |
              |  Backend API   +----------------------------+
              |  (FastAPI)     |
              |  Port 8000     |
              +---+----+---+---+
                  |    |   |
         +--------+  +-+  +--------+
         |           |             |
   +-----v---+ +----v----+ +------v-----+
   |PostgreSQL| |  Redis  | |   MinIO    |
   |Port 5432 | |Port 6379| |Port 9000   |
   +----------+ +---------+ +------------+

What each service does:

  • PostgreSQL - The main database that stores all KhoAI data
  • Redis - Handles background task queues (e.g., processing invoices)
  • MinIO - Stores uploaded files (invoice images, photos, voice recordings)
  • Backend API - The brain of the system (Python/FastAPI)
  • Celery Worker - Processes background tasks (invoice scanning, etc.)
  • Odoo - ERP system for purchase orders and inventory management
  • Web App - Browser-based dashboard for managing invoices
  • Mobile App - Phone app for scanning, voice commands, photo counting

2. Install Required Software

You need to install these programs on your computer. If you already have any of them, skip that step.

2.1 Install Git

Git is used to download and manage the source code.

  1. Go to https://git-scm.com/download/win
  2. Download the installer and run it
  3. Keep all default settings, click Next through the installer
  4. To verify, open Command Prompt (press Win + R, type cmd, press Enter):
    git --version
    
    You should see something like git version 2.43.0.windows.1

2.2 Install Docker Desktop

Docker runs the database, Redis, MinIO, and Odoo in containers (like lightweight virtual machines).

  1. Go to https://www.docker.com/products/docker-desktop/
  2. Download Docker Desktop for Windows
  3. Run the installer
  4. Important: During installation, make sure "Use WSL 2" is checked
  5. After installation, restart your computer
  6. Open Docker Desktop from the Start Menu - wait for it to fully start (the whale icon in the taskbar should stop animating)
  7. To verify, open Command Prompt:
    docker --version
    docker compose version
    

Note: Docker Desktop must be running whenever you work on KhoAI. You will see a whale icon in your system tray (bottom-right of taskbar).

2.3 Install Python 3.11+

Python runs the backend API server.

  1. Go to https://www.python.org/downloads/
  2. Download Python 3.11 or newer (e.g., Python 3.11.8)
  3. Run the installer
  4. IMPORTANT: Check the box that says "Add Python to PATH" at the bottom of the first screen
  5. Click Install Now
  6. To verify, open a new Command Prompt:
    python --version
    
    You should see Python 3.11.x or higher

2.4 Install Node.js 18+

Node.js runs the web app and mobile app.

  1. Go to https://nodejs.org/
  2. Download the LTS version (18.x or 20.x)
  3. Run the installer, keep all defaults
  4. To verify, open a new Command Prompt:
    node --version
    npm --version
    

2.5 Get Your API Keys

You need two API keys for the AI features. Ask the project lead (Thinh) for these keys, or create your own accounts:

  • Anthropic API Key (for invoice scanning with Claude AI)

  • OpenAI API Key (for voice commands with Whisper)

Note: These keys cost money per use. For development, usage is minimal (a few cents per invoice scan). Ask Thinh if you need shared development keys.


3. Download the KhoAI Source Code

Open Command Prompt and run:

cd %USERPROFILE%
git clone https://github.com/YOUR_ORG/kho-ai.git
cd kho-ai

Note: Replace the URL above with the actual repository URL. Ask Thinh if you don't know it. If you already have the code, just cd to the folder where it is.

After cloning, you should see this folder structure:

kho-ai/
├── backend/          <- Python API server
├── mobile/           <- Phone app (React Native/Expo)
├── web/              <- Web dashboard (React)
├── infrastructure/   <- Docker config, seed scripts
├── docs/             <- Documentation
└── README.md

4. Start Infrastructure Services (Docker)

This step starts PostgreSQL, Redis, and MinIO using Docker. Make sure Docker Desktop is running first (check for the whale icon in your taskbar).

4.1 Start KhoAI Infrastructure

Open Command Prompt:

cd %USERPROFILE%\kho-ai\infrastructure
docker compose up -d

What is -d? It means "detached" - the services run in the background so you can keep using your terminal.

Wait 1-2 minutes for everything to start. You will see output showing containers being created.

4.2 Verify Services Are Running

docker compose ps

You should see these containers with STATUS showing Up or healthy:

Container Name Status What It Does
khoai-postgres Up (healthy) Database
khoai-redis Up (healthy) Task queue
khoai-minio Up (healthy) File storage
khoai-minio-init Exited (0) Bucket setup (it's OK that it exited)
khoai-keycloak Up (healthy) Authentication

If a container is not healthy, wait another minute and check again. If it still fails, see Troubleshooting.

4.3 Verify MinIO is Accessible (Optional)

Open your browser and go to: http://localhost:9001

  • Username: minio_access_key
  • Password: minio_secret_key

You should see three buckets: invoices, counting-photos, voice-recordings.


5. Set Up the Backend (Python API)

5.1 Create a Python Virtual Environment

A virtual environment keeps KhoAI's Python packages separate from your system Python.

Open Command Prompt:

cd %USERPROFILE%\kho-ai\backend

python -m venv venv

This creates a venv folder inside backend/. This may take 30 seconds.

5.2 Activate the Virtual Environment

venv\Scripts\activate

Your command prompt should now show (venv) at the beginning of the line:

(venv) C:\Users\YourName\kho-ai\backend>

IMPORTANT: You must activate the virtual environment EVERY TIME you open a new terminal to work on the backend. If you don't see (venv), run venv\Scripts\activate again.

5.3 Install Python Dependencies

python -m pip install -r requirements.txt

This downloads and installs all required Python packages. It takes 2-5 minutes depending on your internet speed. You will see a lot of output - this is normal.

If you get errors about "Microsoft Visual C++", install the Visual C++ Build Tools. This is needed by some Python packages like opencv-python.

5.4 Create the Environment File

The .env file contains all configuration settings. Copy the example file and edit it:

copy .env.example .env

Now open the .env file in a text editor (Notepad, VS Code, etc.):

notepad .env

Find and update these lines with your actual API keys:

# AI Services
ANTHROPIC_API_KEY=sk-ant-your-actual-key-here
OPENAI_API_KEY=sk-your-actual-key-here

Everything else can stay as the default values. The defaults match the Docker services we started in Step 4.

Save and close the file.

IMPORTANT: Never share your .env file or commit it to Git. It contains secret keys.


6. Run Database Migrations

Migrations create the database tables that KhoAI needs. Make sure you are in the backend folder with the virtual environment activated.

cd %USERPROFILE%\kho-ai\backend
venv\Scripts\activate

alembic upgrade head

You should see output like:

INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> xxxx, initial schema
INFO  [alembic.runtime.migration] Running upgrade xxxx -> yyyy, seed dev data
...

If you see "connection refused", make sure Docker is running and the PostgreSQL container is healthy (go back to Step 4.2).


7. Start the Backend API Server

Option A: Using the Batch File (Easiest)

cd %USERPROFILE%\kho-ai\backend
venv\Scripts\activate
startUvi.bat

Option B: Manually

cd %USERPROFILE%\kho-ai\backend
venv\Scripts\activate
uvicorn app.main:app --reload --port 8000

You should see:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process
INFO:     Started server process
INFO:     Application startup complete.

Verify the API is Running

Open your browser and go to: http://localhost:8000/api/v1/docs

You should see the Swagger UI - an interactive API documentation page listing all available endpoints.

Also try: http://localhost:8000/health - you should see {"status": "healthy"}.

IMPORTANT: Keep this terminal window open. If you close it, the API server stops. You need to open NEW terminals for the next steps.


8. Start the Celery Worker

The Celery worker processes background tasks like invoice scanning. Open a new Command Prompt window (keep the API server terminal open).

Option A: Using the Batch File (Easiest)

cd %USERPROFILE%\kho-ai\backend
venv\Scripts\activate
startTasks.bat

Option B: Manually

cd %USERPROFILE%\kho-ai\backend
venv\Scripts\activate
celery -A app.tasks.celery_app worker --loglevel=info --pool=solo

Why --pool=solo? On Windows, Celery needs this flag to work correctly.

You should see:

 -------------- celery@YourPC v5.3.x
--- ***** -----
-- ******* ---- [config]
...
[tasks]
  . app.tasks.invoice_tasks.process_invoice
  ...
[... ready]

IMPORTANT: Keep this terminal window open too. You now have two terminals running: the API server and the Celery worker.


9. Set Up Odoo ERP

Odoo is the ERP system that manages purchase orders and inventory. We run it in Docker.

9.1 Start Odoo

Open a new Command Prompt:

cd %USERPROFILE%\kho-ai\infrastructure
docker compose -f docker-compose.odoo.yml up -d

Wait 1-2 minutes for Odoo to fully start.

9.2 Create the Odoo Database

  1. Open your browser and go to: http://localhost:8069

  2. You will see the Odoo Database Manager page

  3. Fill in these fields:

    Field Value
    Master Password admin
    Database Name xekem
    Email admin@xekem.com
    Password admin
    Phone number (leave empty)
    Language English
    Country Canada
    Demo data Uncheck this (we will load our own Xe Kem data)
  4. Click Create Database

  5. Wait 1-3 minutes - Odoo is creating the database and setting up default data

If you see "Database creation error", wait a moment and try again. The database service might still be starting up.

9.3 Install Required Modules

After the database is created, you will be logged in to Odoo automatically.

  1. Click the Apps menu (grid icon at the top-left, then "Apps")

  2. In the search bar at the top, remove the "Apps" filter by clicking the X next to it

  3. Install these modules one by one:

    Install Inventory:

    • Search for Inventory
    • Click the Install button next to "Inventory"
    • Wait for installation to complete

    Install Purchase:

    • Search for Purchase
    • Click Install
    • Wait for installation to complete

Tip: Each module takes 30-60 seconds to install. You will see a loading spinner.

9.4 Update Backend Configuration for Odoo

Open the backend .env file and make sure the Odoo settings are correct:

notepad %USERPROFILE%\kho-ai\backend\.env

Find the Odoo section and update it:

# Odoo
ODOO_URL=http://localhost:8069
ODOO_DB=xekem
ODOO_USER=admin@xekem.com
ODOO_PASSWORD=admin

Save the file.

Note: If the API server is already running, it will automatically reload when you save the .env file (thanks to --reload mode).


10. Load Xe Kem Test Data

Xe Kem is a Vietnamese ice cream and dessert shop with two locations in Canada. We use it as realistic test data for development.

What Gets Created

Odoo Data Count Examples
Product Categories 23 Packaging > Cups & Lids, Dry Materials > Spices, etc.
Warehouses 2 Mississauga (MSS), North York (NYK)
Suppliers 17 Cash & Carry, Mr. Dairy, PreGel, Viet Thai, etc.
Products ~90 Cups, lids, syrups, dairy, frozen items, etc.

10.1 Seed Odoo Data

Open a new Command Prompt:

cd %USERPROFILE%\kho-ai\infrastructure
python seed_xekem_odoo.py

Note: Before running, you may need to update the credentials inside the script. Open the file and check lines 19-22:

ODOO_URL = "http://localhost:8069"
ODOO_DB = "xekem"
ODOO_USERNAME = "admin@example.com"  # <- Change to admin@xekem.com
ODOO_PASSWORD = "admin"

If the email doesn't match what you used when creating the Odoo database, update it.

You should see output like:

======================================================================
  XE KEM - Odoo Seed Data Script
  Vietnamese Ice Cream & Dessert Shop
======================================================================

[1/8] Connecting to Odoo...
  Connected as UID: 2
[2/8] Creating Product Categories...
  [CREATED] Xe Kem Inventory
  [CREATED] Packaging
  ...
[5/8] Creating Suppliers...
  [CREATED] A1 Supplier (A1)
  [CREATED] Cash & Carry (CC)
  ...
[6/8] Creating Products - Packaging & Tools...
  [CREATED] PKG-CC-003 - Cup 9oz (Box of 1000)
  ...
======================================================================
  Xe Kem seed data creation completed!
======================================================================

10.2 Verify Odoo Data (Optional)

Open http://localhost:8069 and check:

  • Inventory > Products - you should see ~90 products
  • Purchase > Vendors (or Contacts with Vendor filter) - you should see 17 suppliers
  • Inventory > Configuration > Warehouses - you should see MSS and NYK

10.3 Seed KhoAI Data

This syncs the Odoo data into KhoAI and sets up supplier name patterns for automatic invoice matching.

Make sure the Backend API server is running (from Step 7) before running this.

cd %USERPROFILE%\kho-ai\infrastructure
python seed_xekem_khoai.py

You should see:

======================================================================
  XE KEM - Kho-AI Seed Data Script
======================================================================

[1/5] Checking Kho-AI API connection...
  API is healthy: {"status": "healthy"}
[2/5] Syncing suppliers from Odoo...
  Created: 17
  Updated: 0
  Total: 17
[3/5] Updating suppliers with name patterns...
  [UPDATED] Cash & Carry -> patterns: ['cash & carry', 'cash and carry', 'cash&carry']...
  ...
[4/5] Syncing products from Odoo...
  Created: 90
  ...
======================================================================
  Kho-AI seed data setup completed!
======================================================================

If you see "Cannot connect to Kho-AI", make sure the backend API server is running (Step 7).

If supplier sync fails with Odoo error, double-check the Odoo credentials in backend/.env match what you used to create the Odoo database.


11. Set Up the Web App

Open a new Command Prompt:

cd %USERPROFILE%\kho-ai\web

npm install

This downloads all JavaScript packages. Takes 1-3 minutes.

Then start the development server:

npm run dev

You should see:

  VITE v5.x.x  ready in xxx ms

  ➜  Local:   http://localhost:3000/
  ➜  Network: use --host to expose

Open your browser and go to: http://localhost:3000

You should see the KhoAI web dashboard. The web app connects to the backend API on port 8000 automatically (via Vite proxy).

Keep this terminal open while you work with the web app.


12. Set Up the Mobile App (Optional)

The mobile app requires either a physical Android/iOS device or an emulator. This step is optional - the web app provides the same functionality.

12.1 Install Expo CLI

npm install -g expo-cli

12.2 Install Dependencies

Open a new Command Prompt:

cd %USERPROFILE%\kho-ai\mobile

npm install

12.3 Start Expo

npx expo start

This shows a QR code in the terminal.

12.4 Run on Your Phone

  1. Install Expo Go app from your phone's app store (Google Play / Apple App Store)
  2. Scan the QR code with your phone camera (iOS) or Expo Go app (Android)
  3. The app will load on your phone

12.5 Run on Android Emulator (Alternative)

If you have Android Studio installed:

  1. Open Android Studio > Virtual Device Manager > Start an emulator
  2. Open a new Command Prompt:
    cd %USERPROFILE%\kho-ai\mobile
    startExpoReverse.bat
    This sets up port forwarding so the emulator can reach your local backend.

13. Verify Everything Works

Let's test the full system end-to-end.

13.1 Check API Health

Open your browser: http://localhost:8000/health

Expected: {"status": "healthy"}

13.2 Check Products Were Loaded

Open Command Prompt:

curl -H "Authorization: Bearer dev-token" http://localhost:8000/api/v1/products?page_size=5

You should see JSON with product data (Cup 9oz, Sugar, etc.).

What is dev-token? In development mode, the backend accepts Bearer dev-token as authentication, so you don't need to set up Keycloak login. This only works when ENVIRONMENT=development in the .env file.

13.3 Check Suppliers Were Loaded

curl -H "Authorization: Bearer dev-token" http://localhost:8000/api/v1/suppliers?page_size=100

You should see 17 suppliers with their name patterns.

13.4 Test Invoice Scanning (Full Flow)

Upload one of the test receipt images:

curl -X POST -H "Authorization: Bearer dev-token" -F "file=@%USERPROFILE%\kho-ai\backend\tests\receipts\xekem\CashAndCarry_2026Feb03.png" http://localhost:8000/api/v1/invoices/scan

Or use the web app at http://localhost:3000 - click "Upload Invoice" and select a test receipt from backend\tests\receipts\xekem\.

Available test receipts:

File Supplier Contents
CashAndCarry_2026Feb03.png Cash & Carry Cups, lids, boxes, gloves
FoodsUp_2026Feb02.png Foods Up Eggs, flour, sugar
FreshCo_2026Feb05.png FreshCo Dairy, fresh produce
HDBio_2026Jan30.png HD Bio Packaging boxes, containers
MrDairy_2026Feb04.png Mr. Dairy Milk, whipping cream, butter
PreGel_2026Jan25.png PreGel Ice cream base, stabilizer
VietThai_2026Jan28.png Viet Thai Thai tea, condensed milk, durian
MilkTeaSupply_2026Jan31.png Milk Tea Supply Syrups, tea, flavourings
SeowNation_2026Feb05.png Seow Nation Frozen durian
LuckySupermarket_2026Feb01.png Lucky Supermarket Asian groceries, spices

14. Daily Development Workflow

Every day when you start working, follow these steps:

14.1 Start Docker (If Not Already Running)

Make sure Docker Desktop is running (whale icon in taskbar).

cd %USERPROFILE%\kho-ai\infrastructure
docker compose up -d
docker compose -f docker-compose.odoo.yml up -d

14.2 Start the Backend API

Open Terminal 1:

cd %USERPROFILE%\kho-ai\backend
venv\Scripts\activate
startUvi.bat

14.3 Start the Celery Worker

Open Terminal 2:

cd %USERPROFILE%\kho-ai\backend
venv\Scripts\activate
startTasks.bat

14.4 Start the Web App

Open Terminal 3:

cd %USERPROFILE%\kho-ai\web
npm run dev

14.5 Open in Browser

Summary of Terminals

You will typically have 3 terminal windows open:

Terminal What Runs How to Start
Terminal 1 Backend API venv\Scripts\activate then startUvi.bat
Terminal 2 Celery Worker venv\Scripts\activate then startTasks.bat
Terminal 3 Web App npm run dev

Docker services run in the background - you don't need a terminal for them.

Stop Everything at End of Day

To stop Docker services:

cd %USERPROFILE%\kho-ai\infrastructure
docker compose down
docker compose -f docker-compose.odoo.yml down

Note: docker compose down stops the containers but keeps your data. Your database, files, and Odoo data are preserved in Docker volumes.

To stop the backend, Celery, or web app: press Ctrl + C in their respective terminals.


15. Troubleshooting

"docker" is not recognized

  • Make sure Docker Desktop is installed and running
  • Restart your Command Prompt after installing Docker
  • Check that Docker is in your PATH: where docker

"python" is not recognized

  • Re-install Python and check "Add Python to PATH"
  • Or try python3 instead of python
  • Restart your Command Prompt after installing Python

Docker containers fail to start / port already in use

Check if something else is using the port:

netstat -ano | findstr :5432
netstat -ano | findstr :6379
netstat -ano | findstr :8000

If you see a process using the port, you can stop it:

taskkill /PID <the-process-id> /F

Common conflicts:

  • Port 5432: Another PostgreSQL installation
  • Port 6379: Another Redis installation
  • Port 8000: Another Python server

"alembic upgrade head" fails with connection error

sqlalchemy.exc.OperationalError: connection refused

This means PostgreSQL is not running. Fix:

cd %USERPROFILE%\kho-ai\infrastructure
docker compose up -d postgres

Wait 30 seconds, then try alembic again.

"ModuleNotFoundError: No module named ..."

You forgot to activate the virtual environment:

cd %USERPROFILE%\kho-ai\backend
venv\Scripts\activate

Or a package is missing:

pip install -r requirements.txt

Odoo database creation fails

  1. Check Odoo is running: docker ps | findstr odoo
  2. Check Odoo logs: docker logs odoo
  3. If the database xekem already exists, you can drop it:

seed_xekem_odoo.py authentication error

ERROR: Authentication failed. Check credentials.

Open the seed script and update the credentials:

notepad %USERPROFILE%\kho-ai\infrastructure\seed_xekem_odoo.py

Change ODOO_USERNAME (line 21) to match the email you used when creating the Odoo database (e.g., admin@xekem.com).

seed_xekem_khoai.py cannot connect

ERROR: Cannot connect to Kho-AI at http://localhost:8000

Make sure the backend API server is running (Step 7). Open a browser and check http://localhost:8000/health.

Web app shows "Network Error" or blank page

  • Make sure the backend API is running on port 8000
  • Check browser console (F12 > Console tab) for error messages
  • Try clearing browser cache: Ctrl + Shift + Delete

npm install fails

Try clearing the npm cache:

npm cache clean --force
rd /s /q node_modules
del package-lock.json
npm install

Celery worker crashes on Windows

Make sure you use --pool=solo:

celery -A app.tasks.celery_app worker --loglevel=info --pool=solo

Or just use the batch file startTasks.bat which includes this flag.

"Microsoft Visual C++ is required"

Some Python packages need C++ build tools. Install them:

  1. Go to https://visualstudio.microsoft.com/visual-cpp-build-tools/
  2. Download and run the installer
  3. Check "Desktop development with C++" workload
  4. Install and restart your terminal
  5. Re-run pip install -r requirements.txt

How to reset everything and start fresh

If things are really broken and you want to start over:

# Stop all Docker containers and DELETE all data
cd %USERPROFILE%\kho-ai\infrastructure
docker compose down -v
docker compose -f docker-compose.odoo.yml down -v

# Delete the Python virtual environment
cd %USERPROFILE%\kho-ai\backend
rd /s /q venv

# Delete node_modules
cd %USERPROFILE%\kho-ai\web
rd /s /q node_modules

cd %USERPROFILE%\kho-ai\mobile
rd /s /q node_modules

Then start again from Step 4.

WARNING: docker compose down -v deletes ALL data in Docker volumes (database, files, Odoo data). Only do this if you want a completely fresh start.


16. Service Ports Quick Reference

Service URL Credentials
Backend API http://localhost:8000 Bearer dev-token header
API Docs (Swagger) http://localhost:8000/api/v1/docs -
Web App http://localhost:3000 -
Odoo ERP http://localhost:8069 admin@xekem.com / admin
MinIO Console http://localhost:9001 minio_access_key / minio_secret_key
Keycloak Admin http://localhost:8080 admin / admin
PostgreSQL localhost:5432 khoai / khoai_dev_password
Redis localhost:6379 (no password)
MinIO API localhost:9000 minio_access_key / minio_secret_key
Odoo DB (PostgreSQL) localhost:5433 odoo / odoo

Need Help?

  • Ask Thinh - for API keys, project questions, or if you're stuck
  • Check the README - kho-ai\README.md for API endpoint details
  • Check Odoo guide - kho-ai\OdooDevelopmentGuide.md for Odoo-specific help
  • API documentation - http://localhost:8000/api/v1/docs (interactive, try endpoints directly)
  • Test voice commands - see kho-ai\VoiceTestCommands.md for Vietnamese/English examples