---
name: ServicePatterns
description: Quy tắc chuẩn cho Service layer (Interface, Implementation, DI, Repository, Result patterns).
---

# Service Layer Patterns

Tài liệu này mô tả các quy tắc bắt buộc khi tạo Service trong dự án LADA Backend.

## 1. File Organization (QUAN TRỌNG)

**Interface và Implementation phải nằm trong cùng 1 file.**

```
✅ ĐÚNG:
Services/Premises/PremiseService.cs  → chứa cả IPremiseService + PremiseService

❌ SAI:
Services/Premises/IPremiseService.cs → chỉ chứa interface
Services/Premises/PremiseService.cs  → chỉ chứa class
```

## 2. File & Class Naming

| Loại | Convention | Ví dụ |
|------|-----------|-------|
| File | `{Name}Service.cs` | `ExpenseService.cs` |
| Interface | `I{Name}Service` | `IExpenseService` |
| Class | `{Name}Service` | `ExpenseService` |

## 3. Standard Service Structure

```csharp
public interface IExampleService
{
    /// <summary>
    /// Tìm kiếm entity
    /// </summary>
    Task<SmartTableResult<ExampleItem>> Search(SmartTableParam param);
    
    /// <summary>
    /// Tạo hoặc cập nhật entity
    /// </summary>
    Task<BaseResult> CreateOrUpdate(ExampleModel model);
    
    /// <summary>
    /// Xóa entity
    /// </summary>
    Task<BaseResult> Delete(ExampleModel model);
    
    /// <summary>
    /// Lấy thông tin entity theo ID
    /// </summary>
    Task<ExampleModel> GetById(int id);
}

public class ExampleService : IExampleService
{
    private readonly IRepository<Example> _repository;
    private readonly IUserService _userService;

    public ExampleService(IRepository<Example> repository, IUserService userService)
    {
        _repository = repository;
        _userService = userService;
    }

    // Implementation...
}
```

## 4. DI Registration

Đăng ký tại `Ladaer.BackEnd/Infrastructures/Startup/DependencyRegister.cs`:

```csharp
services.AddTransient<IExampleService, ExampleService>();
```

## 5. Repository Pattern

```csharp
private readonly IRepository<Entity> _repository;
private readonly IUserRepository<User> _userRepository;
```

## 6. Result Patterns

```csharp
// Standard result types
BaseResult result = new BaseResult();                     // CRUD result
SmartTableResult<Item> searchResult;                      // Search/List result
EntityModel singleResult;                                 // GetById result
```

## 7. Current User Context (trong Controller)

```csharp
var currentUser = User.GetCurrentUser();
model.UpdatedBy = currentUser.UserId;
model.UpdatedByUserName = currentUser.UserName;
```

## 8. Agency-Based Operations

```csharp
var agencyId = await _userService.GetAgencyIdByIdAsync(currentUser.UserId);
if (agencyId <= 0)
{
    return BadRequest("User không thuộc đại lý nào");
}
```

## 9. Service Categories Reference

| Category | Services |
|----------|----------|
| Orders | OrderService, OrderPackageService, OrderFinService |
| Trucks | TruckService, TruckActivityService, TruckAssetService |
| Finance | FeeService, BackFeeService, ExpenseService |
| Operations | OperationService, WarehouseService |
| Driver App | DriverAppService, DriverAppOrderService, DriverFinService |
| Identity | UserService, RoleService, PermissionService |
| Media | UnifiedMediaService, PictureService |
