package com.hx.phip.his.service.impl; import com.alibaba.fastjson.JSON; import com.hx.exception.ServiceException; import com.hx.mybatisTool.SqlSentence; import com.hx.phiappt.model.*; import com.hx.phiappt.model.cardItem.CardEquity; import com.hx.phiappt.model.cardItem.CardItem; import com.hx.phiappt.model.cardItem.CardItemInfo; import com.hx.phiappt.model.consumables.Consumables; import com.hx.phiappt.model.consumables.ConsumablesType; import com.hx.phiappt.model.limit.LimitOther; import com.hx.phiappt.model.limit.LimitTotal; import com.hx.phiappt.model.limit.MemberLimit; import com.hx.phiappt.model.memberLevel.MemberLevel; import com.hx.phiappt.model.project.*; import com.hx.phiappt.model.promotion.Promotion; import com.hx.phiappt.model.promotion.PromotionInfo; import com.hx.phiappt.model.specification.Specification; import com.hx.phiappt.model.specification.SpecificationValue; import com.hx.phip.common.HisUrl; import com.hx.phip.his.config.SystemConfig; import com.hx.phiappt.dao.mapper.*; import com.hx.phip.dao.mapper.syn.SyncProjectRecordMapper; import com.hx.phip.model.SyncProjectRecord; import com.hx.phip.his.service.GetTokenService; import com.hx.phip.his.service.SyncProjectTreeService; import com.hx.phip.his.service.SyncTransactioalService; import com.hx.phip.uti.ApiUtil; import com.hx.phip.uti.CreateNo; import com.hx.phip.uti.HisHttpUtil; import com.hx.resultTool.ResponseCode; import com.hx.resultTool.Result; import com.hx.util.DateUtil; import com.hx.util.StringUtils; import com.mongodb.BasicDBObject; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.SimpleDateFormat; import java.util.*; @Transactional @Service public class SyncProjectServiceImpl implements SyncProjectTreeService { private static Logger logger = LoggerFactory.getLogger(SyncProjectServiceImpl.class); @Resource private SystemParameterMapper systemParameterMapper; @Resource private SystemConfig systemConfig; @Resource private ProjectTypeMapper projectTypeMapper; @Resource private ProjectMapper projectMapper; @Resource private BodyPartsMapper bodyPartsMapper; @Resource private ProjectInfoMapper projectInfoMapper; @Resource private ProjectAndTypeMapper projectAndTypeMapper; // @Autowired private MongoTemplate mongoTemplate; @Autowired private CardItemMapper cardItemMapper; @Autowired private MemberLevelMapper memberLevelMapper; @Autowired private PromotionMapper promotionMapper; @Autowired private PromotionInfoMapper promotionInfoMapper; @Resource private ConsumablesMapper consumablesMapper; @Resource private LimitTotalMapper limitTotalMapper; @Resource private LimitOtherMapper limitOtherMapper; @Autowired private MemberLimitMapper memberLimitMapper; @Resource private ShopMapper shopMapper; @Resource private CardEquityMapper cardEquityMapper; @Resource private CardItemInfoMapper cardItemInfoMapper; @Resource private ConsumablesTypeMapper consumablesTypeMapper; @Resource private PaymentMethodMapper paymentMethodMapper; @Resource private SyncTransactioalService syncTransactioalService; @Resource private ProjectGeneralMapper projectGeneralMapper; @Resource private SpecificationMapper specificationMapper; @Resource private SpecificationValueMapper specificationValueMapper; @Resource private ProjectGenSpecMapper projectGenSpecMapper; @Resource private ProjectSpecValueMapper projectSpecValueMapper; @Resource private GetTokenService getTokenService; @Resource private ProjectAndConsumablesMapper projectAndConsumablesMapper; @Resource private EmployeeRoleTypeMapper employeeRoleTypeMapper; @Autowired private DeviceMapper deviceMapper; @Autowired private ProjectLaborCostMapper projectLaborCostMapper; @Autowired private ProjectDeviceParameterMapper projectDeviceParameterMapper; @Autowired private DeviceParameterMapper deviceParameterMapper; @Resource private FamiliesRoomMapper familiesRoomMapper; /** * 获取HIS token * * @return */ public String getToken() { //获取 领健 token String at = getTokenService.getHisToken(systemParameterMapper, systemConfig.getApiAppId(), systemConfig.getApiCode(), systemConfig.getApiSecret(), systemConfig.getApiUrl()); return at; } /** * 同步项目树状结构 */ @Override public void categoryServiceTree(SyncProjectRecord syncProjectRecord) { syncProjectRecord.setStartTime(new Date()); String at = getToken(); Map header = new HashMap<>(); header.put("x-access-token", at); String result = HisHttpUtil.HttpURLUtilJson(systemConfig.getApiUrl() + HisUrl.CATALOG_CATEGORY_SERVICE_TREE, null, null, header, "GET"); if (!StringUtils.isEmpty(result)) { JSONArray objects = JSONArray.fromObject(result); if (objects != null) { for (int i = 0; i < objects.size(); i++) { try { handleProjectType(objects.getJSONObject(i)); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); }catch (Exception e){ syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); logger.error("同步商品分类出错了:" + objects.getJSONObject(i)); } } } } else { logger.info("his接口错误,返回:{}", result); throw new ServiceException("his接口错误"); } syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); } public void handleProjectType( JSONObject jsonObject){ String id = jsonObject.getString("id");//顶级项目类别id String name = jsonObject.getString("name");//顶级项目类别名称 String code = jsonObject.getString("code"); JSONArray children = jsonObject.getJSONArray("children"); SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from project_type where apiId = #{m.id} and isDel = 0 "); map.put("isDel", BaseEntity.NO); map.put("id", id); map.put("name", name); ProjectType pt = projectTypeMapper.selectOne(sqlSentence); if (pt == null) { pt=new ProjectType(); pt.setName(name); pt.setOrderNum(BaseEntity.YES); pt.setIsUp(BaseEntity.YES); pt.setNoApptDay(null); pt.setIsDel(BaseEntity.NO); pt.setIsShow(BaseEntity.YES); pt.setApiId(id); pt.setApiCode(code); projectTypeMapper.insert(pt); } else { pt.setName(name); pt.setApiId(id); pt.setApiCode(code); pt.setEditTime(new Date()); projectTypeMapper.updateAll(pt); } if (children != null && pt != null) { operationChildren(children, 2, pt.getId()); } } /** * 处理树状结构子类结构 */ public synchronized void operationChildren(JSONArray childrens, int level, String parentId) { if (childrens != null) { JSONObject jsonObject = null; String id = null; String name = null; String code = null; SqlSentence sqlSentence = null; Map map = null; ProjectType pt = null; for (int i = 0; i < childrens.size(); i++) { jsonObject = childrens.getJSONObject(i); id = jsonObject.getString("id");//顶级项目类别id name = jsonObject.getString("name");//顶级项目类别名称 code = jsonObject.getString("code"); JSONArray children = jsonObject.getJSONArray("children"); sqlSentence = new SqlSentence(); map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from project_type where apiId = #{m.id} and isDel = 0 "); map.put("isDel", BaseEntity.NO); map.put("id", id); map.put("name", name); pt = projectTypeMapper.selectOne(sqlSentence); if (pt == null) { pt = new ProjectType(); pt.setName(name); pt.setOrderNum(BaseEntity.YES); pt.setIsUp(BaseEntity.YES); pt.setNoApptDay(null); pt.setIsDel(BaseEntity.NO); pt.setIsShow(BaseEntity.YES); pt.setLevel(level); pt.setParentId(parentId); pt.setApiId(id); pt.setApiCode(code); projectTypeMapper.insert(pt); } else { pt.setName(name); pt.setApiId(id); pt.setApiCode(code); pt.setParentId(parentId); pt.setEditTime(new Date()); projectTypeMapper.updateAll(pt); } //处理子类 if (children != null && children.size() > 0) { operationChildren(children, level + 1, pt.getId()); } } } } /** * 新增项目分类 * @param jsonObject * @return */ @Override public Result addServiceTree(BasicDBObject jsonObject) { logger.info("新增项目分类入参:{}",jsonObject.toString()); SyncProjectRecord syncProjectRecord=new SyncProjectRecord(3,1,0,0); syncProjectRecord.setOperationType(1); syncProjectRecord.setStartTime(new Date()); syncProjectRecord.setRequestParameters(JSON.toJSONString(jsonObject)); jsonObject.put("_id",UUID.randomUUID().toString()); jsonObject.put("code",jsonObject.getString("_id")); jsonObject.put("group","care-service"); JSONObject metadata=new JSONObject(); metadata.put("tenantId","0001"); metadata.put("version",1); metadata.put("state",1); jsonObject.put("metadata",metadata); jsonObject.put("_class","cn.linkedcare.charites.core.types.CareServiceCategory"); Query query = new Query(); Criteria criteria=new Criteria(); if(jsonObject.get("parentId")==null){ criteria.and("parentId").is(new BasicDBObject("$exists", false)); criteria.and("name").is(jsonObject.get("name")); }else { criteria.and("parentId").is(jsonObject.get("parentId")); criteria.and("name").is(jsonObject.get("name")); } query.addCriteria(criteria); List maps = mongoTemplate.find(query, Map.class, "core-category"); if(maps!=null && maps.size()>=1){ return Result.failure(ResponseCode.ERROR_PARAMS_VALIDATOR,"名称重复"); } try { logger.info("新增项目分类入参:{}",JSON.toJSONString(jsonObject)); mongoTemplate.insert(jsonObject,"core-category"); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); return Result.success(jsonObject.get("_id")); }catch (Exception e){ logger.info("新增项分类失败",e); syncProjectRecord.setEndTime(new Date()); syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); return Result.failure(ResponseCode.ERROR_SERVICE_VALIDATOR,e.getMessage()); } } /**修改项目分类*/ @Override public Result updateServiceTree(BasicDBObject jsonObject) { logger.info("修改项目分类入参:{}",jsonObject.toString()); SyncProjectRecord syncProjectRecord=new SyncProjectRecord(3,1,0,0); syncProjectRecord.setOperationType(2); syncProjectRecord.setStartTime(new Date()); syncProjectRecord.setRequestParameters(JSON.toJSONString(jsonObject)); Query query = new Query(); Criteria criteria=new Criteria(); criteria.and("_id").is(jsonObject.get("id")); query.addCriteria(criteria); List maps = mongoTemplate.find(query, Map.class, "core-category"); if(maps==null || maps.size()!=1){ return Result.failure(ResponseCode.ERROR_PARAMS_VALIDATOR,"分类id不存在"); } Update update = new Update(); if(jsonObject.get("name")!=null){ update.set("name",jsonObject.get("name")); } if(jsonObject.get("value")!=null){ update.set("value",jsonObject.get("value")); } if(jsonObject.get("id")!=null){ update.set("code",jsonObject.get("id")); } if(jsonObject.get("state")!=null){ update.set("metadata.state",jsonObject.get("state")); } try { logger.info("修改项目分类入参:{}",update); mongoTemplate.updateFirst(query, update,"core-category"); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); return Result.success(); }catch (Exception e){ logger.info("修改项目分类入参失败",e); syncProjectRecord.setEndTime(new Date()); syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); return Result.failure(ResponseCode.ERROR_SERVICE_VALIDATOR,e.getMessage()); } } @Override public void saveHisProjectById(String id) { SyncProjectRecord syncProjectRecord=new SyncProjectRecord(4,2,0,0); syncProjectRecord.setStartTime(new Date()); syncProjectRecord.setRequestParameters(id); Query query = new Query(); Criteria criteria=new Criteria(); criteria.and("_id").is(id); query.addCriteria(criteria); List maps = mongoTemplate.find(query, Map.class, "his-care-service"); for (Map map : maps) { try { handleHisProject(JSONObject.fromObject(map)); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); } catch (Exception e) { syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); logger.error("同步项目失败:" ,map.get("_id"),e); } } syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); } /** * 新增项目 - 服务项目 */ @Override public Result syncAddProject(BasicDBObject project) { logger.info("新增项目phis入参:{}",JSON.toJSONString(project)); SyncProjectRecord syncProjectRecord=new SyncProjectRecord(3,1,0,0); syncProjectRecord.setOperationType(1); syncProjectRecord.setStartTime(new Date()); syncProjectRecord.setRequestParameters(JSON.toJSONString(project)); project.put("_id",UUID.randomUUID().toString()); JSONObject metadata=new JSONObject(); metadata.put("tenantId","0001"); metadata.put("version",1); metadata.put("state",1); project.put("metadata",metadata); project.put("businessTimestamp", new Date()); try { logger.info("新增项目入参:{}",JSON.toJSONString(project)); mongoTemplate.insert(project,"his-care-service"); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); return Result.success(project.get("_id")); }catch (Exception e){ logger.info("新增项目失败",e); syncProjectRecord.setEndTime(new Date()); syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); return Result.failure(ResponseCode.ERROR_SERVICE_VALIDATOR,e.getMessage()); } } /** * 修改项目 - 服务项目 */ @Override public Result syncUpdateProject(BasicDBObject basicDBObject) { logger.info("修改项目phis入参:{}",JSON.toJSONString(basicDBObject)); SyncProjectRecord syncProjectRecord=new SyncProjectRecord(3,2,0,0); syncProjectRecord.setOperationType(2); syncProjectRecord.setStartTime(new Date()); syncProjectRecord.setRequestParameters(JSON.toJSONString(basicDBObject)); if(basicDBObject.get("_id")==null){ return Result.failure(ResponseCode.ERROR_PARAMS_VALIDATOR,"修改的项目_id不能为空"); } Query up = new Query(Criteria.where("_id").is(basicDBObject.get("_id"))); Update update = new Update(); if(basicDBObject.get("typeId")!=null){ update.set("typeId",basicDBObject.get("typeId")); } if(basicDBObject.get("nameCh")!=null){ update.set("nameCh",basicDBObject.get("nameCh")); } if(basicDBObject.get("nameEn")!=null){ update.set("nameEn",basicDBObject.get("nameEn")); } if(basicDBObject.get("pinyin")!=null){ update.set("pinyin",basicDBObject.get("pinyin")); } if(basicDBObject.get("careServiceNumber")!=null){ update.set("careServiceNumber",basicDBObject.get("careServiceNumber")); } if(basicDBObject.get("bodyPart")!=null){ update.set("bodyPart",basicDBObject.get("bodyPart")); } if(basicDBObject.get("medicalDepartment")!=null){ update.set("medicalDepartment",basicDBObject.get("medicalDepartment")); } if(basicDBObject.get("spec")!=null){ update.set("spec",basicDBObject.get("spec")); } if(basicDBObject.get("unit")!=null){ update.set("unit",basicDBObject.get("unit")); } if(basicDBObject.get("note")!=null){ update.set("note",basicDBObject.get("note")); } if(basicDBObject.get("unitPrice")!=null){ update.set("unitPrice",basicDBObject.get("unitPrice")); } if(basicDBObject.get("originalUnitPrice")!=null){ update.set("originalUnitPrice",basicDBObject.get("originalUnitPrice")); } if(basicDBObject.get("aptitude")!=null){ update.set("aptitude",basicDBObject.get("aptitude")); } if(basicDBObject.get("standardCode")!=null){ update.set("standardCode",basicDBObject.get("standardCode")); } if(basicDBObject.get("standardName")!=null){ update.set("standardName",basicDBObject.get("standardName")); } if(basicDBObject.get("state")!=null){ update.set("metadata.state",basicDBObject.get("state")); } if(basicDBObject.get("courseCnt")!=null){ update.set("courseCnt",basicDBObject.get("courseCnt")); } if(basicDBObject.get("isCourseTreatment")!=null){ update.set("isCourseTreatment",basicDBObject.get("isCourseTreatment")); } try { logger.info("修改项目入参:{}",basicDBObject); mongoTemplate.updateFirst(up, update,"his-care-service"); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); return Result.success(); }catch (Exception e){ logger.info("修改项目入参失败",e); syncProjectRecord.setEndTime(new Date()); syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); return Result.failure(ResponseCode.ERROR_SERVICE_VALIDATOR,e.getMessage()); } } /** * 同步授权机构下的服务类项目数据 - 服务项目 */ @Override public void saveHisProject(SyncProjectRecord syncProjectRecord) { syncProjectRecord.setStartTime(new Date()); Query query = new Query(); Criteria criteria=new Criteria(); query.addCriteria(criteria); List maps = mongoTemplate.find(query, Map.class, "his-care-service"); for (Map map : maps) { try { handleHisProject(JSONObject.fromObject(map)); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); } catch (Exception e) { syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); logger.info("同步项目失败:{}" ,map.get("_id"),e); } } syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); } /** * 处理项目 */ private Project handleHisProject(JSONObject obj) { SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); //荣爷说phis删除isdel变成1,但是领健删除不了,所有放开isdel判断 09-21 sqlSentence.setSqlSentence("select * from project where apiId = #{m.apiId} "); map.put("apiId", obj.optString("_id")); Project p=null; try { p = projectMapper.selectOne(sqlSentence); }catch (Exception e){ logger.info("apiID重复,自己手动解决,apiId:{}",obj.optString("_id")); return null; } ProjectType pt=null; String typeId = obj.optString("typeId"); if(typeId==null){ logger.info("数据不完整,没有分类,项目id:{}",obj.optString("_id")); return null;//没有项目分类的项目使用不了 } sqlSentence.setSqlSentence("select * from project_type where apiId = #{m.id} and isDel =0"); map.put("id", typeId); pt = projectTypeMapper.selectOne(sqlSentence); if(pt==null){ logger.info("先同步分类,分类id:{},项目id:{}",typeId,obj.optString("_id")); return null;//没有项目分类的项目使用不了 } ProjectGeneral projectGeneral=null; ProjectAndType projectAndType=null; boolean operationType=false; if(p==null){ p=new Project(); p.setApiId(obj.optString("_id")); operationType=true; sqlSentence.setSqlSentence("select * from project_general where projectTypeId = #{m.projectTypeId} and name = #{m.name} and isDel =0"); map.put("projectTypeId", pt.getId()); map.put("name", obj.optString("nameCh")); projectGeneral=projectGeneralMapper.selectOne(sqlSentence); if(projectGeneral==null){ projectGeneral=new ProjectGeneral(); projectGeneral.setCoding(CreateNo.createTimeNo(systemParameterMapper, "SPU", 7, "yyyyMMdd")); projectGeneral.setProjectTypeId(pt.getId()); projectGeneral.setProjectTypeName(pt.getName()); projectGeneral.setName(obj.optString("nameCh")); projectGeneralMapper.insert(projectGeneral); } p.setProjectGeneralId(projectGeneral.getId()); }else { projectGeneral=projectGeneralMapper.selectOneByKey(p.getProjectGeneralId()); if(p.getIsSync()==BaseEntity.NO){ return p;//不需要同步 } // 2022-11-29 荣爷说要同步下面几个,应为双方下面几个参数不一样划扣有问题 //处理耗材成本 商品表 JSONArray products=obj.optJSONArray("products"); handleProducts(products,p.getId()); //处理工时成本 设备or角色表 JSONArray directCostPrices=obj.optJSONArray("directCostPrices"); handleDirectCostPrices(directCostPrices,p.getId()); //处理治疗参数 设备表 JSONArray devices=obj.optJSONArray("devices"); handleDevices(devices,p.getId()); //2022-11-07 荣爷说项目已phis为主 return p; } p.setProjectTypeId(pt.getId()); p.setProjectTypeName(pt.getName()); p.setName(obj.optString("nameCh")); // p.setUseDuration(obj.optInt("exclusiveDuration")*60); p.setUnit(obj.optString("unit")); p.setCoding(obj.optString("careServiceNumber")); p.setPrice(new BigDecimal(obj.optInt("unitPrice")).divide(new BigDecimal(100),2, RoundingMode.HALF_UP)); p.setOriginalPrice(new BigDecimal(obj.optInt("originalUnitPrice")).divide(new BigDecimal(100))); p.setIsUp(obj.optJSONObject("metadata").optInt("state")==1 ? BaseEntity.YES : BaseEntity.NO); p.setIsShow(p.getIsUp()); p.setEnable(p.getIsUp()); p.setSpecification(obj.optString("spec")); p.setStandardName(obj.optString("standardName")); //疗程数处理 boolean isCourseTreatment=obj.getBoolean("isCourseTreatment"); boolean executable=obj.getBoolean("executable"); p.setIsTreatmentItems(isCourseTreatment==true?1:0); Integer courseCnt=obj.getInt("courseCnt"); p.setTreatmentItemsNum(courseCnt); if(operationType){ projectMapper.insert(p); }else { sqlSentence.setSqlSentence(" projectTypeId = #{m.projectTypeId},projectTypeName = #{m.projectTypeName},name = #{m.name}, " + " isUp = #{m.isUp},specification = #{m.specification},unit = #{m.unit},isShow = #{m.isShow},price = #{m.price},enable = #{m.enable},coding = #{m.coding}, " + " editTime = #{m.editTime},originalPrice = #{m.originalPrice},standardName = #{m.standardName} " + " ,isTreatmentItems = #{m.isTreatmentItems},treatmentItemsNum = #{m.treatmentItemsNum} where id = #{m.id}"); map.put("projectTypeId", p.getProjectTypeId()); map.put("projectTypeName", p.getProjectTypeName()); map.put("name", p.getName()); map.put("isUp", p.getIsUp()); map.put("specification", p.getSpecification()); map.put("unit", p.getUnit()); map.put("isShow", p.getIsShow()); map.put("price", p.getPrice()); map.put("enable", p.getEnable()); map.put("coding", p.getCoding()); map.put("editTime", new Date()); map.put("originalPrice", p.getOriginalPrice()); map.put("standardName", p.getStandardName()); map.put("isTreatmentItems", p.getIsTreatmentItems()); map.put("treatmentItemsNum", p.getTreatmentItemsNum()); map.put("id",p.getId()); projectMapper.updateWhere(sqlSentence); } sqlSentence.setSqlSentence("select * from project_info where projectId = #{m.projectId} and isDel = #{m.isDel}"); map.put("isDel", BaseEntity.NO); map.put("projectId", p.getId()); ProjectInfo projectInfo = projectInfoMapper.selectOne(sqlSentence); if (projectInfo == null) { projectInfo = new ProjectInfo(); projectInfo.setProjectId(p.getId()); //处理身体部位 if(obj.optString("bodyPart")!=null && StringUtils.noNull(obj.optString("bodyPart"))){ handleBodyParts(projectInfo,obj.optJSONObject("bodyPart")); } //处理科室 if(obj.optString("medicalDepartment")!=null && StringUtils.noNull(obj.optString("medicalDepartment"))){ handleFamiliesRoom(projectInfo,obj.optJSONObject("medicalDepartment")); } projectInfo.setDoctorQualification(obj.optString("aptitude")); projectInfoMapper.insert(projectInfo); } else { //处理身体部位 if(obj.optString("bodyPart")!=null && StringUtils.noNull(obj.optString("bodyPart"))){ handleBodyParts(projectInfo,obj.optJSONObject("bodyPart")); } //处理科室 if(obj.optString("medicalDepartment")!=null && StringUtils.noNull(obj.optString("medicalDepartment"))){ handleFamiliesRoom(projectInfo,obj.optJSONObject("medicalDepartment")); } projectInfo.setDoctorQualification(obj.optString("aptitude")); projectInfo.setEditTime(new Date()); projectInfoMapper.updateAll(projectInfo); } List type = new ArrayList<>(); if (pt.getParentId() == null && StringUtils.isEmpty(pt.getParentId())) { type.add(pt.getId()); } else { type.add(pt.getId()); type = hangdleProjectType(type, pt.getParentId()); } sqlSentence.setSqlSentence("select * from project_projectType where projectId = #{m.projectId} and isDel = 0"); List projectAndTypeList = projectAndTypeMapper.selectList(sqlSentence); if (projectAndTypeList != null && projectAndTypeList.size() > 0) { map.put("projectId", p.getId()); sqlSentence.setSqlSentence(" projectId = #{m.projectId} and isDel = #{m.isDel}"); projectAndTypeMapper.deleteWhere(sqlSentence); } for (String s : type) { projectAndType = new ProjectAndType(); projectAndType.setProjectId(p.getId()); projectAndType.setProjectTypeId(s); projectAndTypeMapper.insert(projectAndType); } if(operationType){ if (projectAndTypeList != null && projectAndTypeList.size() > 0) { map.put("projectId", projectGeneral.getId()); sqlSentence.setSqlSentence(" projectId = #{m.projectId} and isDel = #{m.isDel}"); projectAndTypeMapper.deleteWhere(sqlSentence); } for (String s : type) { projectAndType = new ProjectAndType(); projectAndType.setProjectId(projectGeneral.getId()); projectAndType.setProjectTypeId(s); projectAndTypeMapper.insert(projectAndType); } } //处理项目总表和规格表的关系,项目表和规格值表 handleProjectGenSpec(obj,projectGeneral,p); //处理耗材成本 商品表 JSONArray products=obj.optJSONArray("products"); handleProducts(products,p.getId()); //处理工时成本 设备or角色表 JSONArray directCostPrices=obj.optJSONArray("directCostPrices"); handleDirectCostPrices(directCostPrices,p.getId()); //处理治疗参数 设备表 JSONArray devices=obj.optJSONArray("devices"); handleDevices(devices,p.getId()); return p; } //处理耗材成本 public void handleProducts(JSONArray products,String projectId){ if (products==null) return; ProjectAndConsumables projectAndConsumables; JSONObject jsonObject; Consumables consumables; SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence(" projectId=#{m.projectId}"); map.put("projectId", projectId); projectAndConsumablesMapper.deleteWhere(sqlSentence); sqlSentence.setSqlSentence("select * from consumables where hisId = #{m.hisId} and isDel = 0"); for (Object product : products) { projectAndConsumables=new ProjectAndConsumables(); jsonObject= (JSONObject) product; map.put("hisId", jsonObject.optString("skuId")); consumables=consumablesMapper.selectOne(sqlSentence); projectAndConsumables.setConsumablesId(consumables==null?"找不到耗材":consumables.getId()); projectAndConsumables.setConsumablesName(consumables==null?"找不到耗材":consumables.getName()); projectAndConsumables.setConsumablesSpec(consumables==null?"找不到耗材":consumables.getSpec()); projectAndConsumables.setConsumablesUnit(consumables==null?"找不到耗材":consumables.getUnitName()); projectAndConsumables.setAdvicePrice(new BigDecimal(jsonObject.optInt("unitPrice")).divide(new BigDecimal(100),2, RoundingMode.HALF_UP)); projectAndConsumables.setAdviceNum(new BigDecimal(jsonObject.optString("qty"))); projectAndConsumables.setTotalPrice(new BigDecimal(jsonObject.optInt("totalPrice")).divide(new BigDecimal(100),2, RoundingMode.HALF_UP)); projectAndConsumables.setIsShow(jsonObject.optBoolean("takeOut")?BaseEntity.YES:BaseEntity.NO); projectAndConsumables.setIsRequired(jsonObject.optBoolean("isMust")?BaseEntity.YES:BaseEntity.NO); projectAndConsumables.setCourseCount(1); projectAndConsumables.setProjectId(projectId); projectAndConsumablesMapper.insert(projectAndConsumables); } } //处理工时成本 public void handleDirectCostPrices(JSONArray directCostPrices,String projectId){ if (directCostPrices==null) return; ProjectLaborCost projectLaborCost; JSONObject jsonObject; EmployeeRoleType employeeRoleType; Device device; JSONObject type; String typeText; JSONObject name; String nameText; String nameId; SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence(" projectId=#{m.projectId}"); map.put("projectId", projectId); projectLaborCostMapper.deleteWhere(sqlSentence); for (Object directCostPrice : directCostPrices) { projectLaborCost=new ProjectLaborCost(); jsonObject= (JSONObject) directCostPrice; type=jsonObject.optJSONObject("type"); if(type==null){ return; } typeText=type.optString("displayText"); projectLaborCost.setCategory(typeText); if("人工".equals(typeText)){ name=jsonObject.optJSONObject("name"); if(name==null){ return; } nameText=name.optString("displayText"); projectLaborCost.setCommonName(nameText); sqlSentence.setSqlSentence(" select id from employee_role_type where name= #{m.name}"); map.put("name", nameText); employeeRoleType=employeeRoleTypeMapper.selectOne(sqlSentence); if(employeeRoleType==null){ projectLaborCost.setCommonId("找不到人工角色"); }else { projectLaborCost.setCommonId(employeeRoleType.getId()); } }else if("设备".equals(typeText)){ name=jsonObject.optJSONObject("name"); if(name==null){ return; } nameText=name.optString("vocabName"); nameId=name.optString("value"); projectLaborCost.setCommonName(nameText); sqlSentence.setSqlSentence(" select id from device where hisId= #{m.hisId}"); map.put("hisId", nameId); device=deviceMapper.selectOne(sqlSentence); if(device==null){ projectLaborCost.setCommonId("找不到设备"); }else { projectLaborCost.setCommonId(device.getId()); } }else { return; } projectLaborCost.setWorkingHours(new BigDecimal(jsonObject.optString("qty"))); projectLaborCost.setWorkingUnitl(jsonObject.optJSONObject("unit")==null?"":jsonObject.optJSONObject("unit").optString("displayText")); projectLaborCost.setCostNum(new BigDecimal(jsonObject.optInt("unitPrice")).divide(new BigDecimal(100),2, RoundingMode.HALF_UP)); projectLaborCost.setCostUnitl("元/"); projectLaborCost.setCourseCount(1); projectLaborCost.setTotalCost(new BigDecimal(jsonObject.optInt("price")).divide(new BigDecimal(100),2, RoundingMode.HALF_UP)); projectLaborCost.setProjectId(projectId); projectLaborCostMapper.insert(projectLaborCost); } } //处理治疗参数 public void handleDevices(JSONArray devices,String projectId){ if (devices==null) return; ProjectDeviceParameter projectAndConsumables; JSONObject jsonObject; Device device; DeviceParameter deviceParameter; SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence(" projectId=#{m.projectId}"); map.put("projectId", projectId); projectDeviceParameterMapper.deleteWhere(sqlSentence); for (Object device1 : devices) { projectAndConsumables=new ProjectDeviceParameter(); jsonObject= (JSONObject) device1; sqlSentence.setSqlSentence(" select id,name from device where hisId= #{m.hisId}"); map.put("hisId", jsonObject.optJSONObject("device").optString("_id")); device=deviceMapper.selectOne(sqlSentence); if(device==null){ continue; } projectAndConsumables.setProjectId(projectId); projectAndConsumables.setDeviceId(device.getId()); projectAndConsumables.setDeviceName(device.getName()); sqlSentence.setSqlSentence("SELECT * FROM device_parameter WHERE deviceId = #{m.deviceId} and parameterName=#{m.parameterName} and isDel = 0 "); map.put("deviceId",device.getId()); map.put("parameterName",jsonObject.optString("parameterName")); deviceParameter=deviceParameterMapper.selectOne(sqlSentence); if(deviceParameter==null){ continue; } projectAndConsumables.setParameterId(deviceParameter.getDeviceId()); projectAndConsumables.setParameterName(deviceParameter.getParameterName()); projectAndConsumables.setParameterUntil(deviceParameter.getParameterUntil()); projectAndConsumables.setReference(deviceParameter.getReference()); projectAndConsumables.setIsRequired(jsonObject.optBoolean("require")?BaseEntity.YES:BaseEntity.NO); projectDeviceParameterMapper.insert(projectAndConsumables); } } //处理身体部位 public ProjectInfo handleBodyParts(ProjectInfo projectInfo, JSONObject bodyPart){ SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from body_parts where hisId = #{m.hisId} and isDel = #{m.isDel}"); map.put("isDel", BaseEntity.NO); map.put("hisId", bodyPart.optString("_id")); BodyParts bodyParts = null; if (bodyPart != null) { String id = bodyPart.optString("_id"); String name = bodyPart.optString("name"); if (!StringUtils.isEmpty(id)) { map.put("hisId", id); bodyParts = bodyPartsMapper.selectOne(sqlSentence); if (bodyParts == null) { bodyParts = new BodyParts(); bodyParts.setName(name); bodyParts.setHisId(id); bodyPartsMapper.insert(bodyParts); } projectInfo.setBodyPartId(bodyParts.getId()); projectInfo.setBodyPartName(name); } } return projectInfo; } //处理科室 public ProjectInfo handleFamiliesRoom(ProjectInfo projectInfo, JSONObject medicalDepartment){ SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from families_room where hisId = #{m.hisId} and isDel = #{m.isDel}"); map.put("isDel", BaseEntity.NO); map.put("hisId", medicalDepartment.optString("_id")); FamiliesRoom familiesRoom = null; if (medicalDepartment != null) { String id = medicalDepartment.optString("_id"); String name = medicalDepartment.optString("name"); if (!StringUtils.isEmpty(id)) { map.put("hisId", id); familiesRoom = familiesRoomMapper.selectOne(sqlSentence); if (familiesRoom == null) { projectInfo.setDepartmentName(name); projectInfo.setDepartmentCode("科室表没有对应的科室"); }else { projectInfo.setDepartmentName(familiesRoom.getFamiliesRoomName()); // 2022-11-04 14:25 荣爷说存科室id 因为code会有重复的 projectInfo.setDepartmentCode(familiesRoom.getId()); } } } return projectInfo; } //处理项目总表和规格表的关系,项目表和规格值表 public void handleProjectGenSpec(JSONObject obj,ProjectGeneral projectGeneral,Project p){ SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); //先删除调所有旧的关联 sqlSentence.setSqlSentence(" generalId = #{m.id}"); map.put("id", projectGeneral.getId()); projectGenSpecMapper.deleteWhere(sqlSentence); sqlSentence.setSqlSentence(" projectId = #{m.id}"); map.put("id", p.getId()); projectSpecValueMapper.deleteWhere(sqlSentence); String specId=null; String specValueId=null; if (!StringUtils.isEmpty(obj.optString("bodyPart"))) { System.out.println(obj.optString("bodyPart")); specId= handleSpecification("身体部位"); specValueId=handleSpecificationValue(obj.optJSONObject("bodyPart").optString("name"),specId); handleProjectSpecValue(projectGeneral.getId(),specId,p.getId(),specValueId); } if(!StringUtils.isEmpty(obj.optString("spec"))){ specId= handleSpecification("规格"); specValueId=handleSpecificationValue(obj.optString("spec"),specId); handleProjectSpecValue(projectGeneral.getId(),specId,p.getId(),specValueId); } if(!StringUtils.isEmpty(obj.optString("unit"))){ specId= handleSpecification("单位"); specValueId=handleSpecificationValue(obj.optString("unit"),specId); handleProjectSpecValue(projectGeneral.getId(),specId,p.getId(),specValueId); } if(!StringUtils.isEmpty(obj.optString("aptitude"))){ specId= handleSpecification("医生资质"); specValueId=handleSpecificationValue(obj.optString("aptitude"),specId); handleProjectSpecValue(projectGeneral.getId(),specId,p.getId(),specValueId); } } //初始化规格 public String handleSpecification(String name){ SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from specification where specName = #{m.specName} and isDel =0"); map.put("specName", name); Specification specification= specificationMapper.selectOne(sqlSentence); if(specification==null){ specification =new Specification(); specification.setCoding(CreateNo.createTimeNo(systemParameterMapper, "SP", 8, "yyyyMMdd")); specification.setSpecName(name); specificationMapper.insert(specification); } return specification.getId(); } //初始化规格值 public String handleSpecificationValue(String name,String specificationId){ SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from specification_value where specValueName = #{m.specValueName} and specificationId = #{m.specificationId} and isDel =0"); map.put("specValueName", name); map.put("specificationId", specificationId); List specificationValues=specificationValueMapper.selectList(sqlSentence); SpecificationValue specificationValue=null; if(specificationValues==null || specificationValues.size()==0){ specificationValue =new SpecificationValue(); specificationValue.setSpecValueName(name); specificationValue.setSpecificationId(specificationId); specificationValueMapper.insert(specificationValue); }else { specificationValue= specificationValues.get(0); } return specificationValue.getId(); } //处理项目总表和规格表管理,项目表和规格值表管理 public void handleProjectSpecValue(String projectGeneralId,String specId,String projectId,String specValueId){ ProjectGenSpec projectGenSpec=new ProjectGenSpec(); projectGenSpec.setGeneralId(projectGeneralId); projectGenSpec.setSpecId(specId); projectGenSpecMapper.insert(projectGenSpec); ProjectSpecValue projectSpecValue=new ProjectSpecValue(); projectSpecValue.setProjectId(projectId); projectSpecValue.setSpecValue(specValueId); projectSpecValueMapper.insert(projectSpecValue); } public List hangdleProjectType(List type, String parentId) { SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from project_type where id = #{m.parentId} and isDel = #{m.isDel}"); map.put("isDel", BaseEntity.NO); map.put("parentId", parentId); ProjectType pt = projectTypeMapper.selectOne(sqlSentence); if (pt == null) { return type; } else { if (pt.getParentId() == null && StringUtils.isEmpty(pt.getParentId())) { type.add(pt.getId()); return type; } else { type.add(pt.getId()); return hangdleProjectType(type, pt.getParentId()); } } } /** * 同步所有促销 * * mongodb对应的数据 测试促销,名称用:测试同步专用(勿拍) * 促销名称 name 拼音码 pinyin * 归属门店 organizations 促销时间 startDate endDate * 状态 active 是否成交 isDeal * 促销类型 scope * 营销类型 marketingType * 生日礼物 按月 birthdayMonth:true 按日 birthdayDay:true * 最近一次到访类型 lastVisitTypes * 限制数量 limitCount 限制总量 totalLimitCount 收款日起, 有效天数 expiredDays 时间卡 periodsNumber * 积分抵扣 抵扣下限 : minCredit 抵扣上限 :maxCredit 积分不足时,是否可用其他支付方式代替:unRequiredCredit * * 促销标签 * 会员等级:memberShipIds * 会员星座:constellations * 客户印象标签 : extensions>customer-tag * 客户动态标签:profileTag * 会员服务类型:classificationIds * 描述:description * 项目 content>services * 商品 content>products */ @Override public void syncHisPromotion(SyncProjectRecord syncProjectRecord,JSONObject jsonObject) { syncProjectRecord.setStartTime(new Date()); syncProjectRecord.setRequestParameters(jsonObject.toString()); Query query = new Query(); Criteria criteria=new Criteria(); if(!StringUtils.isEmpty(jsonObject.optString("id"))){ criteria.and("_id").is(jsonObject.optString("id")); } if(!StringUtils.isEmpty(jsonObject.optString("name"))){ criteria.and("name").is(jsonObject.optString("name")); } query.addCriteria(criteria); List maps = mongoTemplate.find(query, Map.class, "crm-promotion"); for (Map map : maps) { try { handlePromotion(map); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); } catch (Exception e) { syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); logger.error("同步促销出错了:" + map,e); } } syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); } public void handlePromotion(Map map){ //等翔爷那边表设计完 String type =JSONObject.fromObject(map.get("type")).optString("text"); if("促销活动规则".equals(type)){ return;//三少说促销规则不要了 } SqlSentence sqlSentence = new SqlSentence(); Map mapSql = new HashMap<>(); sqlSentence.setM(mapSql); sqlSentence.setSqlSentence("select * from promotion where apiId = #{m.apiId} and isDel = 0 "); String id = null; String name = null; //名称 boolean active = false;//状态 Long amount = null; Promotion promotion = null; id = (String) map.get("_id"); mapSql.put("apiId", id); promotion=promotionMapper.selectOne(sqlSentence); name = (String) map.get("name"); amount = (Long) map.get("amount"); active= (boolean) map.get("active"); if(promotion==null){ promotion=new Promotion(); promotion.setCode(CreateNo.createTimeNo(systemParameterMapper, "CX", 8, "yyyyMMdd")); promotion.setApiId(id); promotion.setName(name); if(new Date().before((Date) map.get("startDate"))){ promotion.setStatus(active==true?Promotion.NOT_START:Promotion.STOP_PAUSE); }else if(new Date().before((Date) map.get("endDate"))){ promotion.setStatus(active==true?Promotion.IN_PROGRESS:Promotion.STOP_PAUSE); }else { promotion.setStatus(Promotion.STOP_START); } promotion.setTotal(new BigDecimal(amount).divide(new BigDecimal(100))); promotionMapper.insert(promotion); }else { if(promotion.getIsSync()==BaseEntity.NO){ return;//不需要同步 } promotion.setName(name); if(promotion.getCode()==null){ promotion.setCode(CreateNo.createTimeNo(systemParameterMapper, "CX", 8, "yyyyMMdd")); } if(new Date().before((Date) map.get("startDate"))){ promotion.setStatus(active==true?Promotion.NOT_START:Promotion.STOP_PAUSE); }else if(new Date().before((Date) map.get("endDate"))){ promotion.setStatus(active==true?Promotion.IN_PROGRESS:Promotion.STOP_PAUSE); }else { promotion.setStatus(Promotion.STOP_START); } promotion.setEditTime(new Date()); promotion.setTotal(new BigDecimal(amount).divide(new BigDecimal(100))); promotionMapper.updateAll(promotion); } //处理内容 JSONObject content= JSONObject.fromObject(map.get("content")) ; if(content!=null){ handlePromotionInfo(content,promotion.getId()); } //处理限制 2022-08-24 荣爷说不处理促销的限制,避免覆盖phis修改的门店,平台限制 //2022-09-01 荣爷说需要更改促销的有效时间 handleLimitTotal(promotion, MemberLimit.LIMIT_PROMOTION,JSONObject.fromObject(map)); } //处理促销内容 public void handlePromotionInfo(JSONObject content,String promotionId) { SqlSentence sqlSentence = new SqlSentence(); Map mapSql = new HashMap<>(); sqlSentence.setM(mapSql); //2022-09-13 荣爷说以为领建可以修改促销内容我们这边也修改 sqlSentence.setSqlSentence(" isDel = 1 where promotionId = #{m.promotionId}"); mapSql.put("promotionId", promotionId); promotionInfoMapper.updateWhere(sqlSentence); //处理项目 JSONArray services=content.optJSONArray("services"); JSONObject service=null; Project p=null; PromotionInfo promotionInfo=null; sqlSentence.setSqlSentence("select * from promotion_info where commonId = #{m.commonId} and promotionId = #{m.promotionId} "); if(services!=null){ for (Object o : services) { service= (JSONObject) o; p = projectMapper.selectOneByApiId(service.optString("serviceId")); if(p==null){ break; } mapSql.put("commonId", p.getId()); promotionInfo=promotionInfoMapper.selectOne(sqlSentence); if(promotionInfo==null){ promotionInfo=new PromotionInfo(); promotionInfo.setCommonCode(p.getCoding()); promotionInfo.setCommonName(p.getName()); promotionInfo.setCommonId(p.getId()); promotionInfo.setType("project"); promotionInfo.setSpecJson("[\""+p.getSpecification()+"\"]"); promotionInfo.setTreatmentItemsNum(p.getTreatmentItemsNum()); promotionInfo.setPrice(p.getPrice()); promotionInfo.setNum(service.optInt("qty")); promotionInfo.setTotal(new BigDecimal(service.optInt("totalRetailPrice")).divide(new BigDecimal(100))); promotionInfo.setDiscountPrice(new BigDecimal(service.optInt("unitTransactionalPrice")).divide(new BigDecimal(100))); promotionInfo.setDiscountAfterPrice(new BigDecimal(service.optInt("totalTransactionalPrice")).divide(new BigDecimal(100)) ); if(promotionInfo.getDiscountAfterPrice().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setIsGiving(1); }else { promotionInfo.setIsGiving(0); } if(promotionInfo.getTotal().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setDiscount(BigDecimal.valueOf(100)); }else if(promotionInfo.getTotal().compareTo(new BigDecimal("0.00")) != 0 && promotionInfo.getDiscountAfterPrice().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setDiscount(BigDecimal.valueOf(0)); }else { promotionInfo.setDiscount(promotionInfo.getDiscountAfterPrice().divide(promotionInfo.getTotal(),4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100))); } promotionInfo.setPromotionId(promotionId); promotionInfo.setIsSpa(isSpa(p.getProjectTypeId())?1:0); promotionInfoMapper.insert(promotionInfo); }else { promotionInfo.setIsDel(0); promotionInfo.setCommonCode(p.getCoding()); promotionInfo.setCommonName(p.getName()); promotionInfo.setCommonId(p.getId()); promotionInfo.setType("project"); promotionInfo.setSpecJson("[\""+p.getSpecification()+"\"]"); promotionInfo.setTreatmentItemsNum(p.getTreatmentItemsNum()); promotionInfo.setPrice(BigDecimal.valueOf(100)); promotionInfo.setNum(service.optInt("qty")); promotionInfo.setTotal(new BigDecimal(service.optInt("totalRetailPrice")).divide(new BigDecimal(100))); promotionInfo.setDiscountPrice(new BigDecimal(service.optInt("unitTransactionalPrice")).divide(new BigDecimal(100))); promotionInfo.setDiscountAfterPrice(new BigDecimal(service.optInt("totalTransactionalPrice")).divide(new BigDecimal(100))); if(promotionInfo.getDiscountAfterPrice().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setIsGiving(1); }else { promotionInfo.setIsGiving(0); } if(promotionInfo.getTotal().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setDiscount(BigDecimal.valueOf(100)); }else if(promotionInfo.getTotal().compareTo(new BigDecimal("0.00")) != 0 && promotionInfo.getDiscountAfterPrice().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setDiscount(BigDecimal.valueOf(0)); }else { promotionInfo.setDiscount(promotionInfo.getDiscountAfterPrice().divide(promotionInfo.getTotal(),4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100))); } promotionInfo.setEditTime(new Date()); promotionInfoMapper.updateAll(promotionInfo); } } } //处理商品 JSONArray products=content.optJSONArray("products"); JSONObject product=null; Consumables consumables=null; if(products!=null){ for (Object o : products) { product = (JSONObject) o; sqlSentence.setSqlSentence("select * from consumables where isDel = 0 and hisId = #{m.hisId} "); mapSql.put("hisId", product.optString("skuId")); consumables=consumablesMapper.selectOne(sqlSentence); if(consumables==null){ break; } sqlSentence.setSqlSentence("select * from promotion_info where commonId = #{m.commonId} and promotionId = #{m.promotionId} "); mapSql.put("promotionId", promotionId); mapSql.put("commonId", consumables.getId()); promotionInfo=promotionInfoMapper.selectOne(sqlSentence); if(promotionInfo==null){ promotionInfo=new PromotionInfo(); promotionInfo.setCommonCode(consumables.getSerialNumber()); promotionInfo.setCommonName(consumables.getName()); promotionInfo.setCommonId(consumables.getId()); promotionInfo.setType("retail"); promotionInfo.setSpecJson("[\""+consumables.getSpec()+"\"]"); promotionInfo.setTreatmentItemsNum(0); promotionInfo.setPrice(consumables.getPrice()); promotionInfo.setNum(product.optInt("qty")); promotionInfo.setTotal(new BigDecimal(product.optInt("totalRetailPrice")).divide(new BigDecimal(100))); promotionInfo.setDiscountPrice(new BigDecimal(product.optInt("unitTransactionalPrice")).divide(new BigDecimal(100))); promotionInfo.setDiscountAfterPrice(new BigDecimal(product.optInt("totalTransactionalPrice")).divide(new BigDecimal(100))); if(promotionInfo.getDiscountAfterPrice().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setIsGiving(1); }else { promotionInfo.setIsGiving(0); } if(promotionInfo.getTotal().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setDiscount(BigDecimal.valueOf(100)); }else if(promotionInfo.getTotal().compareTo(new BigDecimal("0.00")) != 0 && promotionInfo.getDiscountAfterPrice().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setDiscount(BigDecimal.valueOf(0)); }else { promotionInfo.setDiscount(promotionInfo.getDiscountAfterPrice().divide(promotionInfo.getTotal(),4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100))); } promotionInfo.setPromotionId(promotionId); promotionInfoMapper.insert(promotionInfo); }else { promotionInfo.setIsDel(0); promotionInfo.setCommonCode(consumables.getSerialNumber()); promotionInfo.setCommonName(consumables.getName()); promotionInfo.setCommonId(consumables.getId()); promotionInfo.setType("retail"); promotionInfo.setSpecJson("[\""+consumables.getSpec()+"\"]"); promotionInfo.setTreatmentItemsNum(0); promotionInfo.setPrice(consumables.getPrice()); promotionInfo.setNum(product.optInt("qty")); promotionInfo.setTotal(new BigDecimal(product.optInt("totalRetailPrice")).divide(new BigDecimal(100))); promotionInfo.setDiscountPrice(new BigDecimal(product.optInt("unitTransactionalPrice")).divide(new BigDecimal(100))); promotionInfo.setDiscountAfterPrice(new BigDecimal(product.optInt("totalTransactionalPrice")).divide(new BigDecimal(100))); if(promotionInfo.getDiscountAfterPrice().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setIsGiving(1); }else { promotionInfo.setIsGiving(0); } if(promotionInfo.getTotal().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setDiscount(BigDecimal.valueOf(100)); }else if(promotionInfo.getTotal().compareTo(new BigDecimal("0.00")) != 0 && promotionInfo.getDiscountAfterPrice().compareTo(new BigDecimal("0.00")) == 0){ promotionInfo.setDiscount(BigDecimal.valueOf(0)); }else { promotionInfo.setDiscount(promotionInfo.getDiscountAfterPrice().divide(promotionInfo.getTotal(),4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100))); } promotionInfo.setEditTime(new Date()); promotionInfoMapper.updateAll(promotionInfo); } } } } //处理促销限制 public void handleLimitTotal(Promotion promotion, int type, JSONObject json) { SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from limit_total where foreignKey = #{m.foreignKey} and type = #{m.type} and isDel = 0 "); map.put("foreignKey", promotion.getId()); map.put("type", type); LimitTotal limitTotal=limitTotalMapper.selectOne(sqlSentence); if(limitTotal==null){ limitTotal=new LimitTotal(); limitTotal.setCode(promotion.getCode()); limitTotal.setForeignKey(promotion.getId()); limitTotal.setLimitNum(json.optInt("limitCount")); limitTotal.setLimitSumNum(json.optInt("totalLimitCount")); limitTotal.setIsUp("false".equals(json.optString("isDeal"))==true?0:1); limitTotal.setStartTime(DateUtil.timestampToDate(json.optJSONObject("startDate").optLong("time"),"")); limitTotal.setEndTime(DateUtil.timestampToDate(json.optJSONObject("endDate").optLong("time"),"")); limitTotal.setType(type); limitTotalMapper.insert(limitTotal); }else { limitTotal.setLimitNum(json.optInt("limitCount")); limitTotal.setLimitSumNum(json.optInt("totalLimitCount")); limitTotal.setIsUp("false".equals(json.optString("isDeal"))==true?0:1); limitTotal.setStartTime(DateUtil.timestampToDate(json.optJSONObject("startDate").optLong("time"),"")); limitTotal.setEndTime(DateUtil.timestampToDate(json.optJSONObject("endDate").optLong("time"),"")); limitTotal.setEditTime(new Date()); limitTotalMapper.updateAll(limitTotal); } //2022-09-01 荣爷说需要更改促销的有效时间 09-26 荣爷说门店限制是领健修改的,所以要同步;所有限制以领健为主 //会员限制 JSONArray memberShipIds=json.optJSONArray("memberShipIds"); handleMemberLimit(type,promotion.getId(),limitTotal.getId(),memberShipIds); //先删除所有存在的其他限制,因为更新的时候没限制领键mongodb是没存字段的 sqlSentence.setSqlSentence("select * from limit_other where limitTotalId = #{m.limitTotalId} "); map.put("limitTotalId", limitTotal.getId()); List list=limitOtherMapper.selectList(sqlSentence); if(list!=null || list.size()>0){ sqlSentence.setSqlSentence(" limitTotalId = #{m.limitTotalId}"); limitOtherMapper.deleteWhere(sqlSentence); } //星座限制 JSONArray constellations=json.optJSONArray("constellations"); handleLimitOther(LimitOther.TYPE_STAR,limitTotal.getId(),constellations); //门店限制 JSONArray organizations=json.optJSONArray("organizations"); handleLimitOther(LimitOther.TYPE_SHOP,limitTotal.getId(),organizations); } /** * 处理会员限制 * @param jsonArray */ public void handleMemberLimit(int type,String foreignKey,String limitTotalId,JSONArray jsonArray){ if(jsonArray==null || jsonArray.size()==0) return; SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from member_limit where foreignKey = #{m.foreignKey} and type = #{m.type} and limitTotalId = #{m.limitTotalId} and isDel = 0 "); map.put("type", type); map.put("foreignKey", foreignKey); map.put("limitTotalId", limitTotalId); List list=memberLimitMapper.selectList(sqlSentence); if(list!=null && list.size()>0){ return;//三少说我们这边会员限可以修改,所有同步中心定时器同步促销的时候不修改会员限制,只再新增的时候触发 } if(list!=null || list.size()>0){ sqlSentence.setSqlSentence(" isDel = 0 and foreignKey = #{m.foreignKey} and type = #{m.type} and limitTotalId = #{m.limitTotalId} "); memberLimitMapper.deleteWhere(sqlSentence); } MemberLimit memberLimit=null; sqlSentence.setSqlSentence("select * from member_level where hisNo = #{m.hisNo} "); MemberLevel memberLevel=null; for (Object memberShipId : jsonArray) { memberLimit = new MemberLimit(); memberLimit.setType(type); memberLimit.setForeignKey(foreignKey); map.put("hisNo", memberShipId); memberLevel= memberLevelMapper.selectOne(sqlSentence); memberLimit.setMemberId(memberLevel.getId()); memberLimit.setCode(memberLevel.getName()); memberLimit.setLimitTotalId(limitTotalId); memberLimitMapper.insert(memberLimit); } } /** * 处理其他限制限制 * @param jsonArray */ public void handleLimitOther(int type,String limitTotalId,JSONArray jsonArray){ if(jsonArray==null || jsonArray.size()==0) return; SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); LimitOther limitOther=null; JSONObject other=null; if(LimitOther.TYPE_STAR.equals(type)){ for (Object o : jsonArray) { other= (JSONObject) o; limitOther = new LimitOther(); limitOther.setCommonName(other.optString("text")); limitOther.setType(type); limitOther.setLimitTotalId(limitTotalId); limitOtherMapper.insert(limitOther); } }else if(LimitOther.TYPE_SHOP.equals(type)){ Shop shop=null; sqlSentence.setSqlSentence("select * from shop where apiId = #{m.apiId} and isDel=0 "); for (Object o : jsonArray) { other= (JSONObject) o; limitOther = new LimitOther(); map.put("apiId", other.optString("_id")); shop=shopMapper.selectOne(sqlSentence); if(shop==null)break; limitOther.setCommonId(shop.getId()); limitOther.setCommonName(shop.getName()); limitOther.setType(type); limitOther.setLimitTotalId(limitTotalId); limitOtherMapper.insert(limitOther); } } } /**同步所有卡项*/ /** * 同步所有卡项 * * mongodb对应的数据 测试促销,名称用:测试同步专用(勿拍) * * * @return */ @Override public void syncHisCardItem(JSONObject jsonObject, SyncProjectRecord syncProjectRecord) { syncProjectRecord.setStartTime(new Date()); syncProjectRecord.setRequestParameters(jsonObject.toString()); Query query = new Query(); Criteria criteria=new Criteria(); criteria.and("type").is("fusion-card"); if(!StringUtils.isEmpty(jsonObject.optString("id"))){ criteria.and("_id").is(jsonObject.optString("id")); } // criteria.and("name").is("京浙金钻特权-赠送Venus Legacy(全腹部/双侧腰部/提臀)4次/年"); query.addCriteria(criteria); List maps = mongoTemplate.find(query, Map.class, "core-coupon"); for (Map map : maps) { try { handleCard(map); syncProjectRecord.setSuccessNumber(syncProjectRecord.getSuccessNumber()+1); } catch (Exception e) { syncProjectRecord.setFailNumber(syncProjectRecord.getFailNumber()+1); logger.error("同步卡项出错了:" + map,e); } } syncProjectRecord.setEndTime(new Date()); syncTransactioalService.insert(SyncProjectRecordMapper.class,syncProjectRecord); } public void handleCard(Map map){ String id = null; String name = null; Long amount = null; JSONObject metadata=null; JSONObject status=null; CardItem cardItem=null; SqlSentence sqlSentence = new SqlSentence(); Map mapSql = new HashMap<>(); sqlSentence.setM(mapSql); sqlSentence.setSqlSentence("select * from card_item where apiId = #{m.apiId} "); id = (String) map.get("_id"); name = (String) map.get("name"); amount = (Long) map.get("amount"); status= JSONObject.fromObject( map.get("status")); metadata=JSONObject.fromObject( map.get("metadata")); mapSql.put("apiId", id); cardItem=cardItemMapper.selectOne(sqlSentence); if(cardItem==null){ cardItem=new CardItem(); cardItem.setCode(CreateNo.createTimeNo(systemParameterMapper, "CAR", 8, "yyyyMMdd"));//生成随机编码 cardItem.setApiId(id); cardItem.setName(name); cardItem.setTotal(new BigDecimal(amount).divide(new BigDecimal(100))); if("sales".equals(status.optJSONArray("codes").optJSONObject(0).optString("value")) && "1".equals( metadata.optString("state")) && "0001".equals(metadata.optString("tenantId"))){ cardItem.setIsUp(BaseEntity.YES); }else { cardItem.setIsUp(BaseEntity.NO); } switch (status.optJSONArray("codes").optJSONObject(0).optString("value")){ case "sales": cardItem.setStatus(CardItem.SALES); break; case "off-shelves": cardItem.setStatus(CardItem.OFF_SHELVES); break; case "overdue": cardItem.setStatus(CardItem.OVERDUE); break; case "disabled": cardItem.setStatus(CardItem.DISABLED); break; } cardItemMapper.insert(cardItem); //里面相关内容只有新增的时候才处理,不然影响已经下单的卡项,只修改上下架 22-04-01 JSONArray groups=JSONArray.fromObject(map.get("groups")) ; handleCardEquity(groups,cardItem.getId()); //权限绑定 handleCardItemLimitTotal(cardItem,MemberLimit.LIMIT_CARD_ITEM,JSONObject.fromObject(map)); }else { if(cardItem.getIsSync()==BaseEntity.NO){ return;//不需要同步 } //2022-11-30 荣爷说状态和上下架不和领建同步,所以不处理 /*if("sales".equals(status.optJSONArray("codes").optJSONObject(0).optString("value")) && "1".equals( metadata.optString("state"))&& "0001".equals( metadata.optString("tenantId"))){ cardItem.setIsUp(BaseEntity.YES); }else { cardItem.setIsUp(BaseEntity.NO); } */ switch (status.optJSONArray("codes").optJSONObject(0).optString("value")){ case "sales": cardItem.setStatus(CardItem.SALES); break; case "off-shelves": cardItem.setStatus(CardItem.OFF_SHELVES); break; case "overdue": cardItem.setStatus(CardItem.OVERDUE); break; case "disabled": cardItem.setStatus(CardItem.DISABLED); break; } cardItem.setEditTime(new Date()); cardItemMapper.updateAll(cardItem); sqlSentence.setSqlSentence("select * from limit_total where isDel = 0 and foreignKey = #{m.foreignKey} and type = #{m.type} "); mapSql.put("foreignKey", cardItem.getId()); mapSql.put("type", MemberLimit.LIMIT_CARD_ITEM); LimitTotal limitTotal=limitTotalMapper.selectOne(sqlSentence); limitTotal.setStartTime(DateUtil.timestampToDate(JSONObject.fromObject(map).optJSONObject("validity").optJSONObject("start").optJSONObject("_date").optLong("time"),"")); //备注原因:因为领键结束当天也算有效,所以设置23:59:59 Date endTime=DateUtil.timestampToDate(JSONObject.fromObject(map).optJSONObject("validity").optJSONObject("end").optJSONObject("_date").optLong("time"),""); limitTotal.setEndTime(DateUtil.parseString_1(DateUtil.formatDate_3(endTime)+" 23:59:59")); limitTotalMapper.updateAll(limitTotal); } } //处理卡项权益表 public void handleCardEquity(JSONArray groups,String cardItemId) { if(groups==null || groups.size()==00) return; JSONObject group=null; String equity=null; CardEquity cardEquity=null; for (Object o : groups) { cardEquity=new CardEquity(); group= (JSONObject) o; equity=group.optString("type"); cardEquity.setCardItemId(cardItemId); if("Package".equals(equity)){//权益类型-固定项目 cardEquity.setEquityType(CardEquity.EQUITY_TYPE_PROJECT); cardEquity.setShareMoney(new BigDecimal(group.optInt("shareAmount")).divide(new BigDecimal(100))); cardEquity.setIndexValue(group.optInt("index")); cardEquityMapper.insert(cardEquity); handleCardItemInfoProject(group.optJSONArray("lines"),cardItemId,cardEquity.getId()); }else if("Combination".equals(equity)){//权益类型-N选M cardEquity.setEquityType(CardEquity.EQUITY_TYPE_N_M); cardEquity.setGroupName(group.optString("name")); cardEquity.setValue(group.optInt("optionQuantity")); cardEquity.setIndexValue(group.optInt("index")); cardEquity.setShareMoney(new BigDecimal(group.optInt("shareAmount")).divide(new BigDecimal(100))); cardEquityMapper.insert(cardEquity); handleCardItemInfoProject(group.optJSONArray("lines"),cardItemId,cardEquity.getId()); }else if("Point".equals(equity)){//权益类型-次卡 cardEquity.setEquityType(CardEquity.EQUITY_TYPE_TIME_CARD); cardEquity.setGroupName(group.optString("name")); cardEquity.setValue(group.optInt("totalPoints")); cardEquity.setIndexValue(group.optInt("index")); cardEquity.setShareMoney(new BigDecimal(group.optInt("shareAmount")).divide(new BigDecimal(100))); cardEquityMapper.insert(cardEquity); handleCardItemInfoTimeCard(group.optJSONArray("lines"),cardItemId,cardEquity.getId()); }else if("Store".equals(equity)){//权益类型-账户权益 cardEquity.setEquityType(CardEquity.EQUITY_TYPE_ACCOUNT); cardEquity.setIndexValue(group.optInt("index")); cardEquity.setShareMoney(new BigDecimal(group.optInt("shareAmount")).divide(new BigDecimal(100))); cardEquityMapper.insert(cardEquity); handleCardItemInfoAcount(group.optInt("deposit"),group.optInt("giftMoney"),cardItemId,cardEquity.getId()); } } } //处理卡项权益类型-固定项目内容 权益类型-N选M public void handleCardItemInfoProject(JSONArray lines,String cardItemId,String cardEquityId) { JSONObject info=null; CardItemInfo cardItemInfo=null; for (Object line : lines) { info= (JSONObject) line; cardItemInfo=new CardItemInfo(); cardItemInfo.setMaxNum(info.optInt("salableQuantity")); cardItemInfo.setEmResultsNum(info.optInt("performanceQuantity")); cardItemInfo.setShareMoney(new BigDecimal(info.optInt("shareAmount")).divide(new BigDecimal(100))); cardItemInfo.setCardItemId(cardItemId); cardItemInfo.setCardEquityId(cardEquityId); cardItemInfo= handlecommonType(cardItemInfo,info.optJSONObject("scopeItem").optString("type"),info.optJSONObject("scopeItem").optString("_id")); if(cardItemInfo==null){ continue; } cardItemInfoMapper.insert(cardItemInfo); } } //处理卡项权益类型-次卡 public void handleCardItemInfoTimeCard(JSONArray lines,String cardItemId,String cardEquityId) { JSONObject info=null; CardItemInfo cardItemInfo=null; for (Object line : lines) { info= (JSONObject) line; cardItemInfo=new CardItemInfo(); cardItemInfo.setEveryDrawNum(info.optInt("unitCostPoints")); cardItemInfo.setEveryShareMoney(new BigDecimal(info.optInt("shareAmount")).divide(new BigDecimal(100))); cardItemInfo.setCardItemId(cardItemId); cardItemInfo.setCardEquityId(cardEquityId); cardItemInfo= handlecommonType(cardItemInfo,info.optJSONObject("scopeItem").optString("type"),info.optJSONObject("scopeItem").optString("_id")); if(cardItemInfo==null){ continue; } cardItemInfoMapper.insert(cardItemInfo); } } //处理卡项权益类型-账户权益 public void handleCardItemInfoAcount(int deposit,int giftMoney,String cardItemId,String cardEquityId) { SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); //处理储值金 CardItemInfo depositInfo=null; CardItemInfo giftMoneyInfo=null; PaymentMethod paymentMethod=null; sqlSentence.setSqlSentence("select * from payment_method where isDel = 0 and name = #{m.name} "); map.put("name", "储值金"); paymentMethod= paymentMethodMapper.selectOne(sqlSentence); if(paymentMethod!=null){ depositInfo=new CardItemInfo(); depositInfo.setCommonId(paymentMethod.getId()); depositInfo.setCommonName(paymentMethod.getName()); depositInfo.setCommonType("stored"); depositInfo.setPrice(new BigDecimal(giftMoney).divide(new BigDecimal(100))); depositInfo.setShareMoney(new BigDecimal(giftMoney).divide(new BigDecimal(100))); depositInfo.setCardItemId(cardItemId); depositInfo.setCardEquityId(cardEquityId); cardItemInfoMapper.insert(depositInfo); } map.put("name", "增值金"); paymentMethod= paymentMethodMapper.selectOne(sqlSentence); if(paymentMethod!=null){ giftMoneyInfo=new CardItemInfo(); giftMoneyInfo.setCommonId(paymentMethod.getId()); giftMoneyInfo.setCommonName(paymentMethod.getName()); giftMoneyInfo.setCommonType("increment"); giftMoneyInfo.setPrice(new BigDecimal(deposit).divide(new BigDecimal(100))); giftMoneyInfo.setShareMoney(new BigDecimal(deposit).divide(new BigDecimal(100))); giftMoneyInfo.setCardItemId(cardItemId); giftMoneyInfo.setCardEquityId(cardEquityId); cardItemInfoMapper.insert(giftMoneyInfo); } } //处理卡项内容类型 项目,商品,项目分类,商品分类 public CardItemInfo handlecommonType(CardItemInfo cardItemInfo,String type,String id) { SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); switch (type){ case "Service": Project p=projectMapper.selectOneByApiId(id); if(p==null)return null; cardItemInfo.setCommonCode(p.getCoding()); cardItemInfo.setCommonId(p.getId()); cardItemInfo.setCommonName(p.getName()); cardItemInfo.setCommonType("project"); cardItemInfo.setPrice(p.getPrice()); cardItemInfo.setIsSpa(isSpa(p.getProjectTypeId())?1:0); if(p.getSpecification()!=null){ cardItemInfo.setSpecJson("[\""+p.getSpecification()+"\"]"); } break; case "Product": sqlSentence.setSqlSentence("select * from consumables where isDel = 0 and hisId = #{m.hisId} "); map.put("hisId", id); Consumables consumables=consumablesMapper.selectOne(sqlSentence); if(consumables==null)return null; cardItemInfo.setCommonCode(consumables.getSerialNumber()); cardItemInfo.setCommonId(consumables.getId()); cardItemInfo.setCommonName(consumables.getName()); cardItemInfo.setPrice(consumables.getPrice()); if(consumables.getSpec()!=null){ cardItemInfo.setSpecJson("[\""+consumables.getSpec()+"\"]"); } cardItemInfo.setCommonType("retail"); break; case "ServiceCategory": sqlSentence.setSqlSentence("select * from project_type where isDel = 0 and apiId = #{m.apiId} "); map.put("apiId", id); ProjectType projectType=projectTypeMapper.selectOne(sqlSentence); if(projectType==null)return null; cardItemInfo.setCommonId(projectType.getId()); cardItemInfo.setCommonName(projectType.getName()); cardItemInfo.setCommonType("project_type"); break; case "ProductCategory": sqlSentence.setSqlSentence("select * from consumables_type where isDel = 0 and appId = #{m.appId} "); map.put("appId", id); ConsumablesType consumablesType=consumablesTypeMapper.selectOne(sqlSentence); if(consumablesType==null)return null; cardItemInfo.setCommonId(consumablesType.getId()); cardItemInfo.setCommonName(consumablesType.getName()); cardItemInfo.setCommonType("retail_type"); break; } return cardItemInfo; } //处理卡项限制 public void handleCardItemLimitTotal(CardItem cardItem, int type, JSONObject json) { SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("select * from limit_total where isDel = 0 and foreignKey = #{m.foreignKey} and type = #{m.type} "); map.put("foreignKey", cardItem.getId()); map.put("type", type); LimitTotal limitTotal=limitTotalMapper.selectOne(sqlSentence); if(limitTotal==null){ limitTotal=new LimitTotal(); limitTotal.setCode(cardItem.getCode()); limitTotal.setType(type); limitTotal.setForeignKey(cardItem.getId()); limitTotal.setLimitNum(json.optInt("customerLimitCount")==0?null:json.optInt("customerLimitCount")); limitTotal.setLimitSumNum(json.optInt("quantity")==0?null:json.optInt("quantity")); limitTotal.setIsUp(cardItem.getIsUp()); System.out.println(json.optJSONObject("validity").optJSONObject("start").optString("_date")); limitTotal.setStartTime(DateUtil.timestampToDate(json.optJSONObject("validity").optJSONObject("start").optJSONObject("_date").optLong("time"),"")); limitTotal.setEndTime(DateUtil.timestampToDate(json.optJSONObject("validity").optJSONObject("end").optJSONObject("_date").optLong("time"),"")); limitTotalMapper.insert(limitTotal); } //处理会员验证 handleMemberLimit(type,cardItem.getId(),limitTotal.getId(),json.optJSONArray("memberShipIds")); //星座限制 JSONArray constellations=json.optJSONArray("constellations"); handleLimitOther(LimitOther.TYPE_STAR,limitTotal.getId(),constellations); //门店限制 JSONArray organizations=json.optJSONArray("organizations"); handleLimitOther(LimitOther.TYPE_SHOP,limitTotal.getId(),organizations); } @Override public void delayPromotion(String id,int day) { // String id="097b6a3dc7ea48808660d13684b5cd07"; Calendar c = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Query query = new Query(); Criteria criteria=new Criteria(); criteria.and("_id").is(id); // criteria.and("name").is("京浙金钻特权-赠送Venus Legacy(全腹部/双侧腰部/提臀)4次/年"); query.addCriteria(criteria); List maps = mongoTemplate.find(query, Map.class, "his-fusion-card-group-instance"); for (Map map : maps) { Map availableDate= (Map) map.get("availableDate"); Date date= (Date) availableDate.get("end"); c.setTime(date); c.add(Calendar.DAY_OF_MONTH, day); Query up = new Query(Criteria.where("_id").is(id)); Update update = new Update().set("availableDate.end",c.getTime()); mongoTemplate.updateFirst(up, update,"his-fusion-card-group-instance"); } } @Override public boolean projectSpa(String projectTypeId) { return isSpa(projectTypeId); } /**初始化同步phis疗程数*/ @Override public void syncUpdateTreatmentItemsNum() { SqlSentence sqlSentence = new SqlSentence(); Map map = new HashMap<>(); sqlSentence.setM(map); sqlSentence.setSqlSentence("SELECT apiId,treatmentItemsNum FROM project WHERE apiId IS NOT NULL AND treatmentItemsNum>1 AND isDel=0 "); List projects=projectMapper.selectList(sqlSentence); BasicDBObject basicDBObject=null; for (Project project : projects) { basicDBObject = new BasicDBObject(); basicDBObject.put("_id",project.getApiId()); basicDBObject.put("isCourseTreatment",true); basicDBObject.put("courseCnt",project.getTreatmentItemsNum()); syncUpdateProject(basicDBObject); } } public boolean isSpa(String projectTypeId){ ProjectType projectType=projectTypeMapper.selectOneByKey(projectTypeId); if (!StringUtils.isEmpty(projectType.getParentId())){ isSpa(projectType.getParentId()); } if ( projectType.getName().indexOf(systemConfig.getIsSpa())!=-1){ return true; }else { return false; } } }