data_sync.dart 13 KB

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