49 lines
1.5 KiB
Dart
49 lines
1.5 KiB
Dart
import 'dart:developer';
|
|||
|
|
|
||
|
|
import 'package:injectable/injectable.dart';
|
||
|
|
|
||
|
|
import '../../domain/unit/unit.dart';
|
||
|
|
|
||
|
|
/// Kamus satuan yang dipakai untuk menerjemahkan `unit_id` sebuah produk
|
||
|
|
/// menjadi singkatan yang dicetak di keranjang dan struk (`4,2 ons`).
|
||
|
|
///
|
||
|
|
/// Response produk hanya dijamin membawa `unit_id`; nama dan singkatannya
|
||
|
|
/// datang dari `GET /api/v1/units`. Registry ini menjembatani keduanya tanpa
|
||
|
|
/// memaksa setiap pemanggil menunggu request.
|
||
|
|
@lazySingleton
|
||
|
|
class UnitRegistry {
|
||
|
|
final IUnitRepository _repository;
|
||
|
|
final _logName = 'UnitRegistry';
|
||
|
|
|
||
|
|
Map<String, ProductUnit> _unitsById = {};
|
||
|
|
|
||
|
|
UnitRegistry(this._repository);
|
||
|
|
|
||
|
|
bool get isEmpty => _unitsById.isEmpty;
|
||
|
|
|
||
|
|
ProductUnit? byId(String? id) {
|
||
|
|
if (id == null || id.isEmpty) return null;
|
||
|
|
return _unitsById[id];
|
||
|
|
}
|
||
|
|
|
||
|
|
String abbreviationOf(String? id) => byId(id)?.abbreviation ?? '';
|
||
|
|
|
||
|
|
String nameOf(String? id) => byId(id)?.name ?? '';
|
||
|
|
|
||
|
|
/// Muat satuan ke memori. Aman dipanggil berulang; [forceRefresh] menembak
|
||
|
|
/// server ulang saat pengguna melakukan sinkronisasi manual.
|
||
|
|
Future<void> load({bool forceRefresh = false}) async {
|
||
|
|
final result = await _repository.getUnits(forceRefresh: forceRefresh);
|
||
|
|
|
||
|
|
result.fold(
|
||
|
|
(failure) => log('⚠️ Gagal memuat satuan: $failure', name: _logName),
|
||
|
|
(units) {
|
||
|
|
_unitsById = {for (final unit in units) unit.id: unit};
|
||
|
|
log('📏 ${units.length} satuan siap dipakai', name: _logName);
|
||
|
|
},
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
void clear() => _unitsById = {};
|
||
|
|
}
|