data_sync.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import 'dart:convert';
  2. import 'package:fis_jsonrpc/rpc.dart';
  3. import 'package:get/get.dart';
  4. import 'package:uuid/uuid.dart';
  5. import 'package:vital_local_database/core/interface/queryable.dart';
  6. import 'package:vitalapp/architecture/storage/text_storage.dart';
  7. import 'package:vitalapp/database/db.dart';
  8. import 'package:vitalapp/database/entities/defines.dart';
  9. import 'package:vitalapp/database/entities/diagnosis.dart';
  10. import 'package:vitalapp/database/entities/followup.dart';
  11. import 'package:vitalapp/database/entities/patient.dart';
  12. import 'package:vitalapp/managers/adapters/offline/patient.dart';
  13. import 'package:vitalapp/managers/interfaces/models/common.dart';
  14. import 'package:vitalapp/managers/interfaces/models/data_sync.dart';
  15. import 'package:vitalapp/rpc.dart';
  16. import 'package:vitalapp/store/store.dart';
  17. import 'interfaces/data_sync.dart';
  18. import 'package:fis_common/logger/logger.dart';
  19. import 'interfaces/record_data_cache.dart';
  20. class DataSyncManager implements IDataSyncManager {
  21. String get userCode => Store.user.userCode!;
  22. @override
  23. Future<PagedDataCollection<PatientEntity>> getPatientPagedList(
  24. int pageIndex, {
  25. int pageSize = 50,
  26. List<OfflineDataSyncState>? syncStates,
  27. }) async {
  28. try {
  29. final query = db.repositories.patient.queryable.where((x) {
  30. final list = <IDbColumnCondition>[];
  31. list.add(x.isValid.equals(true));
  32. list.add(x.userCode.equals(Store.user.userCode)); //添加用户code
  33. if (syncStates != null && syncStates.isNotEmpty) {
  34. if (syncStates.length == 1) {
  35. list.add(x.overallSyncState.equals(syncStates[0]));
  36. } else {
  37. list.add(x.overallSyncState.inEqueals(syncStates));
  38. }
  39. }
  40. return list;
  41. });
  42. final count = await query.count();
  43. final offset = pageSize * (pageIndex - 1);
  44. final entities = await query.offset(offset).limit(pageSize).toList();
  45. return PagedDataCollection<PatientEntity>(
  46. totalCount: count,
  47. pageIndex: pageIndex,
  48. pageSize: pageSize,
  49. data: entities,
  50. );
  51. } catch (e) {
  52. logger.e("DataSyncManager getPatientPagedList error.", e);
  53. return PagedDataCollection<PatientEntity>(
  54. totalCount: 0,
  55. pageIndex: pageIndex,
  56. pageSize: pageSize,
  57. data: [],
  58. );
  59. }
  60. }
  61. @override
  62. Future<List<PatientEntity>> getPatientWaitUploadAllList() async {
  63. final waitList = await db.repositories.patient.queryable.where((x) {
  64. final list = <IDbColumnCondition>[];
  65. list.add(x.isValid.equals(true));
  66. list.add(x.userCode.equals(Store.user.userCode));
  67. list.add(x.overallSyncState.equals(OfflineDataSyncState.wait));
  68. return list;
  69. }).toList();
  70. final failList = await db.repositories.patient.queryable.where((x) {
  71. final list = <IDbColumnCondition>[];
  72. list.add(x.isValid.equals(true));
  73. list.add(x.userCode.equals(Store.user.userCode));
  74. list.add(x.overallSyncState.equals(OfflineDataSyncState.fail));
  75. return list;
  76. }).toList();
  77. // TODO: 暂时未支持 Where in ,暂时先分开查
  78. return [...waitList, ...failList];
  79. }
  80. @override
  81. Future<bool> syncPatientAllData(String patientCode) async {
  82. // TODO: 后续加上事务支持
  83. final patientEntity =
  84. await db.repositories.patient.singleByCode(patientCode);
  85. if (patientEntity == null) {
  86. return false;
  87. }
  88. bool isSyncCompleted = false;
  89. try {
  90. final patientResult = await syncPatient(patientEntity);
  91. if (!patientResult) {
  92. return false;
  93. }
  94. if (patientEntity.diagnosisCount > 0) {
  95. final diagnosisSyncCount = await syncPatientDiagnosis(patientCode);
  96. patientEntity.diagnosisCount -= diagnosisSyncCount;
  97. }
  98. if (patientEntity.followUpCount > 0) {
  99. final followUpSyncCount = await syncPatientFollowUp(patientCode);
  100. patientEntity.followUpCount -= followUpSyncCount;
  101. }
  102. isSyncCompleted = _checkPatientSyncCompleted(patientEntity);
  103. if (isSyncCompleted) {
  104. patientEntity.overallSyncState = OfflineDataSyncState.success;
  105. } else {
  106. patientEntity.overallSyncState = OfflineDataSyncState.fail;
  107. }
  108. } catch (e) {
  109. logger.e(
  110. "DataSyncManager syncPatientAllData[during sync each] error.", e);
  111. // TODO: 后续可加上失败原因字段
  112. patientEntity.overallSyncState = OfflineDataSyncState.fail;
  113. return false;
  114. }
  115. // 更新居民记录
  116. try {
  117. final ret = await db.repositories.patient.update(patientEntity);
  118. return isSyncCompleted && ret > 0;
  119. } catch (e) {
  120. logger.e(
  121. "DataSyncManager syncPatientAllData[during update overall state] error.",
  122. e);
  123. return false;
  124. }
  125. }
  126. /// 校验同步是否完成
  127. bool _checkPatientSyncCompleted(PatientEntity entity) {
  128. if (entity.examCount > 0) return false;
  129. if (entity.diagnosisCount > 0) return false;
  130. if (entity.followUpCount > 0) return false;
  131. if (entity.syncState != OfflineDataSyncState.success) return false;
  132. return true;
  133. }
  134. @override
  135. Future<bool> syncPatient(PatientEntity entity) async {
  136. try {
  137. final jsonMap = jsonDecode(entity.dataJson);
  138. final dto = PatientDTO.fromJson(jsonMap);
  139. bool syncResult = false;
  140. if (entity.syncType == OfflineDataSyncType.create) {
  141. final request = PatientDtoConverter.dto2Create(dto);
  142. request.token = Store.user.token;
  143. final code = await rpc.patient.createPatientAsync(request);
  144. syncResult = code.isNotEmpty;
  145. } else {
  146. final request = PatientDtoConverter.dto2Update(dto);
  147. request.token = Store.user.token;
  148. syncResult = await rpc.patient.updatePatientAsync(request);
  149. }
  150. entity.syncState =
  151. syncResult ? OfflineDataSyncState.success : OfflineDataSyncState.fail;
  152. await db.repositories.patient.update(entity);
  153. return syncResult;
  154. } catch (e) {
  155. logger.e("DataSyncManager syncPatient error.", e);
  156. return false;
  157. }
  158. }
  159. @override
  160. Future<int> syncPatientDiagnosis(String patientCode) async {
  161. final list = await db.repositories.diagnosis
  162. .getNotUploadedListByPatientCode(patientCode, userCode);
  163. int count = 0;
  164. final appDataId = await _getDiagnosisAppDataId(patientCode);
  165. for (var entity in list) {
  166. final success = await _syncSingleDiagnosis(appDataId, entity);
  167. if (success) {
  168. count++;
  169. }
  170. }
  171. return count;
  172. }
  173. @override
  174. Future<int> syncPatientFollowUp(String patientCode) async {
  175. final list = await db.repositories.followUp
  176. .queryAllListByPatient(patientCode, userCode);
  177. int count = 0;
  178. for (var entity in list) {
  179. final success = await _syncSingleFollowUp(entity);
  180. if (success) {
  181. count++;
  182. }
  183. }
  184. return count;
  185. }
  186. @override
  187. Future<PagedDataCollection<OfflineRecordModel>> getOfflinePagedList(
  188. int pageIndex, {
  189. int pageSize = 50,
  190. List<OfflineDataSyncState>? syncStates,
  191. }) async {
  192. final patientCode = Store.user.currentSelectPatientInfo!.code!;
  193. final userCode = Store.user.userCode!;
  194. final sql = _getListQuerySql(patientCode, userCode, states: []);
  195. final dbList = await db.database.query(sql);
  196. // if(dbList.isEmpty){
  197. // return
  198. // }
  199. return PagedDataCollection<OfflineRecordModel>(
  200. totalCount: 0,
  201. pageIndex: pageIndex,
  202. pageSize: pageSize,
  203. data: [],
  204. );
  205. }
  206. @override
  207. Future<List<OfflineRecordModel>> getOfflineList({
  208. List<OfflineDataSyncState>? syncStates,
  209. }) async {
  210. final patientCode = Store.user.currentSelectPatientInfo!.code!;
  211. final userCode = Store.user.userCode!;
  212. final sql =
  213. _getListQuerySql(patientCode, userCode, states: syncStates ?? []);
  214. final dbList = await db.database.query(sql);
  215. if (dbList.isEmpty) {
  216. return [];
  217. }
  218. final models = dbList.map((e) => OfflineRecordModel.fromJson(e)).toList();
  219. return models;
  220. }
  221. String _getListQuerySql(
  222. String patientCode,
  223. String userCode, {
  224. List<OfflineDataSyncState>? states,
  225. }) {
  226. final sb = StringBuffer();
  227. sb.write('SELECT p.* ');
  228. sb.write(',COUNT(d.id) AS diagnosisCount ');
  229. sb.write(',COUNT(f.id) AS followupCount ');
  230. sb.writeln('FROM patients p ');
  231. // 联表 - 健康检测
  232. sb.writeln('Left JOIN diagnosis d ON p.code = d.patientCode ');
  233. sb.writeln('AND d.isValid =1 AND d.userCode="$userCode" ');
  234. if (states != null && states.isNotEmpty) {
  235. _buildStatesSql(states, "d");
  236. }
  237. // 联表 - 随访
  238. sb.writeln('Left JOIN followup f ON p.code = f.patientCode');
  239. sb.writeln('AND f.isValid =1 AND f.userCode="$userCode" ');
  240. if (states != null && states.isNotEmpty) {
  241. _buildStatesSql(states, "f");
  242. }
  243. sb.writeln('WHERE 1=1 p.isValid=1 ');
  244. sb.writeln('AND p.code="$patientCode" AND p.userCode="$userCode" ');
  245. if (states != null && states.isNotEmpty) {
  246. _buildStatesSql(states, "p");
  247. }
  248. // 根据档案维度分组
  249. sb.writeln('GROUP BY p.code');
  250. //'HAVING p.syncState=0 OR diagnosisCount>0 OR followupCount>0'
  251. sb.writeln(
  252. 'ORDER BY p.createTime DESC, d.createTime DESC,f.createTime DESC');
  253. sb.writeln(';');
  254. return sb.toString();
  255. }
  256. static String _buildStatesSql(
  257. List<OfflineDataSyncState> states, String alias) {
  258. if (alias.length == 1) {
  259. return "AND f.syncState=${states[0].index} ";
  260. }
  261. final sb = StringBuffer("AND ( ");
  262. for (var i = 0; i < states.length; i++) {
  263. final val = states[i].index;
  264. if (i == 0) {
  265. sb.writeln("$alias.syncState=$val ");
  266. } else {
  267. sb.writeln("OR $alias.syncState=$val ");
  268. }
  269. }
  270. sb.writeln(") ");
  271. return sb.toString();
  272. }
  273. Future<bool> _syncSingleFollowUp(FollowUpEntity entity) async {
  274. bool result = false;
  275. try {
  276. if (entity.syncType == OfflineDataSyncType.create) {
  277. final request = CreateFollowUpRequest(
  278. token: Store.user.token,
  279. key: entity.typeKey,
  280. patientCode: entity.patientCode,
  281. templateCode: entity.templateCode,
  282. followUpData: entity.dataJson,
  283. followUpTime: entity.followUpTime,
  284. nextFollowUpTime: entity.nextFollowUpTime,
  285. followUpMode: entity.mode,
  286. followUpPhotos: entity.followUpPhtots,
  287. );
  288. final code = await rpc.vitalFollowUp.createFollowUpAsync(request);
  289. result = code.isNotEmpty;
  290. if (result) {
  291. entity.code = code; // 更新真实Code
  292. }
  293. } else {
  294. final request = UpdateFollowUpRequest(
  295. token: Store.user.token,
  296. key: entity.typeKey,
  297. followUpData: entity.dataJson,
  298. followUpTime: entity.followUpTime,
  299. nextFollowUpTime: entity.nextFollowUpTime,
  300. followUpMode: entity.mode,
  301. code: entity.code,
  302. followUpPhotos: entity.followUpPhtots,
  303. );
  304. result = await rpc.vitalFollowUp.updateFollowUpAsync(request);
  305. }
  306. if (result) {
  307. entity.syncState = OfflineDataSyncState.success;
  308. } else {
  309. entity.syncState = OfflineDataSyncState.fail;
  310. }
  311. final updateRows = await db.repositories.followUp.update(entity);
  312. result = updateRows > 0;
  313. } catch (e) {
  314. logger.e(
  315. "DataSyncManager_syncSingleFollowUp error. id: ${entity.id}.", e);
  316. }
  317. return result;
  318. }
  319. Future<bool> _syncSingleDiagnosis(
  320. String appDataId, DiagnosisEntity entity) async {
  321. final currPatient = Store.user.currentSelectPatientInfo;
  322. if (currPatient == null) {
  323. return false;
  324. }
  325. bool result = false;
  326. try {
  327. final valuesMap = jsonDecode(entity.dataJson);
  328. List<DiagnosisItem> diagnosisItems =
  329. await Get.find<IRecordDataCacheManager>()
  330. .verifyDiagnosisDataList(valuesMap);
  331. // 目前不存在更新
  332. final request = SyncPatientAndDiagnosisDataRequest(
  333. token: Store.user.token,
  334. patientCode: currPatient.code,
  335. patientName: currPatient.patientName ?? '',
  336. patientAddress: currPatient.patientAddress ?? '',
  337. patientGender: currPatient.patientGender,
  338. permanentResidenceAddress: currPatient.permanentResidenceAddress,
  339. phone: currPatient.phone,
  340. cardNo: currPatient.cardNo,
  341. nationality: currPatient.nationality,
  342. birthday: currPatient.birthday,
  343. crowdLabels: currPatient.crowdLabels,
  344. cardType: currPatient.cardType,
  345. contractedDoctor: currPatient.contractedDoctor,
  346. appDataId: appDataId,
  347. diagnosisTime: DateTime.now(),
  348. diagnosisItems: diagnosisItems,
  349. );
  350. result =
  351. await rpc.vitalDiagnosis.syncPatientAndDiagnosisDataAsync(request);
  352. if (result) {
  353. entity.syncState = OfflineDataSyncState.success;
  354. } else {
  355. entity.syncState = OfflineDataSyncState.fail;
  356. }
  357. final updateRows = await db.repositories.diagnosis.update(entity);
  358. result = updateRows > 0;
  359. } catch (e) {
  360. logger.e(
  361. "DataSyncManager_syncSingleDiagnosis error. id: ${entity.id}.", e);
  362. }
  363. return result;
  364. }
  365. Future<String> _getDiagnosisAppDataId(String patientCode) async {
  366. // TODO 待封装
  367. TextStorage cachedRecord = TextStorage(
  368. fileName: 'appDataId',
  369. directory: "patient/$patientCode",
  370. );
  371. String? appDataId = await cachedRecord.read();
  372. appDataId ??= const Uuid().v4().replaceAll('-', '');
  373. return appDataId;
  374. }
  375. }