Skip to main content

Printer Integration

Integrasi dengan Bluetooth thermal printer

๐ŸŽฏ Overview

Printer adalah salah satu fitur utama dalam MStore Mobile yang menyediakan fungsionalitas untuk integrasi dengan bluetooth thermal printer.

๐Ÿ“‹ Features

  • โœ… Bluetooth printer pairing
  • โœ… Receipt printing
  • โœ… Custom receipt templates
  • โœ… Print queue
  • โœ… Printer status monitoring
  • โœ… Test print

๐Ÿ—๏ธ Architecture

BLoC Implementation

BLoC: PrinterBloc
// Events
abstract class PrinterEvent extends Equatable {}

class LoadPrinter extends PrinterEvent {}
class CreatePrinter extends PrinterEvent {}
class UpdatePrinter extends PrinterEvent {}
class DeletePrinter extends PrinterEvent {}

// States
abstract class PrinterState extends Equatable {}

class PrinterInitial extends PrinterState {}
class PrinterLoading extends PrinterState {}
class PrinterLoaded extends PrinterState {}
class PrinterError extends PrinterState {}

// BLoC
class PrinterBloc extends Bloc<PrinterEvent, PrinterState> {
  final PrinterRepository _repository;
  
  PrinterBloc({required PrinterRepository repository})
      : _repository = repository,
        super(PrinterInitial()) {
    on<LoadPrinter>(_onLoad);
    on<CreatePrinter>(_onCreate);
    on<UpdatePrinter>(_onUpdate);
    on<DeletePrinter>(_onDelete);
  }
  
  Future<void> _onLoad(
    LoadPrinter event,
    Emitter<PrinterState> emit,
  ) async {
    emit(PrinterLoading());
    
    final result = await _repository.getPrinters();
    
    result.fold(
      (failure) => emit(PrinterError(failure.message)),
      (data) => emit(PrinterLoaded(data)),
    );
  }
}

Repository Pattern

abstract class PrinterRepository {
  Future<Either<Failure, List<Printer>>> getPrinters();
  Future<Either<Failure, Printer>> getPrinterById(String id);
  Future<Either<Failure, Printer>> createPrinter(Printer data);
  Future<Either<Failure, Printer>> updatePrinter(String id, Printer data);
  Future<Either<Failure, void>> deletePrinter(String id);
}

class PrinterRepositoryImpl implements PrinterRepository {
  final PrinterApi _api;
  final PrinterLocalRepository _localRepo;
  
  @override
  Future<Either<Failure, List<Printer>>> getPrinters() async {
    try {
      // Try local first (offline-first)
      final local = await _localRepo.getPrinters();
      
      // Sync with API in background
      final result = await _api.getPrinters();
      result.fold(
        (failure) => null,
        (data) => _localRepo.savePrinters(data),
      );
      
      return Right(local.isNotEmpty ? local : result.getOrElse(() => []));
    } catch (e) {
      return Left(UnexpectedFailure(e.toString()));
    }
  }
}

๐Ÿ“ก API Integration

Endpoints

  • No API endpoints (local only)

Request/Response Examples

Get List

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

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

Queries

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

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

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

// Get unsynced
final unsynced = await isar.printerLocals
    .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 PrinterPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => getIt<PrinterBloc>()..add(LoadPrinter()),
      child: Scaffold(
        appBar: AppBar(title: Text('Printer Integration')),
        body: BlocBuilder<PrinterBloc, PrinterState>(
          builder: (context, state) {
            if (state is PrinterLoading) {
              return Center(child: CircularProgressIndicator());
            }
            
            if (state is PrinterError) {
              return ErrorWidget(message: state.message);
            }
            
            if (state is PrinterLoaded) {
              return PrinterListView(items: state.items);
            }
            
            return SizedBox.shrink();
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => _navigateToCreate(context),
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

๐Ÿงช Testing

Unit Tests

void main() {
  group('PrinterBloc', () {
    late PrinterBloc bloc;
    late MockPrinterRepository mockRepository;

    setUp(() {
      mockRepository = MockPrinterRepository();
      bloc = PrinterBloc(repository: mockRepository);
    });

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

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

    blocTest<PrinterBloc, PrinterState>(
      'emits [Loading, Loaded] when Load succeeds',
      build: () {
        when(() => mockRepository.getPrinters()).thenAnswer(
          (_) async => Right([Printer(id: '1', name: 'Test')]),
        );
        return bloc;
      },
      act: (bloc) => bloc.add(LoadPrinter()),
      expect: () => [
        PrinterLoading(),
        isA<PrinterLoaded>(),
      ],
    );
  });
}

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