File size: 7,588 Bytes
32eb084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# Tasks API Documentation

## Overview
The Tasks API allows employees to fetch their assigned tasks/visits for the day.

## Database Setup

### Option 1: Using Python Migration Script
```bash
python migrate_tasks.py
```

### Option 2: Using SQL Script
```bash
psql -U postgres -d cuatrolabs -f create_tasks_table.sql
```

## API Endpoint

### GET /tracker/tasks/today
Fetch all tasks assigned to the authenticated employee for today.

**Authentication:** Required (JWT Bearer token)

**Response:**
```json
{
  "success": true,
  "tasks": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "title": "Visit Customer ABC",
      "description": "Deliver products and collect payment",
      "status": "not_started",
      "lat": 19.0760,
      "lon": 72.8777,
      "address": "123 Main St, Mumbai",
      "scheduledAt": "2024-02-17T10:00:00"
    }
  ],
  "count": 1
}
```

**Task Status Values:**
- `not_started` - Task has not been started yet
- `in_progress` - Task is currently being worked on
- `completed` - Task has been completed

**Example Request:**
```bash
curl -X GET "http://localhost:8003/tracker/tasks/today" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

---

### PATCH /tracker/tasks/{task_id}/status
Update the status of a task with location and timestamp tracking.

**Authentication:** Required (JWT Bearer token)

**Path Parameters:**
- `task_id` - UUID of the task to update

**Request Body:**
```json
{
  "status": "in_progress",
  "timestamp": 1708156800000,
  "latitude": 19.0760,
  "longitude": 72.8777
}
```

**Response:**
```json
{
  "success": true,
  "message": "Task status updated successfully"
}
```

**Status Transition Rules:**
- `not_started` β†’ `in_progress` (captures started_at timestamp)
- `not_started` β†’ `completed` (direct completion allowed)
- `in_progress` β†’ `completed` (captures completed_at timestamp)
- `in_progress` β†’ `not_started` (revert allowed)
- `completed` β†’ `in_progress` (reopening allowed)

**Validation Rules:**
- Location (latitude/longitude) is mandatory
- Timestamp must be Unix milliseconds (positive integer)
- Latitude must be between -90 and 90
- Longitude must be between -180 and 180
- Only assigned employee can update the task
- Invalid status transitions return 400 error
- Task not found or unauthorized returns 404 error

**Example Request:**
```bash
curl -X PATCH "http://localhost:8003/tracker/tasks/550e8400-e29b-41d4-a716-446655440000/status" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "in_progress",
    "timestamp": 1708156800000,
    "latitude": 19.0760,
    "longitude": 72.8777
  }'
```

**Error Responses:**

400 Bad Request - Invalid status transition:
```json
{
  "success": false,
  "error": "Cannot transition from 'completed' to 'not_started'",
  "detail": "Cannot transition from 'completed' to 'not_started'"
}
```

404 Not Found - Task not found or unauthorized:
```json
{
  "success": false,
  "error": "Task with ID {task_id} not found",
  "detail": "Task with ID {task_id} not found"
}
```

## Database Schema

### Table: trans.scm_tasks
```sql
CREATE TABLE trans.scm_tasks (
    id UUID PRIMARY KEY,
    merchant_id UUID NOT NULL,
    assigned_to UUID NOT NULL,
    title TEXT NOT NULL,
    description TEXT,
    status TEXT DEFAULT 'not_started',
    latitude DOUBLE PRECISION,
    longitude DOUBLE PRECISION,
    address TEXT,
    scheduled_at TIMESTAMP,
    started_at BIGINT,
    completed_at BIGINT,
    created_at TIMESTAMP DEFAULT now(),
    updated_at TIMESTAMP DEFAULT now()
);
```

### Indexes
- `idx_scm_tasks_assigned_date` - Optimizes queries by assigned_to and scheduled_at
- `idx_scm_tasks_merchant_status` - Optimizes queries by merchant_id and status
- `idx_scm_tasks_status_scheduled` - Optimizes queries by status and scheduled_at

## Testing

### 1. Run the migration
```bash
python migrate_tasks.py
```

### 2. Insert test data
```sql
INSERT INTO trans.scm_tasks (
    id, merchant_id, assigned_to, title, description, 
    status, latitude, longitude, address, scheduled_at
) VALUES (
    gen_random_uuid(),
    'YOUR_MERCHANT_ID'::uuid,
    'YOUR_EMPLOYEE_ID'::uuid,
    'Visit Customer ABC',
    'Deliver products and collect payment',
    'not_started',
    19.0760,
    72.8777,
    '123 Main St, Mumbai',
    CURRENT_DATE + INTERVAL '10 hours'
);
```

### 3. Generate test token
```bash
python generate_test_token.py
```

### 4. Test GET today's tasks
```bash
curl -X GET "http://localhost:8003/tracker/tasks/today" \
  -H "Authorization: Bearer $(cat test_token.txt)"
```

### 5. Test PATCH update task status

Get the task ID from the previous response, then:

**Start the task (not_started β†’ in_progress):**
```bash
TASK_ID="your-task-id-here"
curl -X PATCH "http://localhost:8003/tracker/tasks/${TASK_ID}/status" \
  -H "Authorization: Bearer $(cat test_token.txt)" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "in_progress",
    "timestamp": '$(date +%s000)',
    "latitude": 19.0760,
    "longitude": 72.8777
  }'
```

**Complete the task (in_progress β†’ completed):**
```bash
curl -X PATCH "http://localhost:8003/tracker/tasks/${TASK_ID}/status" \
  -H "Authorization: Bearer $(cat test_token.txt)" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "completed",
    "timestamp": '$(date +%s000)',
    "latitude": 19.0761,
    "longitude": 72.8778
  }'
```

**Test invalid transition (should fail):**
```bash
curl -X PATCH "http://localhost:8003/tracker/tasks/${TASK_ID}/status" \
  -H "Authorization: Bearer $(cat test_token.txt)" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "not_started",
    "timestamp": '$(date +%s000)',
    "latitude": 19.0761,
    "longitude": 72.8778
  }'
```

## Implementation Details

### Files Created/Modified
- `app/tracker/tasks/router.py` - API endpoint handlers (GET today, PATCH status)
- `app/tracker/tasks/service.py` - Business logic with status validation
- `app/tracker/tasks/schemas.py` - Request/response models
- `app/main.py` - Router registration
- `migrate_tasks.py` - Database migration script
- `create_tasks_table.sql` - SQL script for manual setup

### Key Features

**GET /tracker/tasks/today:**
- JWT authentication required
- Filters tasks by authenticated employee
- Returns only today's tasks (based on scheduled_at)
- Tasks ordered by scheduled time
- Includes geolocation data (lat/lon)
- Status tracking (not_started, in_progress, completed)

**PATCH /tracker/tasks/{task_id}/status:**
- JWT authentication required
- Authorization checks (task must be assigned to employee)
- Status transition validation
- Location tracking on every update
- Timestamp tracking (started_at, completed_at)
- Idempotent updates (same status allowed)
- Comprehensive error handling with appropriate HTTP status codes

### Status Transition Logic
The service validates all status transitions to maintain data integrity:
- Prevents invalid transitions (e.g., completed β†’ not_started requires going through in_progress)
- Allows reopening completed tasks
- Allows reverting in-progress tasks
- Captures timestamps at key milestones (started_at, completed_at)

### Security Features
- JWT token validation on all endpoints
- Employee authorization (can only update own tasks)
- Merchant validation (task must belong to employee's merchant)
- Task existence verification
- Returns 404 for unauthorized access (doesn't reveal task existence)

## API Documentation
Once the server is running, visit:
- Swagger UI: http://localhost:8003/docs
- ReDoc: http://localhost:8003/redoc