Spaces:
Runtime error
Runtime error
PupaClic commited on
Commit Β·
d58df14
1
Parent(s): 624809f
docs: remove architecture documentation and refactor service layer
Browse files- Remove ARCHITECTURE.md documentation file
- Update README.md with current project information
- Refactor nosql.py database connection handling
- Update merchant_schema.py with improved validation logic
- Enhance employee_service.py with better error handling
- Improve merchant_service.py service methods
- Optimize sales_order_service.py query performance
- Update db_init.py database initialization utilities
- Consolidate documentation into codebase comments for maintainability
- ARCHITECTURE.md +0 -366
- README.md +226 -61
- app/nosql.py +67 -36
- app/schemas/merchant_schema.py +3 -2
- app/services/employee_service.py +11 -11
- app/services/merchant_service.py +8 -8
- app/services/sales_order_service.py +14 -14
- app/utils/db_init.py +29 -29
ARCHITECTURE.md
DELETED
|
@@ -1,366 +0,0 @@
|
|
| 1 |
-
# Merchant Module Architecture
|
| 2 |
-
|
| 3 |
-
## System Architecture
|
| 4 |
-
|
| 5 |
-
```
|
| 6 |
-
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 7 |
-
β FastAPI Application β
|
| 8 |
-
β (main.py) β
|
| 9 |
-
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
|
| 10 |
-
β
|
| 11 |
-
βββββββββββββββΌββββββββββββββ
|
| 12 |
-
β β β
|
| 13 |
-
βΌ βΌ βΌ
|
| 14 |
-
ββββββββββββββββ ββββββββββββ ββββββββββββ
|
| 15 |
-
β Routers β β Health β β CORS β
|
| 16 |
-
β (merchant) β β Check β βMiddlewareβ
|
| 17 |
-
ββββββββ¬ββββββββ ββββββββββββ ββββββββββββ
|
| 18 |
-
β
|
| 19 |
-
βΌ
|
| 20 |
-
ββββββββββββββββββββββββββββββββββββββββββββ
|
| 21 |
-
β Merchant Router β
|
| 22 |
-
β - POST /merchants β
|
| 23 |
-
β - GET /merchants/{id} β
|
| 24 |
-
β - PUT /merchants/{id} β
|
| 25 |
-
β - DELETE /merchants/{id} β
|
| 26 |
-
β - GET /merchants β
|
| 27 |
-
β - GET /merchants/{id}/children β
|
| 28 |
-
β - GET /merchants/{id}/hierarchy β
|
| 29 |
-
ββββββββββββββββ¬ββββββββββββββββββββββββββββ
|
| 30 |
-
β
|
| 31 |
-
βΌ
|
| 32 |
-
ββββββββββββββββββββββββββββββββββββββββββββ
|
| 33 |
-
β Merchant Service Layer β
|
| 34 |
-
β - create_merchant() β
|
| 35 |
-
β - get_merchant() β
|
| 36 |
-
β - update_merchant() β
|
| 37 |
-
β - delete_merchant() β
|
| 38 |
-
β - list_merchants() β
|
| 39 |
-
β - validate_parent_merchant() β
|
| 40 |
-
β - is_merchant_code_unique() β
|
| 41 |
-
ββββββββββββββββ¬ββββββββββββββββββββββββββββ
|
| 42 |
-
β
|
| 43 |
-
βΌ
|
| 44 |
-
ββββββββββββββββββββββββββββββββββββββββββββ
|
| 45 |
-
β Pydantic Schemas β
|
| 46 |
-
β - MerchantCreate (validation) β
|
| 47 |
-
β - MerchantUpdate (partial) β
|
| 48 |
-
β - MerchantResponse (output) β
|
| 49 |
-
β - ContactModel β
|
| 50 |
-
β - GeoLocationModel β
|
| 51 |
-
β - KYCModel β
|
| 52 |
-
β - SettingsModel β
|
| 53 |
-
ββββββββββββββββ¬ββββββββββββββββββββββββββββ
|
| 54 |
-
β
|
| 55 |
-
βΌ
|
| 56 |
-
ββββββββββββββββββββββββββββββββββββββββββββ
|
| 57 |
-
β Database Models β
|
| 58 |
-
β - MerchantModel (MongoDB document) β
|
| 59 |
-
ββββββββββββββββ¬ββββββββββββββββββββββββββββ
|
| 60 |
-
β
|
| 61 |
-
βΌ
|
| 62 |
-
ββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
-
β MongoDB (Motor/PyMongo) β
|
| 64 |
-
β Collection: scm_merchants β
|
| 65 |
-
ββββββββββββββββββββββββββββββββββββββββββββ
|
| 66 |
-
```
|
| 67 |
-
|
| 68 |
-
## Merchant Hierarchy
|
| 69 |
-
|
| 70 |
-
```
|
| 71 |
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
-
β National CNF β
|
| 73 |
-
β - Root level (no parent) β
|
| 74 |
-
β - KYC: GST, PAN, Bank Account, IFSC β
|
| 75 |
-
β - Controls national distribution β
|
| 76 |
-
ββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
-
β
|
| 78 |
-
β parent_merchant_id
|
| 79 |
-
βΌ
|
| 80 |
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 81 |
-
β CNF β
|
| 82 |
-
β - Regional level οΏ½οΏ½οΏ½
|
| 83 |
-
β - KYC: GST, PAN, Bank Account, IFSC β
|
| 84 |
-
β - Parent: National CNF β
|
| 85 |
-
ββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
|
| 86 |
-
β
|
| 87 |
-
β parent_merchant_id
|
| 88 |
-
βΌ
|
| 89 |
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 90 |
-
β Distributor β
|
| 91 |
-
β - Local distribution β
|
| 92 |
-
β - KYC: GST, PAN, Bank Account, IFSC β
|
| 93 |
-
β - Parent: CNF β
|
| 94 |
-
ββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
|
| 95 |
-
β
|
| 96 |
-
β parent_merchant_id
|
| 97 |
-
βΌ
|
| 98 |
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 99 |
-
β Salon β
|
| 100 |
-
β - End retailer β
|
| 101 |
-
β - KYC: PAN (mandatory), GST (optional) β
|
| 102 |
-
β - Geo-location required β
|
| 103 |
-
β - Parent: Distributor β
|
| 104 |
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 105 |
-
```
|
| 106 |
-
|
| 107 |
-
## Request Flow
|
| 108 |
-
|
| 109 |
-
```
|
| 110 |
-
Client Request
|
| 111 |
-
β
|
| 112 |
-
βΌ
|
| 113 |
-
βββββββββββββββββββ
|
| 114 |
-
β FastAPI Router β βββ Pydantic validation
|
| 115 |
-
ββββββββββ¬βββββββββ
|
| 116 |
-
β
|
| 117 |
-
βΌ
|
| 118 |
-
βββββββββββββββββββββββββββββββββββββββββββ
|
| 119 |
-
β Merchant Service β
|
| 120 |
-
β 1. Validate merchant code uniqueness β
|
| 121 |
-
β 2. Validate parent exists & active β
|
| 122 |
-
β 3. Check parent-child type match β
|
| 123 |
-
β 4. Validate business rules β
|
| 124 |
-
β 5. Generate merchant ID β
|
| 125 |
-
ββββββββββ¬βββββββββββββββββββββββββββββββββ
|
| 126 |
-
β
|
| 127 |
-
βΌ
|
| 128 |
-
βββββββββββββββββββ
|
| 129 |
-
β MongoDB β βββ Insert/Update/Query
|
| 130 |
-
ββββββββββ¬βββββββββ
|
| 131 |
-
β
|
| 132 |
-
βΌ
|
| 133 |
-
βββββββββββββββββββ
|
| 134 |
-
β Response β βββ MerchantResponse schema
|
| 135 |
-
βββββββββββββββββββ
|
| 136 |
-
```
|
| 137 |
-
|
| 138 |
-
## Validation Pipeline
|
| 139 |
-
|
| 140 |
-
```
|
| 141 |
-
Incoming Request Data
|
| 142 |
-
β
|
| 143 |
-
βΌ
|
| 144 |
-
βββββββββββββββββββββββββββββββββββββββββββ
|
| 145 |
-
β 1. Pydantic Schema Validation β
|
| 146 |
-
β - Field types β
|
| 147 |
-
β - Required fields β
|
| 148 |
-
β - String lengths β
|
| 149 |
-
β - Regex patterns β
|
| 150 |
-
ββββββββββ¬βββββββββββββββββββββββββββββββββ
|
| 151 |
-
β
|
| 152 |
-
βΌ
|
| 153 |
-
βββββββββββββββββββββββββββββββββββββββββββ
|
| 154 |
-
β 2. Field-level Validators β
|
| 155 |
-
β - Phone: E.164 format β
|
| 156 |
-
β - Email: lowercase normalization β
|
| 157 |
-
β - Pincode: Indian 6-digit β
|
| 158 |
-
β - GST: 15-char pattern β
|
| 159 |
-
β - PAN: 10-char pattern β
|
| 160 |
-
β - IFSC: 11-char pattern β
|
| 161 |
-
β - URLs: HTTPS only β
|
| 162 |
-
β - Lat/Lng: Range validation β
|
| 163 |
-
ββββββββββ¬βββββββββββββββββββββββββββββββββ
|
| 164 |
-
β
|
| 165 |
-
βΌ
|
| 166 |
-
βββββββββββββββββββββββββββββββββββββββββββ
|
| 167 |
-
β 3. Root Validators (Cross-field) β
|
| 168 |
-
β - Parent requirement by type β
|
| 169 |
-
β - KYC completeness by type β
|
| 170 |
-
β - Geo-location for salons β
|
| 171 |
-
ββββββββββ¬βββββββββββββββββββββββββββββββββ
|
| 172 |
-
β
|
| 173 |
-
βΌ
|
| 174 |
-
βββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
-
β 4. Business Logic Validation β
|
| 176 |
-
β - Parent exists & active β
|
| 177 |
-
β - Parent type matches hierarchy β
|
| 178 |
-
β - Merchant code unique in scope β
|
| 179 |
-
β - Credit limit within max β
|
| 180 |
-
ββββββββββ¬βββββββββββββββββββββββββββββββββ
|
| 181 |
-
β
|
| 182 |
-
βΌ
|
| 183 |
-
Valid Data β Database
|
| 184 |
-
```
|
| 185 |
-
|
| 186 |
-
## Merchant Status Lifecycle
|
| 187 |
-
|
| 188 |
-
```
|
| 189 |
-
βββββββββ
|
| 190 |
-
β DRAFT β βββ Initial creation
|
| 191 |
-
βββββ¬ββββ
|
| 192 |
-
β Submit for approval
|
| 193 |
-
βΌ
|
| 194 |
-
βββββββββββββ
|
| 195 |
-
β SUBMITTED β
|
| 196 |
-
βββββββ¬ββββββ
|
| 197 |
-
β
|
| 198 |
-
ββββββ΄βββββ
|
| 199 |
-
β β
|
| 200 |
-
βΌ βΌ
|
| 201 |
-
ββββββββββββ ββββββββββββ
|
| 202 |
-
β APPROVED β β REJECTED β βββ Denied/Deleted
|
| 203 |
-
ββββββ¬ββββββ ββββββββββββ
|
| 204 |
-
β
|
| 205 |
-
β Activate
|
| 206 |
-
βΌ
|
| 207 |
-
ββββββββββ
|
| 208 |
-
β ACTIVE β ββββ
|
| 209 |
-
ββββββ¬ββββ β Reactivate
|
| 210 |
-
β β
|
| 211 |
-
β Suspend β
|
| 212 |
-
βΌ β
|
| 213 |
-
βββββββββββββ β
|
| 214 |
-
β SUSPENDED βββ
|
| 215 |
-
βββββββββββββ
|
| 216 |
-
```
|
| 217 |
-
|
| 218 |
-
## Data Model Relations
|
| 219 |
-
|
| 220 |
-
```
|
| 221 |
-
MerchantModel
|
| 222 |
-
βββ merchant_id (PK)
|
| 223 |
-
βββ merchant_type (Enum)
|
| 224 |
-
βββ parent_merchant_id (FK β merchant_id)
|
| 225 |
-
βββ merchant_code (Unique within parent)
|
| 226 |
-
βββ merchant_name
|
| 227 |
-
βββ contact (Embedded)
|
| 228 |
-
β βββ phone
|
| 229 |
-
β βββ email
|
| 230 |
-
β βββ address_line1
|
| 231 |
-
β βββ address_line2
|
| 232 |
-
β βββ city
|
| 233 |
-
β βββ state
|
| 234 |
-
β βββ pincode
|
| 235 |
-
β βββ country
|
| 236 |
-
βββ geo_location (Embedded, required for salon)
|
| 237 |
-
β βββ lat
|
| 238 |
-
β βββ lng
|
| 239 |
-
βββ kyc (Embedded)
|
| 240 |
-
β βββ gst_number
|
| 241 |
-
β βββ pan_number
|
| 242 |
-
β βββ business_certificate_url
|
| 243 |
-
β βββ bank_account_number
|
| 244 |
-
β βββ bank_ifsc
|
| 245 |
-
β βββ cancelled_cheque_url
|
| 246 |
-
βββ settings (Embedded)
|
| 247 |
-
β βββ pricing_inherited
|
| 248 |
-
β βββ inventory_inherited
|
| 249 |
-
β βββ auto_allocate_stock
|
| 250 |
-
β βββ allowed_payment_modes (Array)
|
| 251 |
-
β βββ credit_limit
|
| 252 |
-
βββ status (Enum)
|
| 253 |
-
βββ created_by
|
| 254 |
-
βββ created_at
|
| 255 |
-
βββ updated_at
|
| 256 |
-
βββ metadata (Flexible JSON)
|
| 257 |
-
```
|
| 258 |
-
|
| 259 |
-
## API Endpoint Tree
|
| 260 |
-
|
| 261 |
-
```
|
| 262 |
-
/
|
| 263 |
-
βββ /health GET
|
| 264 |
-
βββ /merchants
|
| 265 |
-
βββ / POST (Create)
|
| 266 |
-
βββ / GET (List with filters)
|
| 267 |
-
βββ /{merchant_id} GET (Get one)
|
| 268 |
-
βββ /{merchant_id} PUT (Update)
|
| 269 |
-
βββ /{merchant_id} DELETE (Soft delete)
|
| 270 |
-
βββ /{merchant_id}/children GET (List children)
|
| 271 |
-
βββ /{merchant_id}/hierarchy GET (Get full path)
|
| 272 |
-
```
|
| 273 |
-
|
| 274 |
-
## Module Dependencies
|
| 275 |
-
|
| 276 |
-
```
|
| 277 |
-
main.py
|
| 278 |
-
β
|
| 279 |
-
βββ app.routers.merchant_router
|
| 280 |
-
β β
|
| 281 |
-
β βββ app.services.merchant_service
|
| 282 |
-
β β
|
| 283 |
-
β βββ app.schemas.merchant_schema
|
| 284 |
-
β βββ app.models.merchant_model
|
| 285 |
-
β βββ app.constants.merchant_types
|
| 286 |
-
β βββ app.constants.collections
|
| 287 |
-
β βββ app.nosql (MongoDB)
|
| 288 |
-
β
|
| 289 |
-
βββ app.core.config
|
| 290 |
-
βββ app.core.logging_config
|
| 291 |
-
βββ app.nosql
|
| 292 |
-
βββ MongoDB Connection
|
| 293 |
-
```
|
| 294 |
-
|
| 295 |
-
## File Structure Tree
|
| 296 |
-
|
| 297 |
-
```
|
| 298 |
-
cuatrolabs-scm-ms/
|
| 299 |
-
βββ app/
|
| 300 |
-
β βββ __init__.py
|
| 301 |
-
β βββ cache.py
|
| 302 |
-
β βββ nosql.py
|
| 303 |
-
β βββ constants/
|
| 304 |
-
β β βββ __init__.py β¨
|
| 305 |
-
β β βββ collections.py
|
| 306 |
-
β β βββ merchant_types.py β¨
|
| 307 |
-
β β βββ roles.py
|
| 308 |
-
β β βββ validation.py β¨ NEW
|
| 309 |
-
β βββ core/
|
| 310 |
-
β β βββ config.py
|
| 311 |
-
β β βββ logging_config.py
|
| 312 |
-
β βββ models/
|
| 313 |
-
β β βββ merchant_model.py β¨
|
| 314 |
-
β β βββ employee_model.py
|
| 315 |
-
β β βββ role_model.py
|
| 316 |
-
β β βββ auth_log_model.py
|
| 317 |
-
β βββ schemas/
|
| 318 |
-
β β βββ __init__.py β¨
|
| 319 |
-
β β βββ merchant_schema.py β¨ NEW
|
| 320 |
-
β βββ services/
|
| 321 |
-
β β βββ __init__.py β¨
|
| 322 |
-
β β βββ merchant_service.py β¨ NEW
|
| 323 |
-
β βββ routers/
|
| 324 |
-
β βββ __init__.py β¨
|
| 325 |
-
β βββ merchant_router.py β¨ NEW
|
| 326 |
-
βββ tests/
|
| 327 |
-
β βββ conftest.py
|
| 328 |
-
β βββ test_properties_data_models.py
|
| 329 |
-
β βββ test_merchant_schemas.py β¨ NEW
|
| 330 |
-
βββ examples/
|
| 331 |
-
β βββ quick_start.py β¨ NEW
|
| 332 |
-
βββ main.py β¨ NEW
|
| 333 |
-
βββ requirements.txt
|
| 334 |
-
βββ README.md
|
| 335 |
-
βββ MERCHANT_MODULE.md β¨ NEW
|
| 336 |
-
βββ ENHANCEMENT_SUMMARY.md β¨ NEW
|
| 337 |
-
|
| 338 |
-
β¨ = Enhanced/Created
|
| 339 |
-
```
|
| 340 |
-
|
| 341 |
-
## Technology Stack
|
| 342 |
-
|
| 343 |
-
```
|
| 344 |
-
βββββββββββββββββββββββββββββββββββββββ
|
| 345 |
-
β Application Layer β
|
| 346 |
-
β - FastAPI (Web Framework) β
|
| 347 |
-
β - Pydantic (Validation) β
|
| 348 |
-
β - Python 3.9+ β
|
| 349 |
-
βββββββββββββββ¬ββββββββββββββββββββββββ
|
| 350 |
-
β
|
| 351 |
-
βΌ
|
| 352 |
-
βββββββββββββββββββββββββββββββββββββββ
|
| 353 |
-
β Database Layer β
|
| 354 |
-
β - MongoDB (NoSQL) β
|
| 355 |
-
β - Motor (Async Driver) β
|
| 356 |
-
β - PyMongo β
|
| 357 |
-
βββββββββββββββ¬ββββββββββββββββββββββββ
|
| 358 |
-
β
|
| 359 |
-
βΌ
|
| 360 |
-
βββββββββββββββββββββββββββββββββββββββ
|
| 361 |
-
β Supporting Services β
|
| 362 |
-
β - Redis (Cache) - existing β
|
| 363 |
-
β - insightfy-utils (Logging) β
|
| 364 |
-
β - Uvicorn (ASGI Server) β
|
| 365 |
-
βββββββββββββββββββββββββββββββββββββββ
|
| 366 |
-
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,98 +1,263 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
-
short_description:
|
| 9 |
---
|
| 10 |
|
| 11 |
-
|
| 12 |
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
-
|
| 22 |
-
-
|
| 23 |
-
-
|
| 24 |
-
-
|
|
|
|
| 25 |
|
| 26 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
- **MPMS**: Product and merchant data
|
| 30 |
-
- **RMS**: Resource and employee data
|
| 31 |
-
- **TMS**: Transaction and sales data
|
| 32 |
-
- **CRM**: Customer relationship data
|
| 33 |
|
| 34 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
## API Endpoints
|
| 41 |
|
| 42 |
-
### Health
|
| 43 |
- `GET /health` - Service health status
|
| 44 |
-
- `GET /ready` - Readiness check
|
| 45 |
-
- `GET /live` - Liveness check
|
| 46 |
|
| 47 |
-
###
|
| 48 |
-
- `
|
| 49 |
-
- `GET /api/v1/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
Copy `.env.example` to `.env` and configure:
|
| 54 |
|
| 55 |
```bash
|
| 56 |
-
#
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
#
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
#
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
```
|
| 76 |
|
| 77 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
```bash
|
| 80 |
-
# Install dependencies
|
| 81 |
pip install -r requirements.txt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
|
|
|
| 85 |
```
|
| 86 |
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
|
| 91 |
-
|
| 92 |
-
- `app/services/` - Business logic
|
| 93 |
-
- `app/repositories/` - Data access layer
|
| 94 |
-
- `app/models/` - Database models
|
| 95 |
-
- `app/schemas/` - Pydantic schemas
|
| 96 |
-
- `app/clients/` - Inter-service communication
|
| 97 |
-
- `app/dependencies/` - FastAPI dependencies (auth, etc.)
|
| 98 |
-
- `app/utils/` - Utility functions
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Cuatro Labs SCM
|
| 3 |
+
emoji: π
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
+
short_description: Supply Chain Management - Merchant & Employee Management
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Supply Chain Management (SCM) Microservice
|
| 12 |
|
| 13 |
+
A comprehensive FastAPI-based microservice for managing merchants, employees, and sales operations within the Insightfy Bloom platform. This service provides robust APIs for organizational hierarchy management, employee tracking, and sales order processing.
|
| 14 |
|
| 15 |
+
## Features
|
| 16 |
|
| 17 |
+
### Merchant Management
|
| 18 |
+
- Create, read, update, and delete merchant records
|
| 19 |
+
- Support for multiple merchant types (Distributor, Retailer, Wholesaler, Manufacturer)
|
| 20 |
+
- Hierarchical merchant relationships (parent-child structure)
|
| 21 |
+
- Query merchants by hierarchy and relationships
|
| 22 |
+
- Flexible filtering and pagination
|
| 23 |
|
| 24 |
+
### Employee Management
|
| 25 |
+
- Complete employee lifecycle management (CRUD operations)
|
| 26 |
+
- Employee types: Sales Representative, Manager, Admin, Warehouse Staff, Delivery Personnel
|
| 27 |
+
- Organizational hierarchy with reporting structures
|
| 28 |
+
- Employee status management (Active, Inactive, On Leave, Terminated)
|
| 29 |
+
- Location consent tracking
|
| 30 |
+
- Employee code-based lookups
|
| 31 |
+
- Management chain and direct reports queries
|
| 32 |
|
| 33 |
+
### Sales Order Management
|
| 34 |
+
- Create and manage sales orders
|
| 35 |
+
- Order status tracking (Draft, Confirmed, Processing, Shipped, Delivered, Cancelled)
|
| 36 |
+
- Invoice generation
|
| 37 |
+
- Sales analytics and widgets
|
| 38 |
+
- Advanced filtering and search capabilities
|
| 39 |
|
| 40 |
+
### Authentication & Security
|
| 41 |
+
- JWT-based authentication
|
| 42 |
+
- OTP verification via SMS (Twilio) and Email (SMTP)
|
| 43 |
+
- Role-based access control
|
| 44 |
+
- Secure password hashing with bcrypt
|
| 45 |
|
| 46 |
+
## Architecture
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
### Technology Stack
|
| 49 |
+
- **Framework**: FastAPI 0.104.1
|
| 50 |
+
- **Database**: MongoDB (via Motor async driver)
|
| 51 |
+
- **Cache**: Redis
|
| 52 |
+
- **Authentication**: JWT (python-jose)
|
| 53 |
+
- **Notifications**: Twilio (SMS), SMTP (Email)
|
| 54 |
+
- **Server**: Uvicorn with async support
|
| 55 |
|
| 56 |
+
### Project Structure
|
| 57 |
+
```
|
| 58 |
+
app/
|
| 59 |
+
βββ routers/ # API route handlers
|
| 60 |
+
β βββ employee_router.py
|
| 61 |
+
β βββ merchant_router.py
|
| 62 |
+
β βββ sales_order_router.py
|
| 63 |
+
βββ services/ # Business logic layer
|
| 64 |
+
βββ models/ # Database models
|
| 65 |
+
βββ schemas/ # Pydantic validation schemas
|
| 66 |
+
βββ constants/ # Application constants
|
| 67 |
+
β βββ collections.py
|
| 68 |
+
β βββ employee_types.py
|
| 69 |
+
β βββ merchant_types.py
|
| 70 |
+
β βββ roles.py
|
| 71 |
+
β βββ validation.py
|
| 72 |
+
βββ core/ # Core configuration
|
| 73 |
+
β βββ config.py
|
| 74 |
+
β βββ logging_config.py
|
| 75 |
+
βββ utils/ # Utility functions
|
| 76 |
+
βββ dependencies/ # FastAPI dependencies
|
| 77 |
+
βββ main.py # Application entry point
|
| 78 |
+
βββ nosql.py # MongoDB connection
|
| 79 |
+
βββ cache.py # Redis cache management
|
| 80 |
+
```
|
| 81 |
|
| 82 |
## API Endpoints
|
| 83 |
|
| 84 |
+
### Health Check
|
| 85 |
- `GET /health` - Service health status
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
### Merchant Endpoints (`/api/v1/merchants`)
|
| 88 |
+
- `POST /api/v1/merchants` - Create new merchant
|
| 89 |
+
- `GET /api/v1/merchants/{merchant_id}` - Get merchant by ID
|
| 90 |
+
- `PUT /api/v1/merchants/{merchant_id}` - Update merchant
|
| 91 |
+
- `DELETE /api/v1/merchants/{merchant_id}` - Delete merchant
|
| 92 |
+
- `GET /api/v1/merchants` - List merchants with filters
|
| 93 |
+
- `GET /api/v1/merchants/{merchant_id}/children` - Get child merchants
|
| 94 |
+
- `GET /api/v1/merchants/{merchant_id}/hierarchy` - Get merchant hierarchy
|
| 95 |
+
|
| 96 |
+
### Employee Endpoints (`/api/v1/employees`)
|
| 97 |
+
- `POST /api/v1/employees` - Create new employee
|
| 98 |
+
- `GET /api/v1/employees/{user_id}` - Get employee by ID
|
| 99 |
+
- `GET /api/v1/employees/code/{employee_code}` - Get employee by code
|
| 100 |
+
- `PUT /api/v1/employees/{user_id}` - Update employee
|
| 101 |
+
- `DELETE /api/v1/employees/{user_id}` - Delete employee
|
| 102 |
+
- `GET /api/v1/employees` - List employees with filters
|
| 103 |
+
- `GET /api/v1/employees/{user_id}/reports` - Get direct reports
|
| 104 |
+
- `GET /api/v1/employees/{user_id}/hierarchy` - Get management chain
|
| 105 |
+
- `PATCH /api/v1/employees/{user_id}/status` - Update employee status
|
| 106 |
+
- `PATCH /api/v1/employees/{user_id}/location-consent` - Update location consent
|
| 107 |
|
| 108 |
+
### Sales Order Endpoints (`/api/v1/sales`)
|
| 109 |
+
- `POST /api/v1/sales/order` - Create sales order
|
| 110 |
+
- `GET /api/v1/sales/order/{sales_order_id}` - Get sales order
|
| 111 |
+
- `PUT /api/v1/sales/order/{sales_order_id}` - Update sales order
|
| 112 |
+
- `POST /api/v1/sales/order/list` - List sales orders with filters
|
| 113 |
+
- `POST /api/v1/sales/order/{sales_order_id}/invoice` - Generate invoice
|
| 114 |
+
- `GET /api/v1/sales/info/widgets` - Get sales analytics widgets
|
| 115 |
+
|
| 116 |
+
## Environment Configuration
|
| 117 |
|
| 118 |
Copy `.env.example` to `.env` and configure:
|
| 119 |
|
| 120 |
```bash
|
| 121 |
+
# Application
|
| 122 |
+
APP_NAME=SCM Microservice
|
| 123 |
+
APP_VERSION=1.0.0
|
| 124 |
+
DEBUG=false
|
| 125 |
+
|
| 126 |
+
# MongoDB
|
| 127 |
+
MONGODB_URI=mongodb://localhost:27017
|
| 128 |
+
MONGODB_DB_NAME=scm_db
|
| 129 |
+
|
| 130 |
+
# Redis
|
| 131 |
+
REDIS_HOST=localhost
|
| 132 |
+
REDIS_PORT=6379
|
| 133 |
+
REDIS_PASSWORD=
|
| 134 |
+
REDIS_DB=0
|
| 135 |
+
|
| 136 |
+
# JWT Authentication
|
| 137 |
+
SECRET_KEY=your-secret-key-change-in-production
|
| 138 |
+
ALGORITHM=HS256
|
| 139 |
+
TOKEN_EXPIRATION_HOURS=8
|
| 140 |
+
|
| 141 |
+
# OTP Configuration
|
| 142 |
+
OTP_TTL_SECONDS=600
|
| 143 |
+
OTP_RATE_LIMIT_MAX=10
|
| 144 |
+
OTP_RATE_LIMIT_WINDOW=600
|
| 145 |
|
| 146 |
+
# Twilio (SMS)
|
| 147 |
+
TWILIO_ACCOUNT_SID=your_twilio_account_sid
|
| 148 |
+
TWILIO_AUTH_TOKEN=your_twilio_auth_token
|
| 149 |
+
TWILIO_PHONE_NUMBER=+1234567890
|
| 150 |
+
|
| 151 |
+
# SMTP (Email)
|
| 152 |
+
SMTP_HOST=smtp.gmail.com
|
| 153 |
+
SMTP_PORT=587
|
| 154 |
+
SMTP_USERNAME=your_email@gmail.com
|
| 155 |
+
SMTP_PASSWORD=your_app_password
|
| 156 |
+
SMTP_FROM_EMAIL=noreply@scm.com
|
| 157 |
+
SMTP_USE_TLS=true
|
| 158 |
+
|
| 159 |
+
# Logging
|
| 160 |
+
LOG_LEVEL=INFO
|
| 161 |
```
|
| 162 |
|
| 163 |
+
## Getting Started
|
| 164 |
+
|
| 165 |
+
### Prerequisites
|
| 166 |
+
- Python 3.11+
|
| 167 |
+
- MongoDB
|
| 168 |
+
- Redis
|
| 169 |
+
- Twilio account (for SMS)
|
| 170 |
+
- SMTP server access (for email)
|
| 171 |
+
|
| 172 |
+
### Local Development
|
| 173 |
+
|
| 174 |
+
1. Clone the repository and navigate to the project directory
|
| 175 |
|
| 176 |
+
2. Create and activate a virtual environment:
|
| 177 |
+
```bash
|
| 178 |
+
python -m venv venv
|
| 179 |
+
source venv/bin/activate # On Windows: venv\Scripts\activate
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
3. Install dependencies:
|
| 183 |
```bash
|
|
|
|
| 184 |
pip install -r requirements.txt
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
4. Configure environment variables:
|
| 188 |
+
```bash
|
| 189 |
+
cp .env.example .env
|
| 190 |
+
# Edit .env with your configuration
|
| 191 |
+
```
|
| 192 |
|
| 193 |
+
5. Run the service:
|
| 194 |
+
```bash
|
| 195 |
+
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
|
| 196 |
```
|
| 197 |
|
| 198 |
+
6. Access the API documentation:
|
| 199 |
+
- Swagger UI: http://localhost:8000/docs
|
| 200 |
+
- ReDoc: http://localhost:8000/redoc
|
| 201 |
+
|
| 202 |
+
### Docker Deployment
|
| 203 |
+
|
| 204 |
+
Build and run with Docker:
|
| 205 |
+
|
| 206 |
+
```bash
|
| 207 |
+
# Build the image
|
| 208 |
+
docker build -t scm-microservice .
|
| 209 |
+
|
| 210 |
+
# Run the container
|
| 211 |
+
docker run -p 7860:7860 --env-file .env scm-microservice
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
The service will be available at http://localhost:7860
|
| 215 |
+
|
| 216 |
+
## Testing
|
| 217 |
+
|
| 218 |
+
Run the test suite:
|
| 219 |
+
|
| 220 |
+
```bash
|
| 221 |
+
# Run all tests
|
| 222 |
+
pytest
|
| 223 |
+
|
| 224 |
+
# Run with coverage
|
| 225 |
+
pytest --cov=app tests/
|
| 226 |
+
|
| 227 |
+
# Run specific test file
|
| 228 |
+
pytest tests/test_employee_schemas.py
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
Test files include:
|
| 232 |
+
- `tests/test_employee_schemas.py` - Employee schema validation tests
|
| 233 |
+
- `tests/test_merchant_schemas.py` - Merchant schema validation tests
|
| 234 |
+
- `tests/test_properties_data_models.py` - Property-based testing with Hypothesis
|
| 235 |
+
|
| 236 |
+
## Examples
|
| 237 |
+
|
| 238 |
+
Check the `examples/` directory for usage examples:
|
| 239 |
+
- `quick_start.py` - Basic API usage
|
| 240 |
+
- `sales_order_example.py` - Sales order workflow
|
| 241 |
+
|
| 242 |
+
## API Documentation
|
| 243 |
+
|
| 244 |
+
Once the service is running, interactive API documentation is available at:
|
| 245 |
+
- **Swagger UI**: `/docs`
|
| 246 |
+
- **ReDoc**: `/redoc`
|
| 247 |
+
|
| 248 |
+
## Contributing
|
| 249 |
+
|
| 250 |
+
This service follows standard FastAPI best practices:
|
| 251 |
+
- Async/await for all I/O operations
|
| 252 |
+
- Pydantic models for request/response validation
|
| 253 |
+
- Dependency injection for shared resources
|
| 254 |
+
- Structured logging with python-json-logger
|
| 255 |
+
- Property-based testing with Hypothesis
|
| 256 |
+
|
| 257 |
+
## License
|
| 258 |
+
|
| 259 |
+
Part of the Insightfy Bloom platform by Cuatro Labs.
|
| 260 |
|
| 261 |
+
## Support
|
| 262 |
|
| 263 |
+
For issues and questions, please refer to the project documentation or contact the development team.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/nosql.py
CHANGED
|
@@ -2,50 +2,81 @@
|
|
| 2 |
MongoDB connection and database instance.
|
| 3 |
Provides a singleton database connection for the application.
|
| 4 |
"""
|
| 5 |
-
from motor.motor_asyncio import AsyncIOMotorClient
|
| 6 |
from insightfy_utils.logging import get_logger
|
| 7 |
from app.core.config import settings
|
| 8 |
|
| 9 |
logger = get_logger(__name__)
|
| 10 |
|
| 11 |
-
# MongoDB client and database instances
|
| 12 |
-
client: AsyncIOMotorClient = None
|
| 13 |
-
db = None
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
"""
|
| 21 |
-
global client, db
|
| 22 |
-
try:
|
| 23 |
-
logger.info("Connecting to MongoDB", extra={
|
| 24 |
-
"uri": settings.MONGODB_URI,
|
| 25 |
-
"database": settings.MONGODB_DB_NAME
|
| 26 |
-
})
|
| 27 |
-
|
| 28 |
-
client = AsyncIOMotorClient(settings.MONGODB_URI)
|
| 29 |
-
db = client[settings.MONGODB_DB_NAME]
|
| 30 |
-
|
| 31 |
-
# Test the connection
|
| 32 |
-
await client.admin.command('ping')
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
async def close_mongo_connection():
|
| 43 |
-
"""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
client.close()
|
| 51 |
-
logger.info("MongoDB connection closed")
|
|
|
|
| 2 |
MongoDB connection and database instance.
|
| 3 |
Provides a singleton database connection for the application.
|
| 4 |
"""
|
| 5 |
+
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
|
| 6 |
from insightfy_utils.logging import get_logger
|
| 7 |
from app.core.config import settings
|
| 8 |
|
| 9 |
logger = get_logger(__name__)
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
class DatabaseConnection:
|
| 13 |
+
"""Singleton class to manage MongoDB connection"""
|
| 14 |
+
_client: AsyncIOMotorClient = None
|
| 15 |
+
_db: AsyncIOMotorDatabase = None
|
| 16 |
|
| 17 |
+
@classmethod
|
| 18 |
+
def get_database(cls) -> AsyncIOMotorDatabase:
|
| 19 |
+
"""
|
| 20 |
+
Get the database instance.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
Returns:
|
| 23 |
+
MongoDB database instance
|
| 24 |
+
|
| 25 |
+
Raises:
|
| 26 |
+
RuntimeError if database is not connected
|
| 27 |
+
"""
|
| 28 |
+
if cls._db is None:
|
| 29 |
+
raise RuntimeError("Database not connected. Call connect_to_mongo() first.")
|
| 30 |
+
return cls._db
|
| 31 |
+
|
| 32 |
+
@classmethod
|
| 33 |
+
async def connect(cls):
|
| 34 |
+
"""
|
| 35 |
+
Establish connection to MongoDB.
|
| 36 |
+
Called during application startup.
|
| 37 |
+
"""
|
| 38 |
+
try:
|
| 39 |
+
logger.info("Connecting to MongoDB", extra={
|
| 40 |
+
"uri": settings.MONGODB_URI,
|
| 41 |
+
"database": settings.MONGODB_DB_NAME
|
| 42 |
+
})
|
| 43 |
+
|
| 44 |
+
cls._client = AsyncIOMotorClient(settings.MONGODB_URI)
|
| 45 |
+
cls._db = cls._client[settings.MONGODB_DB_NAME]
|
| 46 |
+
|
| 47 |
+
# Test the connection
|
| 48 |
+
await cls._client.admin.command('ping')
|
| 49 |
+
|
| 50 |
+
logger.info("Successfully connected to MongoDB", extra={
|
| 51 |
+
"database": settings.MONGODB_DB_NAME
|
| 52 |
+
})
|
| 53 |
+
except Exception as e:
|
| 54 |
+
logger.error("Failed to connect to MongoDB", exc_info=e)
|
| 55 |
+
raise
|
| 56 |
+
|
| 57 |
+
@classmethod
|
| 58 |
+
async def close(cls):
|
| 59 |
+
"""
|
| 60 |
+
Close MongoDB connection.
|
| 61 |
+
Called during application shutdown.
|
| 62 |
+
"""
|
| 63 |
+
if cls._client:
|
| 64 |
+
logger.info("Closing MongoDB connection")
|
| 65 |
+
cls._client.close()
|
| 66 |
+
logger.info("MongoDB connection closed")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Public API
|
| 70 |
+
async def connect_to_mongo():
|
| 71 |
+
"""Establish connection to MongoDB"""
|
| 72 |
+
await DatabaseConnection.connect()
|
| 73 |
|
| 74 |
|
| 75 |
async def close_mongo_connection():
|
| 76 |
+
"""Close MongoDB connection"""
|
| 77 |
+
await DatabaseConnection.close()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_database() -> AsyncIOMotorDatabase:
|
| 81 |
+
"""Get the database instance"""
|
| 82 |
+
return DatabaseConnection.get_database()
|
|
|
|
|
|
app/schemas/merchant_schema.py
CHANGED
|
@@ -39,8 +39,9 @@ class ContactModel(BaseModel):
|
|
| 39 |
return v.lower().strip() if v else v
|
| 40 |
|
| 41 |
@field_validator("pincode")
|
| 42 |
-
def pincode_for_india(cls, v: str,
|
| 43 |
-
|
|
|
|
| 44 |
if country in ("india", "in"):
|
| 45 |
if not PINCODE_INDIA_REGEX.match(v):
|
| 46 |
raise ValueError("pincode must be a valid 6-digit Indian pincode")
|
|
|
|
| 39 |
return v.lower().strip() if v else v
|
| 40 |
|
| 41 |
@field_validator("pincode")
|
| 42 |
+
def pincode_for_india(cls, v: str, info):
|
| 43 |
+
# In Pydantic v2, we need to access data from info.data
|
| 44 |
+
country = (info.data.get("country") or "").lower() if info.data else ""
|
| 45 |
if country in ("india", "in"):
|
| 46 |
if not PINCODE_INDIA_REGEX.match(v):
|
| 47 |
raise ValueError("pincode must be a valid 6-digit Indian pincode")
|
app/services/employee_service.py
CHANGED
|
@@ -7,7 +7,7 @@ from fastapi import HTTPException, status
|
|
| 7 |
from insightfy_utils.logging import get_logger
|
| 8 |
import secrets
|
| 9 |
|
| 10 |
-
from app.nosql import
|
| 11 |
from app.constants.collections import SCM_EMPLOYEES_COLLECTION
|
| 12 |
from app.constants.employee_types import (
|
| 13 |
Designation,
|
|
@@ -45,7 +45,7 @@ class EmployeeService:
|
|
| 45 |
Employee document or None if not found
|
| 46 |
"""
|
| 47 |
try:
|
| 48 |
-
employee = await
|
| 49 |
return employee
|
| 50 |
except Exception as e:
|
| 51 |
logger.error(f"Error fetching employee {user_id}", exc_info=e)
|
|
@@ -66,7 +66,7 @@ class EmployeeService:
|
|
| 66 |
True if unique, False otherwise
|
| 67 |
"""
|
| 68 |
try:
|
| 69 |
-
existing = await
|
| 70 |
{"employee_code": code.upper()}
|
| 71 |
)
|
| 72 |
return existing is None
|
|
@@ -102,7 +102,7 @@ class EmployeeService:
|
|
| 102 |
if exclude_user_id:
|
| 103 |
query["user_id"] = {"$ne": exclude_user_id}
|
| 104 |
|
| 105 |
-
existing = await
|
| 106 |
return existing is None
|
| 107 |
except Exception as e:
|
| 108 |
logger.error(f"Error checking email uniqueness", exc_info=e)
|
|
@@ -136,7 +136,7 @@ class EmployeeService:
|
|
| 136 |
if exclude_user_id:
|
| 137 |
query["user_id"] = {"$ne": exclude_user_id}
|
| 138 |
|
| 139 |
-
existing = await
|
| 140 |
return existing is None
|
| 141 |
except Exception as e:
|
| 142 |
logger.error(f"Error checking phone uniqueness", exc_info=e)
|
|
@@ -279,7 +279,7 @@ class EmployeeService:
|
|
| 279 |
if "id_docs" in employee_dict and employee_dict["id_docs"]:
|
| 280 |
employee_dict["id_docs"] = [dict(doc) for doc in employee_dict["id_docs"]]
|
| 281 |
|
| 282 |
-
await
|
| 283 |
|
| 284 |
logger.info(
|
| 285 |
f"Created employee {user_id}",
|
|
@@ -391,7 +391,7 @@ class EmployeeService:
|
|
| 391 |
update_data["id_docs"] = [dict(doc) for doc in update_data["id_docs"]]
|
| 392 |
|
| 393 |
# Update in database
|
| 394 |
-
result = await
|
| 395 |
{"user_id": user_id},
|
| 396 |
{"$set": update_data}
|
| 397 |
)
|
|
@@ -457,7 +457,7 @@ class EmployeeService:
|
|
| 457 |
HTTPException if not found
|
| 458 |
"""
|
| 459 |
try:
|
| 460 |
-
employee = await
|
| 461 |
{"employee_code": employee_code.upper()}
|
| 462 |
)
|
| 463 |
if not employee:
|
|
@@ -511,7 +511,7 @@ class EmployeeService:
|
|
| 511 |
query["region"] = region
|
| 512 |
|
| 513 |
# Fetch employees
|
| 514 |
-
cursor =
|
| 515 |
employees = await cursor.to_list(length=limit)
|
| 516 |
|
| 517 |
return [EmployeeResponse(**emp) for emp in employees]
|
|
@@ -547,7 +547,7 @@ class EmployeeService:
|
|
| 547 |
)
|
| 548 |
|
| 549 |
# Check for active direct reports
|
| 550 |
-
active_reports = await
|
| 551 |
"manager_id": user_id,
|
| 552 |
"status": {"$in": [
|
| 553 |
EmployeeStatus.ACTIVE.value,
|
|
@@ -564,7 +564,7 @@ class EmployeeService:
|
|
| 564 |
|
| 565 |
try:
|
| 566 |
# Soft delete - set status to terminated
|
| 567 |
-
await
|
| 568 |
{"user_id": user_id},
|
| 569 |
{
|
| 570 |
"$set": {
|
|
|
|
| 7 |
from insightfy_utils.logging import get_logger
|
| 8 |
import secrets
|
| 9 |
|
| 10 |
+
from app.nosql import get_database
|
| 11 |
from app.constants.collections import SCM_EMPLOYEES_COLLECTION
|
| 12 |
from app.constants.employee_types import (
|
| 13 |
Designation,
|
|
|
|
| 45 |
Employee document or None if not found
|
| 46 |
"""
|
| 47 |
try:
|
| 48 |
+
employee = await get_database()[SCM_EMPLOYEES_COLLECTION].find_one({"user_id": user_id})
|
| 49 |
return employee
|
| 50 |
except Exception as e:
|
| 51 |
logger.error(f"Error fetching employee {user_id}", exc_info=e)
|
|
|
|
| 66 |
True if unique, False otherwise
|
| 67 |
"""
|
| 68 |
try:
|
| 69 |
+
existing = await get_database()[SCM_EMPLOYEES_COLLECTION].find_one(
|
| 70 |
{"employee_code": code.upper()}
|
| 71 |
)
|
| 72 |
return existing is None
|
|
|
|
| 102 |
if exclude_user_id:
|
| 103 |
query["user_id"] = {"$ne": exclude_user_id}
|
| 104 |
|
| 105 |
+
existing = await get_database()[SCM_EMPLOYEES_COLLECTION].find_one(query)
|
| 106 |
return existing is None
|
| 107 |
except Exception as e:
|
| 108 |
logger.error(f"Error checking email uniqueness", exc_info=e)
|
|
|
|
| 136 |
if exclude_user_id:
|
| 137 |
query["user_id"] = {"$ne": exclude_user_id}
|
| 138 |
|
| 139 |
+
existing = await get_database()[SCM_EMPLOYEES_COLLECTION].find_one(query)
|
| 140 |
return existing is None
|
| 141 |
except Exception as e:
|
| 142 |
logger.error(f"Error checking phone uniqueness", exc_info=e)
|
|
|
|
| 279 |
if "id_docs" in employee_dict and employee_dict["id_docs"]:
|
| 280 |
employee_dict["id_docs"] = [dict(doc) for doc in employee_dict["id_docs"]]
|
| 281 |
|
| 282 |
+
await get_database()[SCM_EMPLOYEES_COLLECTION].insert_one(employee_dict)
|
| 283 |
|
| 284 |
logger.info(
|
| 285 |
f"Created employee {user_id}",
|
|
|
|
| 391 |
update_data["id_docs"] = [dict(doc) for doc in update_data["id_docs"]]
|
| 392 |
|
| 393 |
# Update in database
|
| 394 |
+
result = await get_database()[SCM_EMPLOYEES_COLLECTION].update_one(
|
| 395 |
{"user_id": user_id},
|
| 396 |
{"$set": update_data}
|
| 397 |
)
|
|
|
|
| 457 |
HTTPException if not found
|
| 458 |
"""
|
| 459 |
try:
|
| 460 |
+
employee = await get_database()[SCM_EMPLOYEES_COLLECTION].find_one(
|
| 461 |
{"employee_code": employee_code.upper()}
|
| 462 |
)
|
| 463 |
if not employee:
|
|
|
|
| 511 |
query["region"] = region
|
| 512 |
|
| 513 |
# Fetch employees
|
| 514 |
+
cursor = get_database()[SCM_EMPLOYEES_COLLECTION].find(query).skip(skip).limit(limit)
|
| 515 |
employees = await cursor.to_list(length=limit)
|
| 516 |
|
| 517 |
return [EmployeeResponse(**emp) for emp in employees]
|
|
|
|
| 547 |
)
|
| 548 |
|
| 549 |
# Check for active direct reports
|
| 550 |
+
active_reports = await get_database()[SCM_EMPLOYEES_COLLECTION].find_one({
|
| 551 |
"manager_id": user_id,
|
| 552 |
"status": {"$in": [
|
| 553 |
EmployeeStatus.ACTIVE.value,
|
|
|
|
| 564 |
|
| 565 |
try:
|
| 566 |
# Soft delete - set status to terminated
|
| 567 |
+
await get_database()[SCM_EMPLOYEES_COLLECTION].update_one(
|
| 568 |
{"user_id": user_id},
|
| 569 |
{
|
| 570 |
"$set": {
|
app/services/merchant_service.py
CHANGED
|
@@ -7,7 +7,7 @@ from fastapi import HTTPException, status
|
|
| 7 |
from insightfy_utils.logging import get_logger
|
| 8 |
import secrets
|
| 9 |
|
| 10 |
-
from app.nosql import
|
| 11 |
from app.constants.collections import SCM_MERCHANTS_COLLECTION
|
| 12 |
from app.constants.merchant_types import MerchantType, MerchantStatus
|
| 13 |
from app.models.merchant_model import MerchantModel
|
|
@@ -42,7 +42,7 @@ class MerchantService:
|
|
| 42 |
Merchant document or None if not found
|
| 43 |
"""
|
| 44 |
try:
|
| 45 |
-
merchant = await
|
| 46 |
return merchant
|
| 47 |
except Exception as e:
|
| 48 |
logger.error(f"Error fetching merchant {merchant_id}", exc_info=e)
|
|
@@ -68,7 +68,7 @@ class MerchantService:
|
|
| 68 |
if parent_id:
|
| 69 |
query["parent_merchant_id"] = parent_id
|
| 70 |
|
| 71 |
-
existing = await
|
| 72 |
return existing is None
|
| 73 |
except Exception as e:
|
| 74 |
logger.error(f"Error checking merchant code uniqueness", exc_info=e)
|
|
@@ -187,7 +187,7 @@ class MerchantService:
|
|
| 187 |
merchant_dict["created_at"] = merchant_dict["created_at"].isoformat()
|
| 188 |
merchant_dict["updated_at"] = merchant_dict["updated_at"].isoformat()
|
| 189 |
|
| 190 |
-
await
|
| 191 |
|
| 192 |
logger.info(
|
| 193 |
f"Created merchant {merchant_id}",
|
|
@@ -257,7 +257,7 @@ class MerchantService:
|
|
| 257 |
|
| 258 |
try:
|
| 259 |
# Update in database
|
| 260 |
-
result = await
|
| 261 |
{"merchant_id": merchant_id},
|
| 262 |
{"$set": update_data}
|
| 263 |
)
|
|
@@ -336,7 +336,7 @@ class MerchantService:
|
|
| 336 |
query["status"] = status_filter.value
|
| 337 |
|
| 338 |
# Fetch merchants
|
| 339 |
-
cursor =
|
| 340 |
merchants = await cursor.to_list(length=limit)
|
| 341 |
|
| 342 |
return [MerchantResponse(**m) for m in merchants]
|
|
@@ -371,7 +371,7 @@ class MerchantService:
|
|
| 371 |
)
|
| 372 |
|
| 373 |
# Check for active children
|
| 374 |
-
children = await
|
| 375 |
"parent_merchant_id": merchant_id,
|
| 376 |
"status": {"$in": [MerchantStatus.ACTIVE.value, MerchantStatus.APPROVED.value]}
|
| 377 |
})
|
|
@@ -384,7 +384,7 @@ class MerchantService:
|
|
| 384 |
|
| 385 |
try:
|
| 386 |
# Soft delete - set status to rejected
|
| 387 |
-
await
|
| 388 |
{"merchant_id": merchant_id},
|
| 389 |
{
|
| 390 |
"$set": {
|
|
|
|
| 7 |
from insightfy_utils.logging import get_logger
|
| 8 |
import secrets
|
| 9 |
|
| 10 |
+
from app.nosql import get_database
|
| 11 |
from app.constants.collections import SCM_MERCHANTS_COLLECTION
|
| 12 |
from app.constants.merchant_types import MerchantType, MerchantStatus
|
| 13 |
from app.models.merchant_model import MerchantModel
|
|
|
|
| 42 |
Merchant document or None if not found
|
| 43 |
"""
|
| 44 |
try:
|
| 45 |
+
merchant = await get_database()[SCM_MERCHANTS_COLLECTION].find_one({"merchant_id": merchant_id})
|
| 46 |
return merchant
|
| 47 |
except Exception as e:
|
| 48 |
logger.error(f"Error fetching merchant {merchant_id}", exc_info=e)
|
|
|
|
| 68 |
if parent_id:
|
| 69 |
query["parent_merchant_id"] = parent_id
|
| 70 |
|
| 71 |
+
existing = await get_database()[SCM_MERCHANTS_COLLECTION].find_one(query)
|
| 72 |
return existing is None
|
| 73 |
except Exception as e:
|
| 74 |
logger.error(f"Error checking merchant code uniqueness", exc_info=e)
|
|
|
|
| 187 |
merchant_dict["created_at"] = merchant_dict["created_at"].isoformat()
|
| 188 |
merchant_dict["updated_at"] = merchant_dict["updated_at"].isoformat()
|
| 189 |
|
| 190 |
+
await get_database()[SCM_MERCHANTS_COLLECTION].insert_one(merchant_dict)
|
| 191 |
|
| 192 |
logger.info(
|
| 193 |
f"Created merchant {merchant_id}",
|
|
|
|
| 257 |
|
| 258 |
try:
|
| 259 |
# Update in database
|
| 260 |
+
result = await get_database()[SCM_MERCHANTS_COLLECTION].update_one(
|
| 261 |
{"merchant_id": merchant_id},
|
| 262 |
{"$set": update_data}
|
| 263 |
)
|
|
|
|
| 336 |
query["status"] = status_filter.value
|
| 337 |
|
| 338 |
# Fetch merchants
|
| 339 |
+
cursor = get_database()[SCM_MERCHANTS_COLLECTION].find(query).skip(skip).limit(limit)
|
| 340 |
merchants = await cursor.to_list(length=limit)
|
| 341 |
|
| 342 |
return [MerchantResponse(**m) for m in merchants]
|
|
|
|
| 371 |
)
|
| 372 |
|
| 373 |
# Check for active children
|
| 374 |
+
children = await get_database()[SCM_MERCHANTS_COLLECTION].find_one({
|
| 375 |
"parent_merchant_id": merchant_id,
|
| 376 |
"status": {"$in": [MerchantStatus.ACTIVE.value, MerchantStatus.APPROVED.value]}
|
| 377 |
})
|
|
|
|
| 384 |
|
| 385 |
try:
|
| 386 |
# Soft delete - set status to rejected
|
| 387 |
+
await get_database()[SCM_MERCHANTS_COLLECTION].update_one(
|
| 388 |
{"merchant_id": merchant_id},
|
| 389 |
{
|
| 390 |
"$set": {
|
app/services/sales_order_service.py
CHANGED
|
@@ -8,7 +8,7 @@ from fastapi import HTTPException, status
|
|
| 8 |
from insightfy_utils.logging import get_logger
|
| 9 |
import secrets
|
| 10 |
|
| 11 |
-
from app.nosql import
|
| 12 |
from app.constants.collections import SCM_SALES_ORDERS_COLLECTION
|
| 13 |
from app.schemas.sales_order_schema import (
|
| 14 |
SalesOrderCreate,
|
|
@@ -130,7 +130,7 @@ class SalesOrderService:
|
|
| 130 |
order_number = payload.order_number or generate_order_number(payload.branch_id)
|
| 131 |
|
| 132 |
# Check order number uniqueness
|
| 133 |
-
existing = await
|
| 134 |
{"order_number": order_number}
|
| 135 |
)
|
| 136 |
if existing:
|
|
@@ -238,7 +238,7 @@ class SalesOrderService:
|
|
| 238 |
}
|
| 239 |
|
| 240 |
try:
|
| 241 |
-
await
|
| 242 |
|
| 243 |
logger.info(
|
| 244 |
f"Created sales order {sales_order_id}",
|
|
@@ -262,7 +262,7 @@ class SalesOrderService:
|
|
| 262 |
@staticmethod
|
| 263 |
async def get_sales_order(sales_order_id: str) -> SalesOrderResponse:
|
| 264 |
"""Get sales order by ID."""
|
| 265 |
-
sales_order = await
|
| 266 |
{"sales_order_id": sales_order_id}
|
| 267 |
)
|
| 268 |
|
|
@@ -311,10 +311,10 @@ class SalesOrderService:
|
|
| 311 |
|
| 312 |
try:
|
| 313 |
# Get total count
|
| 314 |
-
total = await
|
| 315 |
|
| 316 |
# Get documents
|
| 317 |
-
cursor =
|
| 318 |
documents = await cursor.to_list(length=limit)
|
| 319 |
|
| 320 |
return {
|
|
@@ -340,7 +340,7 @@ class SalesOrderService:
|
|
| 340 |
) -> SalesOrderResponse:
|
| 341 |
"""Update a sales order."""
|
| 342 |
# Check exists
|
| 343 |
-
existing = await
|
| 344 |
{"sales_order_id": sales_order_id}
|
| 345 |
)
|
| 346 |
if not existing:
|
|
@@ -377,7 +377,7 @@ class SalesOrderService:
|
|
| 377 |
update_data["updated_at"] = datetime.utcnow().isoformat()
|
| 378 |
|
| 379 |
try:
|
| 380 |
-
await
|
| 381 |
{"sales_order_id": sales_order_id},
|
| 382 |
{"$set": update_data}
|
| 383 |
)
|
|
@@ -409,7 +409,7 @@ class SalesOrderService:
|
|
| 409 |
request: InvoiceGenerateRequest
|
| 410 |
) -> InvoiceGenerateResponse:
|
| 411 |
"""Generate invoice for a sales order."""
|
| 412 |
-
sales_order = await
|
| 413 |
{"sales_order_id": sales_order_id}
|
| 414 |
)
|
| 415 |
|
|
@@ -430,7 +430,7 @@ class SalesOrderService:
|
|
| 430 |
invoice_pdf_url = f"https://cdn.example.com/invoices/{invoice_number}.pdf"
|
| 431 |
|
| 432 |
try:
|
| 433 |
-
await
|
| 434 |
{"sales_order_id": sales_order_id},
|
| 435 |
{
|
| 436 |
"$set": {
|
|
@@ -475,17 +475,17 @@ class SalesOrderService:
|
|
| 475 |
{"$match": {"merchant_id": merchant_id}},
|
| 476 |
{"$group": {"_id": None, "total": {"$sum": "$summary.grand_total"}}}
|
| 477 |
]
|
| 478 |
-
total_sales_result = await
|
| 479 |
total_sales = total_sales_result[0]["total"] if total_sales_result else 0
|
| 480 |
|
| 481 |
# Pending orders
|
| 482 |
-
pending_count = await
|
| 483 |
"merchant_id": merchant_id,
|
| 484 |
"status": {"$in": [SalesOrderStatus.CONFIRMED.value, SalesOrderStatus.PROCESSING.value]}
|
| 485 |
})
|
| 486 |
|
| 487 |
# Fulfilled orders
|
| 488 |
-
fulfilled_count = await
|
| 489 |
"merchant_id": merchant_id,
|
| 490 |
"status": SalesOrderStatus.FULFILLED.value
|
| 491 |
})
|
|
@@ -500,7 +500,7 @@ class SalesOrderService:
|
|
| 500 |
},
|
| 501 |
{"$group": {"_id": None, "revenue": {"$sum": "$summary.grand_total"}}}
|
| 502 |
]
|
| 503 |
-
revenue_result = await
|
| 504 |
revenue = revenue_result[0]["revenue"] if revenue_result else 0
|
| 505 |
|
| 506 |
return SalesWidgetsResponse(
|
|
|
|
| 8 |
from insightfy_utils.logging import get_logger
|
| 9 |
import secrets
|
| 10 |
|
| 11 |
+
from app.nosql import get_database
|
| 12 |
from app.constants.collections import SCM_SALES_ORDERS_COLLECTION
|
| 13 |
from app.schemas.sales_order_schema import (
|
| 14 |
SalesOrderCreate,
|
|
|
|
| 130 |
order_number = payload.order_number or generate_order_number(payload.branch_id)
|
| 131 |
|
| 132 |
# Check order number uniqueness
|
| 133 |
+
existing = await get_database()[SCM_SALES_ORDERS_COLLECTION].find_one(
|
| 134 |
{"order_number": order_number}
|
| 135 |
)
|
| 136 |
if existing:
|
|
|
|
| 238 |
}
|
| 239 |
|
| 240 |
try:
|
| 241 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].insert_one(sales_order)
|
| 242 |
|
| 243 |
logger.info(
|
| 244 |
f"Created sales order {sales_order_id}",
|
|
|
|
| 262 |
@staticmethod
|
| 263 |
async def get_sales_order(sales_order_id: str) -> SalesOrderResponse:
|
| 264 |
"""Get sales order by ID."""
|
| 265 |
+
sales_order = await get_database()[SCM_SALES_ORDERS_COLLECTION].find_one(
|
| 266 |
{"sales_order_id": sales_order_id}
|
| 267 |
)
|
| 268 |
|
|
|
|
| 311 |
|
| 312 |
try:
|
| 313 |
# Get total count
|
| 314 |
+
total = await get_database()[SCM_SALES_ORDERS_COLLECTION].count_documents(query)
|
| 315 |
|
| 316 |
# Get documents
|
| 317 |
+
cursor = get_database()[SCM_SALES_ORDERS_COLLECTION].find(query).sort(sort_field, sort_order).skip(skip).limit(limit)
|
| 318 |
documents = await cursor.to_list(length=limit)
|
| 319 |
|
| 320 |
return {
|
|
|
|
| 340 |
) -> SalesOrderResponse:
|
| 341 |
"""Update a sales order."""
|
| 342 |
# Check exists
|
| 343 |
+
existing = await get_database()[SCM_SALES_ORDERS_COLLECTION].find_one(
|
| 344 |
{"sales_order_id": sales_order_id}
|
| 345 |
)
|
| 346 |
if not existing:
|
|
|
|
| 377 |
update_data["updated_at"] = datetime.utcnow().isoformat()
|
| 378 |
|
| 379 |
try:
|
| 380 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].update_one(
|
| 381 |
{"sales_order_id": sales_order_id},
|
| 382 |
{"$set": update_data}
|
| 383 |
)
|
|
|
|
| 409 |
request: InvoiceGenerateRequest
|
| 410 |
) -> InvoiceGenerateResponse:
|
| 411 |
"""Generate invoice for a sales order."""
|
| 412 |
+
sales_order = await get_database()[SCM_SALES_ORDERS_COLLECTION].find_one(
|
| 413 |
{"sales_order_id": sales_order_id}
|
| 414 |
)
|
| 415 |
|
|
|
|
| 430 |
invoice_pdf_url = f"https://cdn.example.com/invoices/{invoice_number}.pdf"
|
| 431 |
|
| 432 |
try:
|
| 433 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].update_one(
|
| 434 |
{"sales_order_id": sales_order_id},
|
| 435 |
{
|
| 436 |
"$set": {
|
|
|
|
| 475 |
{"$match": {"merchant_id": merchant_id}},
|
| 476 |
{"$group": {"_id": None, "total": {"$sum": "$summary.grand_total"}}}
|
| 477 |
]
|
| 478 |
+
total_sales_result = await get_database()[SCM_SALES_ORDERS_COLLECTION].aggregate(pipeline_total).to_list(1)
|
| 479 |
total_sales = total_sales_result[0]["total"] if total_sales_result else 0
|
| 480 |
|
| 481 |
# Pending orders
|
| 482 |
+
pending_count = await get_database()[SCM_SALES_ORDERS_COLLECTION].count_documents({
|
| 483 |
"merchant_id": merchant_id,
|
| 484 |
"status": {"$in": [SalesOrderStatus.CONFIRMED.value, SalesOrderStatus.PROCESSING.value]}
|
| 485 |
})
|
| 486 |
|
| 487 |
# Fulfilled orders
|
| 488 |
+
fulfilled_count = await get_database()[SCM_SALES_ORDERS_COLLECTION].count_documents({
|
| 489 |
"merchant_id": merchant_id,
|
| 490 |
"status": SalesOrderStatus.FULFILLED.value
|
| 491 |
})
|
|
|
|
| 500 |
},
|
| 501 |
{"$group": {"_id": None, "revenue": {"$sum": "$summary.grand_total"}}}
|
| 502 |
]
|
| 503 |
+
revenue_result = await get_database()[SCM_SALES_ORDERS_COLLECTION].aggregate(pipeline_revenue).to_list(1)
|
| 504 |
revenue = revenue_result[0]["revenue"] if revenue_result else 0
|
| 505 |
|
| 506 |
return SalesWidgetsResponse(
|
app/utils/db_init.py
CHANGED
|
@@ -3,7 +3,7 @@ Database initialization utilities.
|
|
| 3 |
Creates indexes and sets up collections for the SCM microservice.
|
| 4 |
"""
|
| 5 |
from insightfy_utils.logging import get_logger
|
| 6 |
-
from app.nosql import
|
| 7 |
from app.constants.collections import (
|
| 8 |
SCM_MERCHANTS_COLLECTION,
|
| 9 |
SCM_EMPLOYEES_COLLECTION,
|
|
@@ -26,58 +26,58 @@ async def create_indexes():
|
|
| 26 |
logger.info("Creating database indexes")
|
| 27 |
|
| 28 |
# Merchants collection indexes
|
| 29 |
-
await
|
| 30 |
-
await
|
| 31 |
-
await
|
| 32 |
-
await
|
| 33 |
logger.info(f"Created indexes for {SCM_MERCHANTS_COLLECTION}")
|
| 34 |
|
| 35 |
# Employees collection indexes
|
| 36 |
-
await
|
| 37 |
-
await
|
| 38 |
-
await
|
| 39 |
-
await
|
| 40 |
-
await
|
| 41 |
("merchant_id", 1),
|
| 42 |
("role_id", 1)
|
| 43 |
])
|
| 44 |
logger.info(f"Created indexes for {SCM_EMPLOYEES_COLLECTION}")
|
| 45 |
|
| 46 |
# Roles collection indexes
|
| 47 |
-
await
|
| 48 |
("merchant_id", 1),
|
| 49 |
("role_id", 1)
|
| 50 |
], unique=True)
|
| 51 |
-
await
|
| 52 |
logger.info(f"Created indexes for {SCM_ROLES_COLLECTION}")
|
| 53 |
|
| 54 |
# Auth logs collection indexes
|
| 55 |
-
await
|
| 56 |
("merchant_id", 1),
|
| 57 |
("timestamp", -1)
|
| 58 |
])
|
| 59 |
-
await
|
| 60 |
("associate_id", 1),
|
| 61 |
("timestamp", -1)
|
| 62 |
])
|
| 63 |
-
await
|
| 64 |
|
| 65 |
# TTL index for 90-day retention (7776000 seconds)
|
| 66 |
-
await
|
| 67 |
"timestamp",
|
| 68 |
expireAfterSeconds=7776000
|
| 69 |
)
|
| 70 |
logger.info(f"Created indexes for {SCM_AUTH_LOGS_COLLECTION}")
|
| 71 |
|
| 72 |
# Sales orders collection indexes
|
| 73 |
-
await
|
| 74 |
-
await
|
| 75 |
-
await
|
| 76 |
-
await
|
| 77 |
-
await
|
| 78 |
-
await
|
| 79 |
-
await
|
| 80 |
-
await
|
| 81 |
("merchant_id", 1),
|
| 82 |
("order_date", -1)
|
| 83 |
])
|
|
@@ -97,11 +97,11 @@ async def drop_indexes():
|
|
| 97 |
try:
|
| 98 |
logger.warning("Dropping all database indexes")
|
| 99 |
|
| 100 |
-
await
|
| 101 |
-
await
|
| 102 |
-
await
|
| 103 |
-
await
|
| 104 |
-
await
|
| 105 |
|
| 106 |
logger.info("All database indexes dropped")
|
| 107 |
|
|
|
|
| 3 |
Creates indexes and sets up collections for the SCM microservice.
|
| 4 |
"""
|
| 5 |
from insightfy_utils.logging import get_logger
|
| 6 |
+
from app.nosql import get_database
|
| 7 |
from app.constants.collections import (
|
| 8 |
SCM_MERCHANTS_COLLECTION,
|
| 9 |
SCM_EMPLOYEES_COLLECTION,
|
|
|
|
| 26 |
logger.info("Creating database indexes")
|
| 27 |
|
| 28 |
# Merchants collection indexes
|
| 29 |
+
await get_database()[SCM_MERCHANTS_COLLECTION].create_index("merchant_id", unique=True)
|
| 30 |
+
await get_database()[SCM_MERCHANTS_COLLECTION].create_index("business_name", unique=True)
|
| 31 |
+
await get_database()[SCM_MERCHANTS_COLLECTION].create_index("merchant_type")
|
| 32 |
+
await get_database()[SCM_MERCHANTS_COLLECTION].create_index("contact_email")
|
| 33 |
logger.info(f"Created indexes for {SCM_MERCHANTS_COLLECTION}")
|
| 34 |
|
| 35 |
# Employees collection indexes
|
| 36 |
+
await get_database()[SCM_EMPLOYEES_COLLECTION].create_index("associate_id", unique=True)
|
| 37 |
+
await get_database()[SCM_EMPLOYEES_COLLECTION].create_index("email", unique=True)
|
| 38 |
+
await get_database()[SCM_EMPLOYEES_COLLECTION].create_index("mobile", unique=True)
|
| 39 |
+
await get_database()[SCM_EMPLOYEES_COLLECTION].create_index("merchant_id")
|
| 40 |
+
await get_database()[SCM_EMPLOYEES_COLLECTION].create_index([
|
| 41 |
("merchant_id", 1),
|
| 42 |
("role_id", 1)
|
| 43 |
])
|
| 44 |
logger.info(f"Created indexes for {SCM_EMPLOYEES_COLLECTION}")
|
| 45 |
|
| 46 |
# Roles collection indexes
|
| 47 |
+
await get_database()[SCM_ROLES_COLLECTION].create_index([
|
| 48 |
("merchant_id", 1),
|
| 49 |
("role_id", 1)
|
| 50 |
], unique=True)
|
| 51 |
+
await get_database()[SCM_ROLES_COLLECTION].create_index("merchant_id")
|
| 52 |
logger.info(f"Created indexes for {SCM_ROLES_COLLECTION}")
|
| 53 |
|
| 54 |
# Auth logs collection indexes
|
| 55 |
+
await get_database()[SCM_AUTH_LOGS_COLLECTION].create_index([
|
| 56 |
("merchant_id", 1),
|
| 57 |
("timestamp", -1)
|
| 58 |
])
|
| 59 |
+
await get_database()[SCM_AUTH_LOGS_COLLECTION].create_index([
|
| 60 |
("associate_id", 1),
|
| 61 |
("timestamp", -1)
|
| 62 |
])
|
| 63 |
+
await get_database()[SCM_AUTH_LOGS_COLLECTION].create_index("event_type")
|
| 64 |
|
| 65 |
# TTL index for 90-day retention (7776000 seconds)
|
| 66 |
+
await get_database()[SCM_AUTH_LOGS_COLLECTION].create_index(
|
| 67 |
"timestamp",
|
| 68 |
expireAfterSeconds=7776000
|
| 69 |
)
|
| 70 |
logger.info(f"Created indexes for {SCM_AUTH_LOGS_COLLECTION}")
|
| 71 |
|
| 72 |
# Sales orders collection indexes
|
| 73 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].create_index("sales_order_id", unique=True)
|
| 74 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].create_index("order_number", unique=True)
|
| 75 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].create_index("merchant_id")
|
| 76 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].create_index("branch_id")
|
| 77 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].create_index("status")
|
| 78 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].create_index("order_date")
|
| 79 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].create_index("customer.customer_id")
|
| 80 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].create_index([
|
| 81 |
("merchant_id", 1),
|
| 82 |
("order_date", -1)
|
| 83 |
])
|
|
|
|
| 97 |
try:
|
| 98 |
logger.warning("Dropping all database indexes")
|
| 99 |
|
| 100 |
+
await get_database()[SCM_MERCHANTS_COLLECTION].drop_indexes()
|
| 101 |
+
await get_database()[SCM_EMPLOYEES_COLLECTION].drop_indexes()
|
| 102 |
+
await get_database()[SCM_ROLES_COLLECTION].drop_indexes()
|
| 103 |
+
await get_database()[SCM_AUTH_LOGS_COLLECTION].drop_indexes()
|
| 104 |
+
await get_database()[SCM_SALES_ORDERS_COLLECTION].drop_indexes()
|
| 105 |
|
| 106 |
logger.info("All database indexes dropped")
|
| 107 |
|