# Service Management API Documentation

Base URL: `https://api.alldigtalseva.com`

---

## Table of Contents

1. [Service Management APIs (Admin)](#service-management-apis-admin)
2. [Service Check APIs (Public/Angular)](#service-check-apis-publicangular)
3. [Angular Integration Guide](#angular-integration-guide)

---

## Service Management APIs (Admin)

All admin endpoints require Bearer token authentication.

### Add New Service

Add a new service that will be available in the Angular frontend.

**Endpoint:** `POST /api/admin/service`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "name": "Farmer ID",
    "path": "/user/farmerid",
    "is_coming_soon": false
}
```

**Parameters:**
- `name` (required, string, max: 255): Service name
- `path` (required, string, unique): Service path (must start with `/`, e.g., `/user/farmerid`)
- `is_coming_soon` (optional, boolean): Whether service is coming soon (default: `false`)

**Success Response (201):**
```json
{
    "success": true,
    "message": "Service added successfully",
    "data": {
        "id": 1,
        "name": "Farmer ID",
        "path": "/user/farmerid",
        "is_coming_soon": false,
        "created_by": 1,
        "created_at": "2025-12-04T07:40:00.000000Z",
        "updated_at": "2025-12-04T07:40:00.000000Z"
    }
}
```

**Error Response (422) - Validation Error:**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "path": ["The path has already been taken."]
    }
}
```

**cURL Example:**
```bash
curl -X POST https://api.alldigtalseva.com/api/admin/service \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Farmer ID",
    "path": "/user/farmerid",
    "is_coming_soon": false
  }'
```

---

### Get All Services

Get list of all services.

**Endpoint:** `GET /api/admin/service`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Farmer ID",
            "path": "/user/farmerid",
            "is_coming_soon": false,
            "created_by": 1,
            "created_at": "2025-12-04T07:40:00.000000Z",
            "updated_at": "2025-12-04T07:40:00.000000Z"
        },
        {
            "id": 2,
            "name": "Aadhaar Card",
            "path": "/user/aadhaar",
            "is_coming_soon": true,
            "created_by": 1,
            "created_at": "2025-12-04T07:41:00.000000Z",
            "updated_at": "2025-12-04T07:41:00.000000Z"
        }
    ]
}
```

---

### Get Single Service

Get details of a specific service.

**Endpoint:** `GET /api/admin/service/{id}`

**Headers:**
```
Authorization: Bearer {admin_token}
```

---

### Update Service

Update an existing service.

**Endpoint:** `PUT /api/admin/service/{id}` or `PATCH /api/admin/service/{id}`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body (all fields optional):**
```json
{
    "name": "Updated Farmer ID",
    "path": "/user/farmerid",
    "is_coming_soon": true
}
```

**Success Response (200):**
```json
{
    "success": true,
    "message": "Service updated successfully",
    "data": {
        "id": 1,
        "name": "Updated Farmer ID",
        "path": "/user/farmerid",
        "is_coming_soon": true,
        "created_by": 1,
        "created_at": "2025-12-04T07:40:00.000000Z",
        "updated_at": "2025-12-04T07:42:00.000000Z"
    }
}
```

---

### Delete Service

Delete a service.

**Endpoint:** `DELETE /api/admin/service/{id}`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "message": "Service deleted successfully"
}
```

---

## Service Check APIs (Public/Angular)

These endpoints are public and can be used by Angular frontend to check service availability.

### Check Service by Path (Query Parameter)

Check if a service is available or coming soon by providing path as query parameter.

**Endpoint:** `GET /api/service/check?path={path}`

**Query Parameters:**
- `path` (required, string): Service path (e.g., `/user/farmerid`)

**Success Response (200) - Service Available:**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "name": "Farmer ID",
        "path": "/user/farmerid",
        "is_coming_soon": false,
        "available": true,
        "message": "Service is available"
    }
}
```

**Success Response (200) - Service Coming Soon:**
```json
{
    "success": true,
    "data": {
        "id": 2,
        "name": "Aadhaar Card",
        "path": "/user/aadhaar",
        "is_coming_soon": true,
        "available": false,
        "message": "This service will come soon"
    }
}
```

**Error Response (404) - Service Not Found:**
```json
{
    "success": false,
    "message": "Service not found",
    "is_coming_soon": false,
    "available": false
}
```

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/service/check?path=/user/farmerid"
```

---

### Get Service by Path (Route Parameter)

Get service details by path using route parameter (useful for Angular routing).

**Endpoint:** `GET /api/service/path/{path}`

**Note:** Path should be provided without leading slash in URL, but stored with slash in database.

**Example:**
- URL: `/api/service/path/user/farmerid`
- Checks for path: `/user/farmerid`

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "name": "Farmer ID",
        "path": "/user/farmerid",
        "is_coming_soon": false,
        "available": true,
        "message": "Service is available"
    }
}
```

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/service/path/user/farmerid
```

---

### Get All Services (Public)

Get list of all services (public endpoint).

**Endpoint:** `GET /api/services`

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Farmer ID",
            "path": "/user/farmerid",
            "is_coming_soon": false,
            "created_by": 1,
            "created_at": "2025-12-04T07:40:00.000000Z",
            "updated_at": "2025-12-04T07:40:00.000000Z"
        }
    ]
}
```

---

## Angular Integration Guide

### Service Guard Implementation

Create an Angular guard to check service availability before routing:

**service.guard.ts:**
```typescript
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ServiceGuard implements CanActivate {
  private apiUrl = 'https://api.alldigtalseva.com/api';

  constructor(
    private http: HttpClient,
    private router: Router
  ) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    const path = route.routeConfig?.path || '';
    const fullPath = `/user/${path}`;

    return this.http.get<any>(`${this.apiUrl}/service/check`, {
      params: { path: fullPath }
    }).pipe(
      map(response => {
        if (response.success && response.data) {
          if (response.data.is_coming_soon) {
            // Show coming soon message
            alert('This service will come soon');
            return false;
          }
          return true;
        }
        return false;
      }),
      catchError(error => {
        console.error('Service check failed:', error);
        return of(false);
      })
    );
  }
}
```

---

### Route Configuration

**app-routing.module.ts:**
```typescript
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ServiceGuard } from './guards/service.guard';
import { FarmerIdComponent } from './components/farmer-id/farmer-id.component';
import { ComingSoonComponent } from './components/coming-soon/coming-soon.component';

const routes: Routes = [
  {
    path: 'user/farmerid',
    component: FarmerIdComponent,
    canActivate: [ServiceGuard]
  },
  {
    path: 'coming-soon',
    component: ComingSoonComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
```

---

### Service Check Component

**service-check.component.ts:**
```typescript
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-service-check',
  template: `
    <div *ngIf="loading">Checking service...</div>
    <div *ngIf="service">
      <div *ngIf="service.is_coming_soon" class="coming-soon">
        <h2>This service will come soon</h2>
        <p>Service: {{ service.name }}</p>
      </div>
      <div *ngIf="!service.is_coming_soon">
        <!-- Service is available, show component -->
        <router-outlet></router-outlet>
      </div>
    </div>
  `
})
export class ServiceCheckComponent implements OnInit {
  service: any = null;
  loading = true;

  constructor(
    private route: ActivatedRoute,
    private http: HttpClient,
    private router: Router
  ) {}

  ngOnInit() {
    const path = this.route.snapshot.url.join('/');
    const fullPath = `/${path}`;

    this.http.get<any>(`https://api.alldigtalseva.com/api/service/check`, {
      params: { path: fullPath }
    }).subscribe({
      next: (response) => {
        this.loading = false;
        if (response.success && response.data) {
          this.service = response.data;
          if (response.data.is_coming_soon) {
            // Optionally redirect to coming soon page
            // this.router.navigate(['/coming-soon']);
          }
        }
      },
      error: (error) => {
        this.loading = false;
        console.error('Service check failed:', error);
      }
    });
  }
}
```

---

### Service Check Service (Angular Service)

**service-check.service.ts:**
```typescript
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ServiceCheckService {
  private apiUrl = 'https://api.alldigtalseva.com/api';

  constructor(private http: HttpClient) {}

  checkService(path: string): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/service/check`, {
      params: { path: path }
    }).pipe(
      map(response => response.data)
    );
  }

  getAllServices(): Observable<any[]> {
    return this.http.get<any>(`${this.apiUrl}/services`).pipe(
      map(response => response.data)
    );
  }
}
```

---

### Usage in Component

**farmer-id.component.ts:**
```typescript
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ServiceCheckService } from '../services/service-check.service';

@Component({
  selector: 'app-farmer-id',
  template: `
    <div class="service-container">
      <h1>Farmer ID Service</h1>
      <!-- Your service content here -->
    </div>
  `
})
export class FarmerIdComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private serviceCheck: ServiceCheckService
  ) {}

  ngOnInit() {
    const path = this.route.snapshot.url.join('/');
    const fullPath = `/${path}`;

    this.serviceCheck.checkService(fullPath).subscribe({
      next: (service) => {
        if (service.is_coming_soon) {
          // Show coming soon message
          alert('This service will come soon');
        } else {
          // Service is available, proceed
          console.log('Service is available:', service);
        }
      },
      error: (error) => {
        console.error('Service check failed:', error);
      }
    });
  }
}
```

---

### Coming Soon Component

**coming-soon.component.ts:**
```typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-coming-soon',
  template: `
    <div class="coming-soon-container">
      <div class="coming-soon-content">
        <h1>This service will come soon</h1>
        <p>We're working hard to bring you this service. Please check back later.</p>
        <button (click)="goBack()">Go Back</button>
      </div>
    </div>
  `,
  styles: [`
    .coming-soon-container {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      background-color: #f5f5f5;
    }
    .coming-soon-content {
      text-align: center;
      padding: 2rem;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    h1 {
      color: #333;
      margin-bottom: 1rem;
    }
    p {
      color: #666;
      margin-bottom: 2rem;
    }
    button {
      padding: 10px 20px;
      background-color: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
  `]
})
export class ComingSoonComponent {
  goBack() {
    window.history.back();
  }
}
```

---

### Route Resolver (Alternative Approach)

**service.resolver.ts:**
```typescript
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ServiceResolver implements Resolve<any> {
  private apiUrl = 'https://api.alldigtalseva.com/api';

  constructor(private http: HttpClient) {}

  resolve(route: ActivatedRouteSnapshot): Observable<any> {
    const path = route.routeConfig?.path || '';
    const fullPath = `/user/${path}`;

    return this.http.get<any>(`${this.apiUrl}/service/check`, {
      params: { path: fullPath }
    }).pipe(
      map(response => response.data),
      catchError(error => {
        console.error('Service resolver error:', error);
        return of(null);
      })
    );
  }
}
```

**Usage in routes:**
```typescript
{
  path: 'user/farmerid',
  component: FarmerIdComponent,
  resolve: { service: ServiceResolver }
}
```

---

## Important Notes

1. **Path Format**: 
   - Paths must start with `/` (e.g., `/user/farmerid`)
   - Paths must be unique
   - Valid characters: letters, numbers, `/`, and `-`

2. **Coming Soon Status**:
   - When `is_coming_soon` is `true`, show "This service will come soon" message
   - When `is_coming_soon` is `false`, service is available

3. **Angular Routing**:
   - Use guards or resolvers to check service availability before loading component
   - Redirect to coming soon page if service is not available

4. **API Response**:
   - `available`: `true` when service is ready, `false` when coming soon
   - `message`: Human-readable message about service status

---

## Example Workflow

1. **Admin adds service:**
   ```bash
   POST /api/admin/service
   {
     "name": "Farmer ID",
     "path": "/user/farmerid",
     "is_coming_soon": false
   }
   ```

2. **User navigates to `/user/farmerid` in Angular app**

3. **Angular guard checks service:**
   ```typescript
   GET /api/service/check?path=/user/farmerid
   ```

4. **If coming soon:**
   - Show "This service will come soon" message
   - Optionally redirect to coming soon page

5. **If available:**
   - Load the service component
   - User can use the service

---

## Response Codes

| Status Code | Description |
|------------|-------------|
| 200 | Success - Service found |
| 404 | Not Found - Service doesn't exist |
| 401 | Unauthorized - Admin token required for management APIs |
| 422 | Validation Error - Invalid input data |

---

**Last Updated:** December 4, 2025


