data_sync.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. import 'dart:convert';
  2. import 'package:fis_jsonrpc/rpc.dart';
  3. import 'package:get/get.dart';
  4. import 'package:vital_local_database/core/interface/queryable.dart';
  5. import 'package:vitalapp/database/db.dart';
  6. import 'package:vitalapp/database/entities/defines.dart';
  7. import 'package:vitalapp/database/entities/diagnosis.dart';
  8. import 'package:vitalapp/database/entities/exam.dart';
  9. import 'package:vitalapp/database/entities/followup.dart';
  10. import 'package:vitalapp/database/entities/patient.dart';
  11. import 'package:vitalapp/managers/adapters/offline/patient.dart';
  12. import 'package:vitalapp/managers/interfaces/models/common.dart';
  13. import 'package:vitalapp/managers/interfaces/patient.dart';
  14. import 'package:vitalapp/rpc.dart';
  15. import 'package:vitalapp/store/store.dart';
  16. import 'interfaces/data_sync.dart';
  17. import 'package:fis_common/logger/logger.dart';
  18. import 'interfaces/record_data_cache.dart';
  19. class DataSyncManager implements IDataSyncManager {
  20. static const tcmKey = "HEITCMC";
  21. String get userCode => Store.user.userCode!;
  22. final _patientManager = Get.find<IPatientManager>();
  23. @override
  24. Future<PagedDataCollection<PatientEntity>> getPatientPagedList(
  25. int pageIndex, {
  26. int pageSize = 50,
  27. List<OfflineDataSyncState>? syncStates,
  28. bool isReturnCountOnly = false,
  29. }) async {
  30. try {
  31. var query = db.repositories.patient.queryable.where((x) {
  32. final list = <IDbColumnCondition>[];
  33. list.add(x.isValid.equals(true));
  34. list.add(x.userCode.equals(Store.user.userCode)); //添加用户code
  35. if (syncStates != null && syncStates.isNotEmpty) {
  36. if (syncStates.length == 1) {
  37. list.add(x.overallSyncState.equals(syncStates[0]));
  38. } else {
  39. list.add(x.overallSyncState.inEqueals(syncStates));
  40. }
  41. }
  42. return list;
  43. });
  44. List<OfflineDataSyncState> states = syncStates ?? [];
  45. if (states.isEmpty) {
  46. states.add(OfflineDataSyncState.wait);
  47. states.add(OfflineDataSyncState.fail);
  48. states.add(OfflineDataSyncState.success);
  49. }
  50. // updateTime 比 createTime 大于一秒以上,说明有操作而更新过数据
  51. final successWhere =
  52. "overallSyncState=${OfflineDataSyncState.success.index} AND julianday(updateTime) > julianday(createTime, '+1 second')";
  53. if (states.length == 1) {
  54. if (states.first == OfflineDataSyncState.success) {
  55. query = query.whereCustom(" AND $successWhere");
  56. } else {
  57. query = query.and((x) => x.overallSyncState.equals(states.first));
  58. }
  59. } else {
  60. if (states.contains(OfflineDataSyncState.success)) {
  61. final noralStateValue = states
  62. .where((e) => e != OfflineDataSyncState.success)
  63. .map((e) => e.index)
  64. .join(',');
  65. query = query.whereCustom(
  66. " AND ( overallSyncState IN ($noralStateValue) OR ( $successWhere ) ) ",
  67. );
  68. } else {
  69. query.and((x) => x.overallSyncState.inEqueals(states));
  70. }
  71. }
  72. final count = await query.count();
  73. if (isReturnCountOnly) {
  74. // 只需要返回数量
  75. return PagedDataCollection<PatientEntity>(
  76. totalCount: count,
  77. pageIndex: pageIndex,
  78. pageSize: pageSize,
  79. data: [],
  80. );
  81. }
  82. final offset = pageSize * (pageIndex - 1);
  83. final entities = await query.offset(offset).limit(pageSize).toList();
  84. return PagedDataCollection<PatientEntity>(
  85. totalCount: count,
  86. pageIndex: pageIndex,
  87. pageSize: pageSize,
  88. data: entities,
  89. );
  90. } catch (e) {
  91. logger.e("DataSyncManager getPatientPagedList error.", e);
  92. return PagedDataCollection<PatientEntity>(
  93. totalCount: 0,
  94. pageIndex: pageIndex,
  95. pageSize: pageSize,
  96. data: [],
  97. );
  98. }
  99. }
  100. @override
  101. Future<List<PatientEntity>> getPatientWaitUploadAllList() async {
  102. final waitList = await db.repositories.patient.queryable.where((x) {
  103. final list = <IDbColumnCondition>[];
  104. list.add(x.isValid.equals(true));
  105. list.add(x.userCode.equals(Store.user.userCode));
  106. list.add(x.overallSyncState.equals(OfflineDataSyncState.wait));
  107. return list;
  108. }).toList();
  109. final failList = await db.repositories.patient.queryable.where((x) {
  110. final list = <IDbColumnCondition>[];
  111. list.add(x.isValid.equals(true));
  112. list.add(x.userCode.equals(Store.user.userCode));
  113. list.add(x.overallSyncState.equals(OfflineDataSyncState.fail));
  114. return list;
  115. }).toList();
  116. // TODO: 暂时未支持 Where in ,暂时先分开查
  117. return [...waitList, ...failList];
  118. }
  119. @override
  120. Future<bool> syncPatientAllData(String patientCode) async {
  121. PatientEntity? patientEntity;
  122. try {
  123. patientEntity = await db.repositories.patient
  124. .singleByCodeWithUserCode(patientCode, Store.user.userCode!);
  125. } catch (e) {
  126. logger.e(
  127. "DataSyncManager.syncPatientAllData db.singleByCodeWithUserCode-$patientCode error.",
  128. e);
  129. }
  130. if (patientEntity == null) {
  131. return false;
  132. }
  133. bool isSyncCompleted = false;
  134. try {
  135. final patientResult = await syncPatient(patientEntity);
  136. if (patientResult) {
  137. if (patientEntity.diagnosisCount > 0) {
  138. final diagnosisSyncCount = await syncPatientDiagnosis(patientCode);
  139. patientEntity.diagnosisCount -= diagnosisSyncCount;
  140. }
  141. if (patientEntity.gxyFollowUpCount > 0) {
  142. final followUpSyncCount =
  143. await _syncPatientFollowUpWithKey(patientCode, "GXY");
  144. patientEntity.gxyFollowUpCount -= followUpSyncCount;
  145. }
  146. if (patientEntity.tnbFollowUpCount > 0) {
  147. final followUpSyncCount =
  148. await _syncPatientFollowUpWithKey(patientCode, "TNB");
  149. patientEntity.tnbFollowUpCount -= followUpSyncCount;
  150. }
  151. if (patientEntity.examCount > 0) {
  152. final count = await syncPatientExam(patientCode);
  153. // patientEntity.followUpCount -= count;
  154. }
  155. if (patientEntity.tcmConsitutionCount > 0) {
  156. final count = await syncPatientTCMConsitution(patientCode);
  157. patientEntity.tcmConsitutionCount -= count;
  158. }
  159. }
  160. isSyncCompleted = checkPatientSyncCompleted(patientEntity);
  161. if (isSyncCompleted) {
  162. patientEntity.overallSyncState = OfflineDataSyncState.success;
  163. } else {
  164. patientEntity.overallSyncState = OfflineDataSyncState.fail;
  165. }
  166. } catch (e) {
  167. logger.e(
  168. "DataSyncManager syncPatientAllData[during sync each] error.", e);
  169. // TODO: 后续可加上失败原因字段
  170. patientEntity.overallSyncState = OfflineDataSyncState.fail;
  171. return false;
  172. }
  173. // 更新居民记录
  174. try {
  175. final ret = await db.repositories.patient.update(patientEntity);
  176. return isSyncCompleted && ret > 0;
  177. } catch (e) {
  178. logger.e(
  179. "DataSyncManager syncPatientAllData[during update overall state] error.",
  180. e);
  181. return false;
  182. }
  183. }
  184. @override
  185. bool checkPatientSyncCompleted(PatientEntity entity) {
  186. if (entity.examCount > 0) return false;
  187. if (entity.tcmConsitutionCount > 0) return false;
  188. if (entity.diagnosisCount > 0) return false;
  189. if (entity.gxyFollowUpCount > 0) return false;
  190. if (entity.tnbFollowUpCount > 0) return false;
  191. if (entity.syncState != OfflineDataSyncState.success) return false;
  192. return true;
  193. }
  194. @override
  195. Future<bool> syncPatient(PatientEntity entity) async {
  196. logger.i("DataSyncManager start sync patient info...");
  197. logger.i("Patient info: ${entity.name}|${entity.code}.");
  198. bool syncResult = false;
  199. try {
  200. final jsonMap = jsonDecode(entity.dataJson);
  201. final dto = PatientDTO.fromJson(jsonMap);
  202. if (entity.syncType == OfflineDataSyncType.create) {
  203. final request = PatientDtoConverter.dto2Create(dto);
  204. request.token = Store.user.token;
  205. final code = await rpc.vitalPatient.createPatientAsync(request);
  206. syncResult = code.isNotEmpty;
  207. if (syncResult) {
  208. entity.code = code;
  209. }
  210. } else {
  211. final request = PatientDtoConverter.dto2Update(dto);
  212. request.token = Store.user.token;
  213. syncResult = await rpc.patient.updatePatientAsync(request);
  214. }
  215. if (syncResult) {
  216. syncResult = await _syncPatientExt(entity);
  217. if (!syncResult) {
  218. logger.i("DataSyncManager sync patient ext info fail.");
  219. }
  220. } else {
  221. logger.i("DataSyncManager sync patient base info fail.");
  222. }
  223. entity.syncState =
  224. syncResult ? OfflineDataSyncState.success : OfflineDataSyncState.fail;
  225. await db.repositories.patient.update(entity);
  226. } catch (e) {
  227. logger.e("DataSyncManager sync patient error.", e);
  228. syncResult = false;
  229. }
  230. logger.i("DataSyncManager stop sync patient info.");
  231. return syncResult;
  232. }
  233. @override
  234. Future<int> syncPatientDiagnosis(String patientCode) async {
  235. logger.i("DataSyncManager start sync diagnosis...");
  236. final list = await db.repositories.diagnosis
  237. .getNotUploadedListByPatientCode(patientCode, userCode);
  238. logger.i("DataSyncManager diagnosis total count: ${list.length}.");
  239. int count = 0;
  240. try {
  241. for (var entity in list) {
  242. final success = await _syncSingleDiagnosis(entity);
  243. if (success) {
  244. count++;
  245. }
  246. }
  247. } catch (e) {
  248. logger.e("DataSyncManager sync diagnosis error.", e);
  249. }
  250. logger.i("DataSyncManager stop sync diagnosis; uploaded count: $count.");
  251. return count;
  252. }
  253. @override
  254. Future<int> syncPatientFollowUp(String patientCode) async {
  255. logger.i("DataSyncManager start sync followup...");
  256. final list = await db.repositories.followUp
  257. .queryAllListByPatient(patientCode, userCode);
  258. logger.i("DataSyncManager followup total count: ${list.length}.");
  259. int count = 0;
  260. try {
  261. for (var entity in list) {
  262. final success = await _syncSingleFollowUp(entity);
  263. if (success) {
  264. count++;
  265. }
  266. }
  267. } catch (e) {
  268. logger.e("DataSyncManager sync followup error.", e);
  269. }
  270. logger.i("DataSyncManager stop sync followup; uploaded count: $count.");
  271. return count;
  272. }
  273. @override
  274. Future<int> syncPatientExam(String patientCode) async {
  275. logger.i("DataSyncManager start sync exam...");
  276. final list = await db.repositories.exam.queryPatientAllList(
  277. patientCode, userCode,
  278. keys: ["Unset"]); //TODO: 这里请指定Key集合
  279. logger.i("DataSyncManager exam total count: ${list.length}.");
  280. int count = 0;
  281. try {
  282. for (var entity in list) {
  283. final success = await _syncSingleExam(entity);
  284. if (success) {
  285. count++;
  286. }
  287. }
  288. } catch (e) {
  289. logger.e("DataSyncManager sync exam error.", e);
  290. }
  291. logger.i("DataSyncManager stop sync exam; uploaded count: $count.");
  292. return count;
  293. }
  294. @override
  295. Future<int> syncPatientTCMConsitution(String patientCode) async {
  296. logger.i("DataSyncManager start sync TCMConsitution...");
  297. final list = await db.repositories.exam
  298. .queryPatientAllList(patientCode, userCode, keys: [tcmKey]);
  299. logger.i("DataSyncManager TCMConsitution total count: ${list.length}.");
  300. int count = 0;
  301. try {
  302. for (var entity in list) {
  303. final success = await _syncSingleExam(entity);
  304. if (success) {
  305. count++;
  306. }
  307. }
  308. } catch (e) {
  309. logger.e("DataSyncManager sync TCMConsitution error.", e);
  310. }
  311. logger
  312. .i("DataSyncManager stop sync TCMConsitution; uploaded count: $count.");
  313. return count;
  314. }
  315. Future<int> _syncPatientFollowUpWithKey(
  316. String patientCode, String key) async {
  317. logger.i("DataSyncManager start sync followup...");
  318. final list = await db.repositories.followUp
  319. .queryAllListByPatient(patientCode, userCode, key);
  320. logger.i("DataSyncManager followup total count: ${list.length}.");
  321. int count = 0;
  322. try {
  323. for (var entity in list) {
  324. final success = await _syncSingleFollowUp(entity);
  325. if (success) {
  326. count++;
  327. }
  328. }
  329. } catch (e) {
  330. logger.e("DataSyncManager sync followup error.", e);
  331. }
  332. logger.i("DataSyncManager stop sync followup; uploaded count: $count.");
  333. return count;
  334. }
  335. Future<bool> _syncSingleFollowUp(FollowUpEntity entity) async {
  336. bool result = false;
  337. try {
  338. if (entity.syncType == OfflineDataSyncType.create) {
  339. final request = CreateFollowUpRequest(
  340. token: Store.user.token,
  341. key: entity.typeKey,
  342. patientCode: entity.patientCode,
  343. templateCode: entity.templateCode,
  344. followUpData: entity.dataJson,
  345. followUpTime: entity.followUpTime,
  346. nextFollowUpTime: entity.nextFollowUpTime,
  347. followUpMode: entity.mode,
  348. followUpPhotos: entity.followUpPhtots,
  349. );
  350. final code = await rpc.vitalFollowUp.createFollowUpAsync(request);
  351. result = code.isNotEmpty;
  352. if (result) {
  353. entity.code = code; // 更新真实Code
  354. }
  355. } else {
  356. final request = UpdateFollowUpRequest(
  357. token: Store.user.token,
  358. key: entity.typeKey,
  359. followUpData: entity.dataJson,
  360. followUpTime: entity.followUpTime,
  361. nextFollowUpTime: entity.nextFollowUpTime,
  362. followUpMode: entity.mode,
  363. code: entity.code,
  364. followUpPhotos: entity.followUpPhtots,
  365. );
  366. result = await rpc.vitalFollowUp.updateFollowUpAsync(request);
  367. }
  368. if (result) {
  369. entity.syncState = OfflineDataSyncState.success;
  370. } else {
  371. entity.syncState = OfflineDataSyncState.fail;
  372. }
  373. final updateRows = await db.repositories.followUp.update(entity);
  374. result = updateRows > 0;
  375. } catch (e) {
  376. logger.e(
  377. "DataSyncManager_syncSingleFollowUp error. id: ${entity.id}.", e);
  378. }
  379. return result;
  380. }
  381. /// 根据身份证号获取居民信息
  382. Future<PatientDTO?> _getPatientByID(String idNum,
  383. [bool isValidOperationDoctor = true]) async {
  384. final patient = await _patientManager.getDetail(
  385. idNum,
  386. isValidOperationDoctor: isValidOperationDoctor,
  387. );
  388. return patient;
  389. }
  390. Future<bool> _syncSingleDiagnosis(DiagnosisEntity entity) async {
  391. final currPatient = await _getPatientByID(entity.patientCode);
  392. if (currPatient == null) {
  393. return false;
  394. }
  395. bool result = false;
  396. try {
  397. final valuesMap = jsonDecode(entity.dataJson);
  398. List<DiagnosisItem> diagnosisItems =
  399. await Get.find<IRecordDataCacheManager>()
  400. .verifyDiagnosisDataList(valuesMap);
  401. // 目前不存在更新
  402. final request = SyncPatientAndDiagnosisDataRequest(
  403. token: Store.user.token,
  404. patientCode: currPatient.code,
  405. patientName: currPatient.patientName ?? '',
  406. patientAddress: currPatient.patientAddress ?? '',
  407. patientGender: currPatient.patientGender,
  408. permanentResidenceAddress: currPatient.permanentResidenceAddress,
  409. phone: currPatient.phone,
  410. cardNo: currPatient.cardNo,
  411. nationality: currPatient.nationality,
  412. birthday: currPatient.birthday,
  413. crowdLabels: currPatient.crowdLabels,
  414. cardType: currPatient.cardType,
  415. contractedDoctor: currPatient.contractedDoctor,
  416. appDataId: entity.code,
  417. diagnosisTime: DateTime.now(),
  418. diagnosisItems: diagnosisItems,
  419. );
  420. result =
  421. await rpc.vitalDiagnosis.syncPatientAndDiagnosisDataAsync(request);
  422. if (result) {
  423. entity.syncState = OfflineDataSyncState.success;
  424. } else {
  425. entity.syncState = OfflineDataSyncState.fail;
  426. }
  427. final updateRows = await db.repositories.diagnosis.update(entity);
  428. result = updateRows > 0;
  429. } catch (e) {
  430. logger.e(
  431. "DataSyncManager_syncSingleDiagnosis error. id: ${entity.id}.", e);
  432. }
  433. return result;
  434. }
  435. Future<bool> _syncSingleExam(ExamEntity entity) async {
  436. bool result = false;
  437. try {
  438. if (entity.syncType == OfflineDataSyncType.create) {
  439. final code = await _createExam(entity);
  440. result = code.isNotEmpty;
  441. if (result) {
  442. entity.code = code; // 更新真实Code
  443. }
  444. } else {
  445. result = await _updateExam(entity);
  446. }
  447. if (result) {
  448. entity.syncState = OfflineDataSyncState.success;
  449. } else {
  450. entity.syncState = OfflineDataSyncState.fail;
  451. }
  452. final updateRows = await db.repositories.exam.update(entity);
  453. result = updateRows > 0;
  454. } catch (e) {
  455. logger.e("DataSyncManager_syncSingleExam error. id: ${entity.id}.", e);
  456. }
  457. return result;
  458. }
  459. Future<String> _createExam(ExamEntity entity) async {
  460. final code = entity.code.startsWith("mock") ? null : entity.code;
  461. final request = CreateExamRequest(
  462. code: code,
  463. batchNumber: entity.batchNumber,
  464. key: entity.templateKey,
  465. patientCode: entity.patientCode,
  466. examData: entity.dataJson,
  467. templateCode: entity.templateCode,
  468. physicalExamNumber: "",
  469. token: Store.user.token,
  470. );
  471. final result = await rpc.vitalExam.createExamAsync(request);
  472. return result;
  473. }
  474. Future<bool> _updateExam(ExamEntity entity) async {
  475. // 中医体质 和 普通体检 更新通道不同
  476. if (entity.templateKey == tcmKey) {
  477. final request = UpdateExamRequest(
  478. token: Store.user.token,
  479. key: entity.templateKey,
  480. examData: entity.dataJson,
  481. code: entity.code,
  482. );
  483. final result = await rpc.vitalExam.updateExamAsync(request);
  484. return result;
  485. } else {
  486. final code = await _createExam(entity);
  487. return code.isNotEmpty;
  488. }
  489. }
  490. Future<bool> _syncPatientExt(PatientEntity entity) async {
  491. if (entity.extJson == null || entity.extJson!.isEmpty) {
  492. return true;
  493. }
  494. if (entity.extCode == null || entity.extCode!.startsWith("mock")) {
  495. final extCode =
  496. await rpc.vitalPatientExtension.createPatientExtensionAsync(
  497. CreatePatientExtensionRequest(
  498. token: Store.user.token,
  499. key: "PatientHealthInfo",
  500. patientCode: entity.code,
  501. extensionData: entity.extJson,
  502. ),
  503. );
  504. if (extCode.isNotEmpty) {
  505. entity.extCode = extCode;
  506. return true;
  507. } else {
  508. return false;
  509. }
  510. } else {
  511. final result =
  512. await rpc.vitalPatientExtension.updatePatientExtensionAsync(
  513. UpdatePatientExtensionRequest(
  514. code: entity.extCode,
  515. token: Store.user.token,
  516. key: "PatientHealthInfo",
  517. patientCode: entity.code,
  518. extensionData: entity.extJson,
  519. ),
  520. );
  521. return result;
  522. }
  523. }
  524. }