Skip to main content

Inventory Management

Manajemen inventori dengan stock tracking dan low stock alerts

๐ŸŽฏ Overview

Inventory adalah salah satu fitur utama dalam MStore Mobile yang menyediakan fungsionalitas untuk manajemen inventori dengan stock tracking dan low stock alerts.

๐Ÿ“‹ Features

  • โœ… Product CRUD operations
  • โœ… Stock tracking
  • โœ… Low stock alerts
  • โœ… Stock adjustment
  • โœ… Stock opname
  • โœ… Batch operations
  • โœ… Category management
  • โœ… Barcode scanning

๐Ÿ—๏ธ Architecture

BLoC Implementation

BLoC: InventoryBloc, CashierInventoryBloc, CreateInventoryBloc, DetailInventoryBloc
// Events
abstract class InventoryEvent extends Equatable {}

class LoadInventory extends InventoryEvent {}
class CreateInventory extends InventoryEvent {}
class UpdateInventory extends InventoryEvent {}
class DeleteInventory extends InventoryEvent {}

// States
abstract class InventoryState extends Equatable {}

class InventoryInitial extends InventoryState {}
class InventoryLoading extends InventoryState {}
class InventoryLoaded extends InventoryState {}
class InventoryError extends InventoryState {}

// BLoC
class InventoryBloc extends Bloc<InventoryEvent, InventoryState> {
  final InventoryRepository _repository;
  
  InventoryBloc({required InventoryRepository repository})
      : _repository = repository,
        super(InventoryInitial()) {
    on<LoadInventory>(_onLoad);
    on<CreateInventory>(_onCreate);
    on<UpdateInventory>(_onUpdate);
    on<DeleteInventory>(_onDelete);
  }
  
  Future<void> _onLoad(
    LoadInventory event,
    Emitter<InventoryState> emit,
  ) async {
    emit(InventoryLoading());
    
    final result = await _repository.getInventorys();
    
    result.fold(
      (failure) => emit(InventoryError(failure.message)),
      (data) => emit(InventoryLoaded(data)),
    );
  }
}

Repository Pattern

abstract class InventoryRepository {
  Future<Either<Failure, List<Inventory>>> getInventorys();
  Future<Either<Failure, Inventory>> getInventoryById(String id);
  Future<Either<Failure, Inventory>> createInventory(Inventory data);
  Future<Either<Failure, Inventory>> updateInventory(String id, Inventory data);
  Future<Either<Failure, void>> deleteInventory(String id);
}

class InventoryRepositoryImpl implements InventoryRepository {
  final InventoryApi _api;
  final InventoryLocalRepository _localRepo;
  
  @override
  Future<Either<Failure, List<Inventory>>> getInventorys() async {
    try {
      // Try local first (offline-first)
      final local = await _localRepo.getInventorys();
      
      // Sync with API in background
      final result = await _api.getInventorys();
      result.fold(
        (failure) => null,
        (data) => _localRepo.saveInventorys(data),
      );
      
      return Right(local.isNotEmpty ? local : result.getOrElse(() => []));
    } catch (e) {
      return Left(UnexpectedFailure(e.toString()));
    }
  }
}

๐Ÿ“ก API Integration

Endpoints

  • /api/v1/inventory/*
  • /api/v1/products/*

Request/Response Examples

Get List

GET /api/v1/inventory/*
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

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

Queries

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

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

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

// Get unsynced
final unsynced = await isar.inventoryLocals
    .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 InventoryPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => getIt<InventoryBloc>()..add(LoadInventory()),
      child: Scaffold(
        appBar: AppBar(title: Text('Inventory Management')),
        body: BlocBuilder<InventoryBloc, InventoryState>(
          builder: (context, state) {
            if (state is InventoryLoading) {
              return Center(child: CircularProgressIndicator());
            }
            
            if (state is InventoryError) {
              return ErrorWidget(message: state.message);
            }
            
            if (state is InventoryLoaded) {
              return InventoryListView(items: state.items);
            }
            
            return SizedBox.shrink();
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => _navigateToCreate(context),
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

๐Ÿงช Testing

Unit Tests

void main() {
  group('InventoryBloc', () {
    late InventoryBloc bloc;
    late MockInventoryRepository mockRepository;

    setUp(() {
      mockRepository = MockInventoryRepository();
      bloc = InventoryBloc(repository: mockRepository);
    });

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

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

    blocTest<InventoryBloc, InventoryState>(
      'emits [Loading, Loaded] when Load succeeds',
      build: () {
        when(() => mockRepository.getInventorys()).thenAnswer(
          (_) async => Right([Inventory(id: '1', name: 'Test')]),
        );
        return bloc;
      },
      act: (bloc) => bloc.add(LoadInventory()),
      expect: () => [
        InventoryLoading(),
        isA<InventoryLoaded>(),
      ],
    );
  });
}

๐Ÿ“Š 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