Skip to main content

Debt Management

Manajemen piutang pelanggan

๐ŸŽฏ Overview

Debt adalah salah satu fitur utama dalam MStore Mobile yang menyediakan fungsionalitas untuk manajemen piutang pelanggan.

๐Ÿ“‹ Features

  • โœ… Customer debt tracking
  • โœ… Payment installments
  • โœ… Debt reminders
  • โœ… Payment history
  • โœ… Debt reports

๐Ÿ—๏ธ Architecture

BLoC Implementation

BLoC: DebtBloc
// Events
abstract class DebtEvent extends Equatable {}

class LoadDebt extends DebtEvent {}
class CreateDebt extends DebtEvent {}
class UpdateDebt extends DebtEvent {}
class DeleteDebt extends DebtEvent {}

// States
abstract class DebtState extends Equatable {}

class DebtInitial extends DebtState {}
class DebtLoading extends DebtState {}
class DebtLoaded extends DebtState {}
class DebtError extends DebtState {}

// BLoC
class DebtBloc extends Bloc<DebtEvent, DebtState> {
  final DebtRepository _repository;
  
  DebtBloc({required DebtRepository repository})
      : _repository = repository,
        super(DebtInitial()) {
    on<LoadDebt>(_onLoad);
    on<CreateDebt>(_onCreate);
    on<UpdateDebt>(_onUpdate);
    on<DeleteDebt>(_onDelete);
  }
  
  Future<void> _onLoad(
    LoadDebt event,
    Emitter<DebtState> emit,
  ) async {
    emit(DebtLoading());
    
    final result = await _repository.getDebts();
    
    result.fold(
      (failure) => emit(DebtError(failure.message)),
      (data) => emit(DebtLoaded(data)),
    );
  }
}

Repository Pattern

abstract class DebtRepository {
  Future<Either<Failure, List<Debt>>> getDebts();
  Future<Either<Failure, Debt>> getDebtById(String id);
  Future<Either<Failure, Debt>> createDebt(Debt data);
  Future<Either<Failure, Debt>> updateDebt(String id, Debt data);
  Future<Either<Failure, void>> deleteDebt(String id);
}

class DebtRepositoryImpl implements DebtRepository {
  final DebtApi _api;
  final DebtLocalRepository _localRepo;
  
  @override
  Future<Either<Failure, List<Debt>>> getDebts() async {
    try {
      // Try local first (offline-first)
      final local = await _localRepo.getDebts();
      
      // Sync with API in background
      final result = await _api.getDebts();
      result.fold(
        (failure) => null,
        (data) => _localRepo.saveDebts(data),
      );
      
      return Right(local.isNotEmpty ? local : result.getOrElse(() => []));
    } catch (e) {
      return Left(UnexpectedFailure(e.toString()));
    }
  }
}

๐Ÿ“ก API Integration

Endpoints

  • /api/v1/debts/*

Request/Response Examples

Get List

GET /api/v1/debts/*
Authorization: Bearer {access_token}
Response:
{
  "success": true,
  "data": [
    {
      "id": "123",
      "name": "Example",
      "created_at": "2024-10-14T10:00:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 100
  }
}

๐Ÿ’พ Local Database (Isar)

Schema

  • DebtLocal
@collection
class DebtLocal {
  Id id = Isar.autoIncrement;
  
  @Index()
  String? debtId;
  
  String? name;
  DateTime? createdAt;
  DateTime? updatedAt;
  DateTime? syncedAt;
  
  bool? isSynced;
  bool? isDeleted;
}

Queries

// Get all
final items = await isar.debtLocals.where().findAll();

// Get by ID
final item = await isar.debtLocals
    .filter()
    .debtIdEqualTo(id)
    .findFirst();

// Search
final results = await isar.debtLocals
    .filter()
    .nameContains(query, caseSensitive: false)
    .findAll();

// Get unsynced
final unsynced = await isar.debtLocals
    .filter()
    .isSyncedEqualTo(false)
    .findAll();

๐Ÿ”„ Offline-First Strategy

Write Operations

  1. Save to local Isar immediately
  2. Show success to user
  3. Add to sync queue
  4. Background sync when online
  5. Update with server response

Read Operations

  1. Read from local Isar (fast)
  2. Show to user immediately
  3. Background fetch from API
  4. Update local cache if changed
  5. Notify UI if data updated

Conflict Resolution

  • Strategy: Last-write-wins
  • Timestamp: Server timestamp as source of truth
  • Logging: All conflicts logged for audit

๐ŸŽจ UI Components

Main Screen

class DebtPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => getIt<DebtBloc>()..add(LoadDebt()),
      child: Scaffold(
        appBar: AppBar(title: Text('Debt Management')),
        body: BlocBuilder<DebtBloc, DebtState>(
          builder: (context, state) {
            if (state is DebtLoading) {
              return Center(child: CircularProgressIndicator());
            }
            
            if (state is DebtError) {
              return ErrorWidget(message: state.message);
            }
            
            if (state is DebtLoaded) {
              return DebtListView(items: state.items);
            }
            
            return SizedBox.shrink();
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => _navigateToCreate(context),
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

๐Ÿงช Testing

Unit Tests

void main() {
  group('DebtBloc', () {
    late DebtBloc bloc;
    late MockDebtRepository mockRepository;

    setUp(() {
      mockRepository = MockDebtRepository();
      bloc = DebtBloc(repository: mockRepository);
    });

    tearDown(() {
      bloc.close();
    });

    test('initial state is DebtInitial', () {
      expect(bloc.state, equals(DebtInitial()));
    });

    blocTest<DebtBloc, DebtState>(
      'emits [Loading, Loaded] when Load succeeds',
      build: () {
        when(() => mockRepository.getDebts()).thenAnswer(
          (_) async => Right([Debt(id: '1', name: 'Test')]),
        );
        return bloc;
      },
      act: (bloc) => bloc.add(LoadDebt()),
      expect: () => [
        DebtLoading(),
        isA<DebtLoaded>(),
      ],
    );
  });
}

๐Ÿ“Š Performance Considerations

  • Lazy Loading: Load data on demand
  • Pagination: Implement pagination for large datasets
  • Caching: Cache frequently accessed data
  • Indexing: Use Isar indexes for fast queries
  • Background Sync: Sync in background to avoid blocking UI

๐Ÿ” Security

  • Authorization: Check user permissions before operations
  • Data Encryption: Sensitive data encrypted in Isar
  • Input Validation: Validate all user inputs
  • Audit Trail: Log all operations for audit

๐Ÿ“ฑ Platform-Specific

iOS

  • Use Cupertino widgets
  • Follow iOS HIG
  • Handle safe area insets

Android

  • Use Material widgets
  • Follow Material Design
  • Handle back button

Last Updated: October 14, 2024
Status: โœ… Production Ready