{"id":31425145,"url":"https://github.com/michaelwp/jatistore","last_synced_at":"2025-09-30T04:57:20.675Z","repository":{"id":305431979,"uuid":"1022848552","full_name":"michaelwp/jatistore","owner":"michaelwp","description":null,"archived":false,"fork":false,"pushed_at":"2025-07-27T14:39:51.000Z","size":12320,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-27T16:39:08.640Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/michaelwp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-20T01:05:19.000Z","updated_at":"2025-07-27T14:38:36.000Z","dependencies_parsed_at":"2025-07-20T04:50:31.264Z","dependency_job_id":"e5011f9a-f154-4a15-9f1b-292846f4e375","html_url":"https://github.com/michaelwp/jatistore","commit_stats":null,"previous_names":["michaelwp/jatistore"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/michaelwp/jatistore","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fjatistore","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fjatistore/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fjatistore/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fjatistore/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/michaelwp","download_url":"https://codeload.github.com/michaelwp/jatistore/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fjatistore/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":277632377,"owners_count":25850734,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-30T02:00:09.208Z","response_time":75,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-30T04:57:19.133Z","updated_at":"2025-09-30T04:57:20.669Z","avatar_url":"https://github.com/michaelwp.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JatiStore - Point of Sales (POS) System\n\nA modern, robust Point of Sales system built with Go, PostgreSQL, and Fiber web framework. JatiStore provides comprehensive inventory management, customer management, order processing, payment handling, and receipt generation with full transaction tracking and audit capabilities.\n\n## 🚀 Features\n\n- **🔐 User Authentication**: JWT-based authentication with role-based access control\n- **👥 User Management**: Complete user administration with admin, user, and cashier roles\n- **🔒 Secure Access**: All features protected by authentication with proper authorization\n- **Product Management**: Complete CRUD operations for products with category organization\n- **Category Management**: Hierarchical product categorization system\n- **Inventory Management**: Real-time stock level tracking across multiple locations\n- **Customer Management**: Complete customer database with search capabilities\n- **Order Processing**: Create and manage sales orders with multiple items\n- **Payment Processing**: Support for multiple payment methods (cash, card, transfer, digital wallet)\n- **Receipt Generation**: Automatic receipt generation for completed orders\n- **Transaction Tracking**: Complete audit trail of all inventory movements and sales\n- **RESTful API**: Clean, intuitive API endpoints with comprehensive documentation\n- **PostgreSQL Database**: Robust, scalable database with proper indexing and constraints\n- **Swagger UI**: Interactive API documentation with live testing capabilities\n- **Environment Configuration**: Flexible configuration management for different environments\n\n## 📁 Project Structure\n\n```\njatistore/\n├── main.go                 # Application entry point\n├── go.mod                  # Go module file\n├── go.sum                  # Go module checksums\n├── env.example             # Environment variables example\n├── README.md               # This file\n├── AUTHENTICATION.md       # Authentication system documentation\n├── test_auth.sh           # Authentication testing script\n├── Makefile                # Build and management commands\n├── docs/                   # Swagger API documentation (auto-generated)\n│   ├── docs.go\n│   ├── swagger.json\n│   └── swagger.yaml\n├── bin/                    # Compiled binary output\n└── internal/               # Internal application code\n    ├── config/             # Configuration management\n    ├── database/           # Database connection and setup\n    │   └── migrations/     # Database migration files\n    ├── models/             # Data models and structures\n    ├── repository/         # Data access layer\n    ├── services/           # Business logic layer\n    ├── handlers/           # HTTP request handlers\n    ├── middleware/         # HTTP middleware\n    └── router/             # Route definitions\n```\n\n## ⚙️ Prerequisites\n\n- **Go 1.24** or higher\n- **PostgreSQL 12** or higher\n- **Git**\n\n## 🛠️ Makefile Commands\n\nThe project includes a comprehensive `Makefile` for common development tasks:\n\n| Command         | Description                                                      |\n|-----------------|------------------------------------------------------------------|\n| `make build`    | Build the application binary into the `bin/` directory           |\n| `make run`      | Run the application using `go run main.go`                       |\n| `make swag`     | Generate Swagger API documentation into the `docs/` directory    |\n| `make tidy`     | Clean up and verify Go module dependencies                       |\n| `make clean`    | Remove the `bin/` and `docs/` directories                        |\n| `make lint`     | Run golangci-lint for code quality checks                        |\n| `make pre-commit` | Run pre-commit checks including linting                        |\n| `make install-hooks` | Install git hooks for automated checks                      |\n| `make migrate-up`   | Apply all database migrations (requires `migrate` tool)      |\n| `make migrate-down` | Roll back the last database migration (requires `migrate`)   |\n\n\u003e **Note:**\n\u003e - `make migrate-up` and `make migrate-down` require the [golang-migrate](https://github.com/golang-migrate/migrate) CLI tool to be installed.\n\u003e - `make swag` requires the [swag CLI](https://github.com/swaggo/swag) to be installed.\n\n## 🚀 Quick Start\n\n### 1. Clone and Setup\n```bash\ngit clone \u003crepository-url\u003e\ncd jatistore\ngo mod tidy\n```\n\n### 2. Database Setup\n```bash\n# Create PostgreSQL database\ncreatedb jatistore\n\n# Or using psql\npsql -U postgres -c \"CREATE DATABASE jatistore;\"\n```\n\n### 3. Environment Configuration\n```bash\ncp env.example .env\n# Edit .env file with your database credentials, JWT_SECRET, SALT, and ROUND\n```\n\nExample `.env` configuration:\n```env\nDB_HOST=localhost\nDB_PORT=5432\nDB_USER=y_username\nDB_PASSWORD=y_password\nDB_NAME=y_database\nPORT=8080\nENVIRONMENT=development\nLOG_LEVEL=info\nJWT_SECRET=your-secret-key-here\nSALT=your-random-salt-string\nROUND=12\n```\n\n### 4. Generate API Documentation\n```bash\nmake swag\n```\n\n### 5. Run the Application\n```bash\nmake run\n```\n\nThe server will start on `http://localhost:8080`\n\n### 6. Set Up Authentication\n```bash\n# Register your first admin user\ncurl -X POST http://localhost:8080/api/v1/auth/register \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"admin\",\n    \"email\": \"admin@jatistore.com\",\n    \"password\": \"admin123\",\n    \"role\": \"admin\"\n  }'\n\n# Login to get JWT token\ncurl -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"admin\",\n    \"password\": \"admin123\"\n  }'\n```\n\n## 📚 API Documentation\n\n### Swagger UI\nAfter running the app and generating docs, visit:\n```\nhttp://localhost:8080/swagger/index.html\n```\n\nHere you can view and interact with the complete API documentation.\n\n## 🔌 API Endpoints\n\n### Health Check\n- `GET /health` - Check if the API is running\n\n### Authentication (Public Endpoints)\n- `POST /api/v1/auth/register` - Register a new user account\n- `POST /api/v1/auth/login` - Login and get JWT token\n\n### Authentication (Protected Endpoints)\nAll endpoints below require a valid JWT token in the Authorization header:\n```\nAuthorization: Bearer \u003cjwt_token\u003e\n```\n\n- `GET /api/v1/auth/profile` - Get current user profile\n- `PUT /api/v1/auth/profile` - Update current user profile\n- `POST /api/v1/auth/change-password` - Change current user password\n\n### User Management (Admin Only)\n- `GET /api/v1/auth/users` - Get all users\n- `GET /api/v1/auth/users/:id` - Get user by ID\n- `PUT /api/v1/auth/users/:id` - Update user\n- `DELETE /api/v1/auth/users/:id` - Delete user\n\n### Categories (Authentication Required)\n- `GET /api/v1/categories` - Get all categories\n- `GET /api/v1/categories/:id` - Get category by ID\n- `POST /api/v1/categories` - Create a new category\n- `PUT /api/v1/categories/:id` - Update a category\n- `DELETE /api/v1/categories/:id` - Delete a category\n\n### Products (Authentication Required)\n- `GET /api/v1/products` - Get all products\n- `GET /api/v1/products/:id` - Get product by ID\n- `POST /api/v1/products` - Create a new product\n- `PUT /api/v1/products/:id` - Update a product\n- `DELETE /api/v1/products/:id` - Delete a product\n\n### Inventory (Authentication Required)\n- `GET /api/v1/inventory` - Get all inventory records\n- `GET /api/v1/inventory/:id` - Get inventory by ID\n- `POST /api/v1/inventory` - Create a new inventory record\n- `PUT /api/v1/inventory/:id` - Update an inventory record\n- `DELETE /api/v1/inventory/:id` - Delete an inventory record\n- `POST /api/v1/inventory/adjust` - Adjust stock levels and record transactions\n\n### Customers (Authentication Required)\n- `GET /api/v1/customers` - Get all customers\n- `GET /api/v1/customers/search` - Search customers by name, email, or phone\n- `GET /api/v1/customers/:id` - Get customer by ID\n- `POST /api/v1/customers` - Create a new customer\n- `PUT /api/v1/customers/:id` - Update a customer\n- `DELETE /api/v1/customers/:id` - Delete a customer\n\n### Orders (Authentication Required)\n- `GET /api/v1/orders` - Get all orders\n- `GET /api/v1/orders/:id` - Get order by ID\n- `POST /api/v1/orders` - Create a new order\n- `PUT /api/v1/orders/:id/status` - Update order status\n- `POST /api/v1/orders/:id/payments` - Process payment for an order\n- `POST /api/v1/orders/:id/receipt` - Generate receipt for an order\n- `GET /api/v1/customers/:customerId/orders` - Get orders by customer\n\n## ✨ Automatic Field Generation\n\n### SKU Generation\nWhen creating or updating products, if the `sku` field is not provided or is empty, the system automatically generates a unique SKU using the format:\n```\nSKU-{8-character-uuid}\n```\nExample: `SKU-a1b2c3d4`\n\n### Barcode Number Generation\nWhen creating or updating products, if the `barcode_number` field is not provided or is empty, the system automatically generates a unique barcode number using the format:\n```\nBC-{8-character-uuid}\n```\nExample: `BC-e5f6g7h8`\n\n### Benefits\n- **No Duplicate Errors**: Prevents duplicate key constraint violations\n- **Unique Identification**: Every product gets a unique SKU and barcode\n- **Simplified API Calls**: Optional fields make API calls easier\n- **Consistent Format**: Predictable format for generated values\n\n### Example: Creating Product Without SKU/Barcode\n```bash\ncurl -X POST http://localhost:8080/api/v1/products \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"iPhone 15\",\n    \"description\": \"Latest iPhone model\",\n    \"category_id\": \"category-uuid-here\",\n    \"price\": 999.99\n  }'\n```\nThis will automatically generate both SKU and barcode_number.\n\n## 🔐 Authentication \u0026 Authorization\n\n### User Password Policy\n- **Minimum 8 characters**\n- **At least 1 numeric character**\n- **At least 1 symbol**\n- **At least 1 uppercase letter**\n- Passwords are hashed using bcrypt with a configurable cost (rounds) and a secret salt from the environment.\n\n### Password Hashing Configuration\n- **SALT**: A secret string from the environment, prepended to the password before hashing.\n- **ROUND**: Bcrypt cost (number of hashing rounds, default: 12). Set in the environment.\n\n### User Roles\n- **admin**: Full access to all features including user management\n- **user**: Standard access to POS features\n- **cashier**: Access to order processing and basic features\n\n### Security Features\n- **JWT Tokens**: Secure token-based authentication with 24-hour expiration\n- **Password Hashing**: All passwords securely hashed using bcrypt\n- **Role-Based Access**: Server-side role validation for all protected routes\n- **Input Validation**: Comprehensive validation for all user inputs\n- **Account Management**: Users can be activated/deactivated without deletion\n\n### Authentication Flow\n1. **Register** a new user account (or login with existing credentials)\n2. **Login** to receive a JWT token\n3. **Include token** in all subsequent API requests\n4. **Token expires** after 24 hours (re-login required)\n\nFor detailed authentication documentation, see [AUTHENTICATION.md](AUTHENTICATION.md).\n\n## 💡 API Examples\n\n### Authentication Examples\n\n#### Register a New User\n```bash\ncurl -X POST http://localhost:8080/api/v1/auth/register \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"admin\",\n    \"email\": \"admin@jatistore.com\",\n    \"password\": \"admin123\",\n    \"role\": \"admin\"\n  }'\n```\n\n#### Login and Get Token\n```bash\ncurl -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"admin\",\n    \"password\": \"admin123\"\n  }'\n```\n\n#### Access Protected Endpoint\n```bash\ncurl -X GET http://localhost:8080/api/v1/products \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\"\n```\n\n### Create a Category\n```bash\ncurl -X POST http://localhost:8080/api/v1/categories \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"Electronics\",\n    \"description\": \"Electronic devices and accessories\"\n  }'\n```\n\n### Create a Product\n```bash\ncurl -X POST http://localhost:8080/api/v1/products \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"iPhone 15\",\n    \"description\": \"Latest iPhone model with advanced features\",\n    \"sku\": \"IPHONE-15-128GB\",           # Optional - auto-generated if not provided\n    \"barcode_number\": \"1234567890123\",  # Optional - auto-generated if not provided\n    \"category_id\": \"category-uuid-here\",\n    \"price\": 999.99\n  }'\n```\n\n### Create Inventory Record\n```bash\ncurl -X POST http://localhost:8080/api/v1/inventory \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"product_id\": \"product-uuid-here\",\n    \"quantity\": 50,\n    \"location\": \"Warehouse A\"\n  }'\n```\n\n### Adjust Stock (Record Transaction)\n```bash\n# Add stock (incoming shipment)\ncurl -X POST http://localhost:8080/api/v1/inventory/adjust \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"product_id\": \"product-uuid-here\",\n    \"quantity\": 25,\n    \"type\": \"in\",\n    \"reason\": \"New shipment received\",\n    \"reference\": \"PO-2024-001\"\n  }'\n\n# Remove stock (sale or loss)\ncurl -X POST http://localhost:8080/api/v1/inventory/adjust \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"product_id\": \"product-uuid-here\",\n    \"quantity\": 5,\n    \"type\": \"out\",\n    \"reason\": \"Customer order fulfilled\",\n    \"reference\": \"SO-2024-005\"\n  }'\n\n# Manual adjustment (stock count correction)\ncurl -X POST http://localhost:8080/api/v1/inventory/adjust \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"product_id\": \"product-uuid-here\",\n    \"quantity\": 45,\n    \"type\": \"adjustment\",\n    \"reason\": \"Physical count correction\",\n    \"reference\": \"STOCK-COUNT-2024-01\"\n  }'\n```\n\n### Create a Customer\n```bash\ncurl -X POST http://localhost:8080/api/v1/customers \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"John Doe\",\n    \"email\": \"john.doe@example.com\",\n    \"phone\": \"+1234567890\",\n    \"address\": \"123 Main St, City, State 12345\"\n  }'\n```\n\n### Create an Order\n```bash\ncurl -X POST http://localhost:8080/api/v1/orders \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"customer_id\": \"customer-uuid-here\",\n    \"items\": [\n      {\n        \"product_id\": \"product-uuid-here\",\n        \"quantity\": 2,\n        \"discount\": 10.00\n      }\n    ],\n    \"tax_amount\": 15.00,\n    \"discount_amount\": 5.00,\n    \"notes\": \"Customer requested express delivery\"\n  }'\n```\n\n### Process Payment\n```bash\ncurl -X POST http://localhost:8080/api/v1/orders/order-uuid-here/payments \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"amount\": 150.00,\n    \"payment_method\": \"card\",\n    \"reference\": \"TXN-123456\"\n  }'\n```\n\n### Generate Receipt\n```bash\ncurl -X POST http://localhost:8080/api/v1/orders/order-uuid-here/receipt \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\"\n```\n\n## 🗄️ Database Schema\n\nThe application automatically creates the following tables with proper relationships and constraints:\n\n### Core Tables\n- **users**: User accounts with authentication and role management\n- **categories**: Product categories with unique names\n- **products**: Product information linked to categories. Fields:\n  - `id` (UUID): Product ID\n  - `name` (string): Product name (required)\n  - `description` (string): Product description\n  - `sku` (string): Stock Keeping Unit (optional, auto-generated as \"SKU-{8-char-uuid}\" if not provided)\n  - `barcode_number` (string): Barcode number (optional, auto-generated as \"BC-{8-char-uuid}\" if not provided)\n  - `category_id` (UUID): Linked category (required)\n  - `price` (float): Product price (required)\n  - `created_at`, `updated_at` (timestamp)\n- **inventory**: Stock levels and locations (unique constraint on product_id + location)\n- **inventory_transactions**: Complete audit trail of all stock movements\n- **customers**: Customer information with unique email addresses\n- **orders**: Sales orders with customer association and status tracking\n- **order_items**: Individual items within orders with pricing and discounts\n- **payments**: Payment records for orders with multiple payment method support\n- **receipts**: Receipt records for completed orders\n\n### Key Features\n- **Foreign Key Constraints**: Proper referential integrity\n- **Unique Constraints**: Prevent duplicate entries where appropriate\n- **Check Constraints**: Ensure data validity (e.g., non-negative quantities)\n- **Indexes**: Optimized for common query patterns\n- **Cascade Deletes**: Automatic cleanup of related records\n- **Automatic Numbering**: Order and receipt numbers generated automatically\n- **Transaction Support**: Database transactions for data consistency\n- **Password Security**: Bcrypt hashing for user passwords\n\n## 🔄 Inventory Transactions\n\nThe system automatically tracks all inventory movements through the `inventory_transactions` table:\n\n### Transaction Types\n- **`in`**: Stock added (shipments, returns, etc.)\n- **`out`**: Stock removed (sales, damage, etc.)\n- **`adjustment`**: Manual stock corrections (physical counts, etc.)\n\n## 💳 Payment Processing\n\nThe POS system supports multiple payment methods and tracks payment status:\n\n### Payment Methods\n- **`cash`**: Cash payments\n- **`card`**: Credit/debit card payments\n- **`transfer`**: Bank transfer payments\n- **`digital_wallet`**: Digital wallet payments (e.g., PayPal, Apple Pay)\n\n### Payment Status\n- **`pending`**: Payment initiated but not completed\n- **`completed`**: Payment successfully processed\n- **`failed`**: Payment processing failed\n- **`refunded`**: Payment has been refunded\n\n## 📋 Order Management\n\n### Order Status\n- **`pending`**: Order created but not yet processed\n- **`completed`**: Order has been fulfilled\n- **`cancelled`**: Order has been cancelled\n\n### Order Features\n- **Automatic Numbering**: Orders get unique numbers (ORD-1000, ORD-1001, etc.)\n- **Customer Association**: Orders can be linked to customers (optional)\n- **Item Management**: Multiple items per order with individual pricing\n- **Discounts**: Item-level and order-level discounts\n- **Tax Calculation**: Support for tax amounts\n- **Payment Tracking**: Track payment status separately from order status\n- **`adjustment`**: Manual correction (stock counts, corrections)\n\n## 🔄 Complete POS Workflow\n\nHere's a typical workflow for processing a sale in the POS system:\n\n### 1. Setup (One-time)\n```bash\n# Register admin user (if not already done)\ncurl -X POST http://localhost:8080/api/v1/auth/register \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"admin\",\n    \"email\": \"admin@jatistore.com\",\n    \"password\": \"admin123\",\n    \"role\": \"admin\"\n  }'\n\n# Login to get token\nLOGIN_RESPONSE=$(curl -s -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"username\": \"admin\",\n    \"password\": \"admin123\"\n  }')\n\nTOKEN=$(echo $LOGIN_RESPONSE | grep -o '\"token\":\"[^\"]*\"' | cut -d'\"' -f4)\n\n# Create categories\ncurl -X POST http://localhost:8080/api/v1/categories \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\": \"Electronics\", \"description\": \"Electronic devices\"}'\n\n# Create products\ncurl -X POST http://localhost:8080/api/v1/products \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"iPhone 15\",\n    \"description\": \"Latest iPhone model\",\n    \"sku\": \"IPHONE-15-128GB\",\n    \"barcode_number\": \"1234567890123\",\n    \"category_id\": \"category-uuid-here\",\n    \"price\": 999.99\n  }'\n\n# Add inventory\ncurl -X POST http://localhost:8080/api/v1/inventory \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"product_id\": \"product-uuid-here\",\n    \"quantity\": 50,\n    \"location\": \"Main Store\"\n  }'\n```\n\n### 2. Customer Management\n```bash\n# Create customer (optional - can create anonymous orders)\ncurl -X POST http://localhost:8080/api/v1/customers \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"John Doe\",\n    \"email\": \"john@example.com\",\n    \"phone\": \"+1234567890\",\n    \"address\": \"123 Main St\"\n  }'\n```\n\n### 3. Create Order\n```bash\ncurl -X POST http://localhost:8080/api/v1/orders \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"customer_id\": \"customer-uuid-here\",\n    \"items\": [\n      {\n        \"product_id\": \"product-uuid-here\",\n        \"quantity\": 1,\n        \"discount\": 50.00\n      }\n    ],\n    \"tax_amount\": 75.00,\n    \"discount_amount\": 25.00,\n    \"notes\": \"Customer requested gift wrapping\"\n  }'\n```\n\n### 4. Process Payment\n```bash\ncurl -X POST http://localhost:8080/api/v1/orders/order-uuid-here/payments \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"amount\": 1000.00,\n    \"payment_method\": \"card\",\n    \"reference\": \"TXN-123456\"\n  }'\n```\n\n### 5. Generate Receipt\n```bash\ncurl -X POST http://localhost:8080/api/v1/orders/order-uuid-here/receipt \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Content-Type: application/json\"\n```\n\n### 6. Update Order Status\n```bash\ncurl -X PUT http://localhost:8080/api/v1/orders/order-uuid-here/status \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"status\": \"completed\"}'\n```\n\n## 🛠️ Troubleshooting\n\n### Common Issues\n\n#### Authentication Issues\n- **Error**: `Authorization header is required`\n- **Solution**: Include JWT token in Authorization header: `Authorization: Bearer \u003ctoken\u003e`\n- **Error**: `Invalid or expired token`\n- **Solution**: Re-login to get a new token (tokens expire after 24 hours)\n\n#### Database Connection Issues\n- **Error**: `failed to connect to database`\n- **Solution**: Check your `.env` file and ensure PostgreSQL is running\n- **Command**: `pg_isready -h localhost -p 5432`\n\n#### Port Already in Use\n- **Error**: `address already in use`\n- **Solution**: Change the port in your `.env` file or kill the existing process\n- **Command**: `lsof -ti:8080 | xargs kill -9`\n\n#### Missing Dependencies\n- **Error**: `go: module not found`\n- **Solution**: Run `go mod tidy` to download dependencies\n\n#### Swagger Documentation Issues\n- **Error**: Swagger UI not loading\n- **Solution**: Regenerate docs with `swag init -g main.go -o docs`\n\n### Performance Tips\n\n1. **Database Indexes**: The system automatically creates indexes for common queries\n2. **Connection Pooling**: Configured for optimal performance with 25 connections\n3. **Caching**: Consider adding Redis for session management in production\n4. **Load Balancing**: Use multiple instances behind a load balancer for high traffic\n\n## 🔒 Security Considerations\n\n### Production Deployment\n\n1. **Environment Variables**: Never commit `.env` files to version control\n2. **JWT Secret**: Use a strong, unique JWT secret in production\n3. **Database Security**: Use strong passwords and restrict database access\n4. **HTTPS**: Always use HTTPS in production\n5. **Rate Limiting**: Implement rate limiting for API endpoints\n6. **Authentication**: JWT authentication is already implemented\n7. **Input Validation**: All inputs are validated, but consider additional sanitization\n\n### Data Backup\n\n```bash\n# Backup database\npg_dump jatistore \u003e backup_$(date +%Y%m%d_%H%M%S).sql\n\n# Restore database\npsql jatistore \u003c backup_file.sql\n```\n\n## 📊 Monitoring and Logging\n\n### Application Logs\nThe application logs important events to stdout. In production, consider:\n- Structured logging with JSON format\n- Log aggregation (ELK stack, Fluentd)\n- Application performance monitoring (APM)\n\n### Database Monitoring\n- Monitor query performance with `EXPLAIN ANALYZE`\n- Set up database connection monitoring\n- Configure alerts for disk space and connection limits\n\n## 🚀 Deployment\n\n### Docker Deployment\n```dockerfile\nFROM golang:1.24-alpine AS builder\nWORKDIR /app\nCOPY . .\nRUN go mod download\nRUN go build -o main .\n\nFROM alpine:latest\nRUN apk --no-cache add ca-certificates\nWORKDIR /root/\nCOPY --from=builder /app/main .\nEXPOSE 8080\nCMD [\"./main\"]\n```\n\n### Environment Variables for Production\n```env\nDB_HOST=your-db-host\nDB_PORT=5432\nDB_USER=your-db-user\nDB_PASSWORD=your-secure-password\nDB_NAME=jatistore\nPORT=8080\nENVIRONMENT=production\nLOG_LEVEL=info\nJWT_SECRET=your-very-secure-jwt-secret-key\n```\n\n### Transaction Fields\n- **`product_id`**: Reference to the product\n- **`type`**: Transaction type (in/out/adjustment)\n- **`quantity`**: Amount of stock moved\n- **`reason`**: Human-readable reason for the transaction\n- **`reference`**: External reference (PO number, SO number, etc.)\n- **`created_at`**: Timestamp of the transaction\n\n### Benefits\n- **Complete Audit Trail**: Track every inventory change\n- **Compliance**: Meet regulatory and audit requirements\n- **Troubleshooting**: Easily identify and investigate issues\n- **Reporting**: Generate detailed inventory movement reports\n\n## 📡 API Response Format\n\nAll API endpoints return a consistent response format:\n\n### Success Response\n```json\n{\n  \"success\": true,\n  \"message\": \"Operation completed successfully\",\n  \"data\": {\n    // Response data here\n  }\n}\n```\n\n### Error Response\n```json\n{\n  \"success\": false,\n  \"error\": \"Error description\"\n}\n```\n\n### HTTP Status Codes\n- **200 OK**: Request successful\n- **201 Created**: Resource created successfully\n- **400 Bad Request**: Invalid request data\n- **401 Unauthorized**: Authentication required or invalid token\n- **403 Forbidden**: Insufficient permissions\n- **404 Not Found**: Resource not found\n- **409 Conflict**: Resource conflict (e.g., duplicate username/email)\n- **500 Internal Server Error**: Server error\n\n## 🔍 Advanced Queries\n\n### Search Customers\n```bash\n# Search by name, email, or phone\ncurl \"http://localhost:8080/api/v1/customers/search?q=john\" \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\"\n```\n\n### Get Customer Orders\n```bash\n# Get all orders for a specific customer\ncurl \"http://localhost:8080/api/v1/customers/customer-uuid-here/orders\" \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\"\n```\n\n### Update Order Status\n```bash\n# Mark order as completed\ncurl -X PUT http://localhost:8080/api/v1/orders/order-uuid-here/status \\\n  -H \"Authorization: Bearer \u003cyour_jwt_token\u003e\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"status\": \"completed\"}'\n```\n\n## 📈 Business Intelligence\n\n### Key Metrics Available\n- **Total Sales**: Sum of all completed orders\n- **Order Count**: Number of orders by status\n- **Customer Analytics**: Customer order history\n- **Product Performance**: Most sold products\n- **Payment Analytics**: Payment method distribution\n- **Inventory Levels**: Current stock levels\n- **User Activity**: Authentication and access patterns\n\n### Sample Queries\n```sql\n-- Total sales today\nSELECT SUM(total_amount) FROM orders \nWHERE DATE(created_at) = CURRENT_DATE \nAND payment_status = 'paid';\n\n-- Top selling products\nSELECT p.name, SUM(oi.quantity) as total_sold\nFROM order_items oi\nJOIN products p ON oi.product_id = p.id\nGROUP BY p.id, p.name\nORDER BY total_sold DESC\nLIMIT 10;\n\n-- Customer order history\nSELECT c.name, COUNT(o.id) as order_count, SUM(o.total_amount) as total_spent\nFROM customers c\nLEFT JOIN orders o ON c.id = o.customer_id\nGROUP BY c.id, c.name\nORDER BY total_spent DESC;\n\n-- User activity by role\nSELECT u.role, COUNT(*) as login_count\nFROM users u\nWHERE u.is_active = true\nGROUP BY u.role;\n```\n\n## 🛠️ Development\n\n### Running Tests\n```bash\ngo test ./...\n```\n\n### Testing Authentication\n```bash\n# Run the authentication test script\n./test_auth.sh\n```\n\n### Building for Production\n```bash\nmake build\n```\n\n### Database Migrations\nThe application automatically creates tables on startup. For production environments, consider using a proper migration tool like `golang-migrate`.\n\n### Code Structure\nThe application follows clean architecture principles:\n- **Handlers**: HTTP request/response handling\n- **Services**: Business logic and validation\n- **Repository**: Data access and persistence\n- **Models**: Data structures and validation rules\n- **Middleware**: Authentication and authorization\n\n## ⚙️ Environment Variables\n\n| Variable      | Description                  | Default      | Required |\n|---------------|------------------------------|--------------|----------|\n| `DB_HOST`     | Database host                | `localhost`  | Yes      |\n| `DB_PORT`     | Database port                | `5432`       | Yes      |\n| `DB_USER`     | Database user                | `y_username` | Yes      |\n| `DB_PASSWORD` | Database password            | `y_password` | Yes      |\n| `DB_NAME`     | Database name                | `y_database` | Yes      |\n| `PORT`        | Server port                  | `8080`       | No       |\n| `ENVIRONMENT` | Application environment      | `development`| No       |\n| `LOG_LEVEL`   | Logging level                | `info`       | No       |\n| `JWT_SECRET`  | JWT signing secret           | `your-secret-key` | No |\n| `SALT`        | Bcrypt salt for password hashing | (set your own) | Yes |\n| `ROUND`       | Bcrypt cost (rounds)         | `12`         | No |\n\n## 🤝 Contributing\n\nWe welcome contributions! Please follow these steps:\n\n1. **Fork** the repository\n2. **Create** a feature branch (`git checkout -b feature/amazing-feature`)\n3. **Commit** your changes (`git commit -m 'Add amazing feature'`)\n4. **Push** to the branch (`git push origin feature/amazing-feature`)\n5. **Open** a Pull Request\n\n### Development Guidelines\n- Follow Go coding standards and conventions\n- Add tests for new functionality\n- Update documentation as needed\n- Ensure all tests pass before submitting\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🆘 Support\n\nIf you encounter any issues or have questions:\n\n1. Check the [API Documentation](http://localhost:8080/swagger/index.html)\n2. Review the [Authentication Documentation](AUTHENTICATION.md)\n3. Review the [Issues](../../issues) page\n4. Create a new issue with detailed information\n\n## 🔄 Upgrade from Inventory to POS\n\nThis application has been upgraded from a simple inventory management system to a full-featured Point of Sales (POS) system with authentication. Here's what changed:\n\n### What's New\n- **🔐 User Authentication**: JWT-based authentication with role-based access control\n- **👥 User Management**: Complete user administration with admin, user, and cashier roles\n- **🔒 Secure Access**: All features protected by authentication with proper authorization\n- **Customer Management**: Complete customer database with search\n- **Order Processing**: Sales order creation and management\n- **Payment Processing**: Multiple payment methods support\n- **Receipt Generation**: Automatic receipt creation\n- **Enhanced API**: New endpoints for POS operations\n- **Business Intelligence**: Built-in analytics capabilities\n\n### Backward Compatibility\n- All existing inventory management features remain unchanged\n- Existing API endpoints continue to work but now require authentication\n- Database schema includes all original tables plus new POS and user tables\n- No data migration required\n\n### Migration Path\n1. **Existing Users**: Your current inventory data is preserved\n2. **Authentication Setup**: Register admin users to access the system\n3. **New Features**: Start using customer and order management\n4. **Gradual Adoption**: Use POS features as needed\n5. **Full Integration**: Eventually integrate inventory with sales\n\n### Benefits of the Upgrade\n- **Complete Business Solution**: From inventory to sales with security\n- **Secure Access**: Role-based authentication and authorization\n- **Customer Relationship Management**: Track customer history\n- **Sales Analytics**: Understand your business better\n- **Professional Receipts**: Generate proper sales receipts\n- **Payment Tracking**: Monitor cash flow and payments\n- **Audit Trail**: Complete transaction history\n- **User Management**: Multi-user support with proper access control\n\n---\n\n**Built with ❤️ using Go, PostgreSQL, and Fiber**\n\n*Upgraded from Inventory Management to Full POS System with Authentication* ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelwp%2Fjatistore","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichaelwp%2Fjatistore","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelwp%2Fjatistore/lists"}