organization.dart 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import 'dart:convert';
  2. import 'package:fis_common/logger/logger.dart';
  3. import 'package:fis_jsonrpc/rpc.dart';
  4. import 'package:get/get.dart';
  5. import 'package:vitalapp/architecture/storage/text_storage.dart';
  6. import 'package:vitalapp/rpc.dart';
  7. import 'package:vitalapp/store/store.dart';
  8. import 'interfaces/models/organization.dart';
  9. import 'interfaces/organization.dart';
  10. class OrganizationManager implements IOrganizationManager {
  11. static const _fileName = "organization.conf";
  12. final _storage = TextStorage(directory: "/configs", fileName: _fileName);
  13. OrganizationConfigurations? _cache;
  14. @override
  15. Future<OrganizationConfigurations> getConfigurations() async {
  16. _cache ??= await _loadConfig();
  17. return _cache ?? OrganizationConfigurations();
  18. }
  19. @override
  20. Future<OrganizationConfigurations> syncConfigurations() async {
  21. final config = OrganizationConfigurations();
  22. config.dynamicParams = await _getDynamicParams();
  23. // TODO: add other org configs
  24. await _save2File(config);
  25. _cache = config;
  26. return config;
  27. }
  28. @override
  29. Future<DynamicParameterDTO?> getDynamicParamByKey(String key) async {
  30. final config = await getConfigurations();
  31. final param = config.dynamicParams.firstWhereOrNull((e) => e.key == key);
  32. return param;
  33. }
  34. Future<OrganizationConfigurations?> _loadConfig() async {
  35. try {
  36. final jsonText = await _storage.read();
  37. if (jsonText != null) {
  38. final jsonMap = jsonDecode(jsonText);
  39. final config = OrganizationConfigurations().fromJson(jsonMap);
  40. return config;
  41. } else {
  42. return syncConfigurations();
  43. }
  44. } catch (e) {
  45. logger.e("OrganizationManager - Save config to file error.", e);
  46. return null;
  47. }
  48. }
  49. Future<List<DynamicParameterDTO>> _getDynamicParams() async {
  50. try {
  51. final request = GetDynamicParameterRequest(
  52. token: Store.user.token,
  53. organizationCode: Store.user.organizationCode,
  54. );
  55. final result = await rpc.organization.getDynamicParameterAsync(request);
  56. return result;
  57. } catch (e) {
  58. logger.e("OrganizationManager - GetDynamicParameter error.", e);
  59. return [];
  60. }
  61. }
  62. Future<bool> _save2File(OrganizationConfigurations config) async {
  63. try {
  64. final jsonMap = config.toJson();
  65. final jsonText = jsonEncode(jsonMap);
  66. final result = await _storage.save(jsonText);
  67. return result;
  68. } catch (e) {
  69. logger.e("OrganizationManager - Save config to file error.", e);
  70. return false;
  71. }
  72. }
  73. }