organization.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 =
  56. await rpc.vitalOrganization.getDynamicParameterAsync(request);
  57. return result;
  58. } catch (e) {
  59. logger.e("OrganizationManager - GetDynamicParameter error.", e);
  60. return [];
  61. }
  62. }
  63. Future<bool> _save2File(OrganizationConfigurations config) async {
  64. try {
  65. final jsonMap = config.toJson();
  66. final jsonText = jsonEncode(jsonMap);
  67. final result = await _storage.save(jsonText);
  68. return result;
  69. } catch (e) {
  70. logger.e("OrganizationManager - Save config to file error.", e);
  71. return false;
  72. }
  73. }
  74. }