contract.go 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  1. package contract
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "hongze/hz_crm_api/models"
  9. "hongze/hz_crm_api/models/company"
  10. "hongze/hz_crm_api/models/contract"
  11. "hongze/hz_crm_api/models/contract/request"
  12. "hongze/hz_crm_api/models/system"
  13. "hongze/hz_crm_api/services"
  14. "hongze/hz_crm_api/utils"
  15. "mime/multipart"
  16. "os"
  17. "reflect"
  18. "regexp"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. // AddContract 新增合同
  25. func AddContract(req request.AddContractReq, sellerId, productId int, sellerName string) (newContract *contract.Contract, err error, errMsg string) {
  26. originalPrice := req.OriginalPrice
  27. price := req.Price
  28. if originalPrice < 0 {
  29. err = errors.New("合同金额不能小于0")
  30. return
  31. }
  32. //如果优惠后金额小于等于0,那么就是等于优惠前的金额
  33. if price <= 0 {
  34. price = originalPrice
  35. }
  36. //合同日期
  37. var startDate, endDate time.Time
  38. if req.ContractBusinessType == "代付合同" {
  39. businessContractInfo, tmpErr := contract.GetContractById(req.RelationContractId)
  40. if tmpErr != nil {
  41. err = tmpErr
  42. return
  43. }
  44. startDate = businessContractInfo.StartDate
  45. endDate = businessContractInfo.EndDate
  46. ok, tmpErr := CheckContractPrice(businessContractInfo, price)
  47. if tmpErr != nil {
  48. err = tmpErr
  49. return
  50. }
  51. if !ok {
  52. err = errors.New("合同金额异常,不能高于业务合同金额")
  53. errMsg = "合同金额异常,不能高于业务合同金额"
  54. return
  55. }
  56. } else {
  57. tmpStartDate, tmpErr := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  58. if tmpErr != nil {
  59. err = errors.New(fmt.Sprint("合同开始日期转换失败:", tmpErr))
  60. return
  61. }
  62. startDate = tmpStartDate
  63. tmpEndDate, tmpErr := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  64. if tmpErr != nil {
  65. err = errors.New(fmt.Sprint("合同结束日期转换失败:", tmpErr))
  66. return
  67. }
  68. endDate = tmpEndDate
  69. }
  70. companyName := req.CompanyName
  71. if companyName == "" {
  72. err = errors.New("客户名称必填")
  73. return
  74. }
  75. creditCode := req.CreditCode
  76. if companyName == "" {
  77. err = errors.New("社会统一信用代码必填")
  78. return
  79. }
  80. contractCode, err := contract.GetCompanyContractCode(productId, req.ContractBusinessType)
  81. if err != nil {
  82. err = errors.New(fmt.Sprint("合同编号生成异常,Err:", err))
  83. return
  84. }
  85. contractInfo := &contract.Contract{
  86. ContractCode: contractCode,
  87. SellerId: sellerId,
  88. SellerName: sellerName,
  89. ProductId: productId,
  90. ContractType: req.ContractType,
  91. ContractBusinessType: req.ContractBusinessType,
  92. Status: "待提交",
  93. StartDate: startDate,
  94. EndDate: endDate,
  95. OriginalPrice: originalPrice,
  96. Price: price,
  97. PayRemark: utils.TrimStr(req.PayRemark), //付款方式说明,长度255位
  98. PayChannel: utils.TrimStr(req.PayChannel), //付款渠道,长度255位
  99. CompanyName: utils.TrimStr(companyName),
  100. CreditCode: utils.TrimStr(creditCode),
  101. ProvinceId: req.ProvinceId,
  102. Province: utils.TrimStr(req.Province),
  103. CityId: req.CityId,
  104. City: utils.TrimStr(req.City),
  105. Address: utils.TrimStr(req.Address),
  106. Fax: utils.TrimStr(req.Fax),
  107. Phone: utils.TrimStr(req.Phone),
  108. Postcode: utils.TrimStr(req.Postcode),
  109. Remark: req.Remark,
  110. SellerRemark: req.SellerRemark, //销售备注
  111. TemplateId: req.TemplateId,
  112. SourceId: req.SourceId, //来源合同id
  113. ModifyTime: time.Now(),
  114. CreateTime: time.Now(),
  115. }
  116. contractServiceSlice, err := getContractServiceAndDetail(contractInfo.ProductId, req.Service, true)
  117. if err != nil {
  118. return
  119. }
  120. newContract, err = contract.AddContract(contractInfo, contractServiceSlice, req.RelationContractId)
  121. if err != nil {
  122. return
  123. }
  124. //添加操作日志
  125. remark := "新增合同模板"
  126. if newContract.SourceId > 0 {
  127. remark = "复制模板"
  128. }
  129. _ = contract.AddContractOperationRecord(newContract.ContractId, newContract.SellerId, 0, "add", newContract.SellerName, remark)
  130. return
  131. }
  132. // EditContract 编辑合同
  133. func EditContract(req request.EditContractReq, opUser *system.Admin) (newContract *contract.Contract, err error, errMsg string) {
  134. //查询当前合同信息
  135. nowContract, err := contract.GetContractById(req.ContractId)
  136. if err != nil {
  137. if err.Error() == utils.ErrNoRow() {
  138. err = errors.New(fmt.Sprint("根据合同编号:", req.ContractId, " 找不到初始合同"))
  139. }
  140. return
  141. }
  142. if nowContract.SellerId != opUser.AdminId {
  143. err = errors.New("当前账号无操作权限")
  144. return
  145. }
  146. ignoreStatus := []string{"待提交", "已撤回", "已驳回", "已审批"}
  147. if !strings.Contains(strings.Join(ignoreStatus, ","), nowContract.Status) {
  148. err = errors.New("合同状态异常,不允许修改,当前合同状态:" + nowContract.Status)
  149. return
  150. }
  151. originalPrice := req.OriginalPrice
  152. price := req.Price
  153. if originalPrice < 0 {
  154. err = errors.New("合同金额不能小于0")
  155. return
  156. }
  157. //如果优惠后金额小于等于0,那么就是等于优惠前的金额
  158. if price <= 0 {
  159. price = originalPrice
  160. }
  161. checkPrice := price //代付合同,需要检查的需要支付的余额
  162. // 是否更新业务合同金额
  163. updateBusinessContractPrice := 0.0
  164. if nowContract.Status == "已审批" && nowContract.ContractBusinessType == "代付合同" {
  165. updateBusinessContractPrice = nowContract.Price
  166. //因为当前代付合同是已审批的,所以修改重审的时候:
  167. //需要检查的需要支付的余额 = 当前提交的金额 - 之前提交的金额
  168. checkPrice = price - nowContract.Price
  169. }
  170. //合同日期
  171. var startDate, endDate time.Time
  172. if nowContract.ContractBusinessType == "代付合同" {
  173. businessContractInfo, tmpErr := contract.GetContractById(req.RelationContractId)
  174. if tmpErr != nil {
  175. err = tmpErr
  176. return
  177. }
  178. startDate = businessContractInfo.StartDate
  179. endDate = businessContractInfo.EndDate
  180. ok, tmpErr := CheckContractPrice(businessContractInfo, checkPrice)
  181. if tmpErr != nil {
  182. err = tmpErr
  183. return
  184. }
  185. if !ok {
  186. err = errors.New("合同金额异常,不能高于业务合同金额")
  187. errMsg = "合同金额异常,不能高于业务合同金额"
  188. return
  189. }
  190. } else {
  191. tmpStartDate, tmpErr := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  192. if tmpErr != nil {
  193. err = errors.New(fmt.Sprint("合同开始日期转换失败:", tmpErr))
  194. return
  195. }
  196. startDate = tmpStartDate
  197. tmpEndDate, tmpErr := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  198. if tmpErr != nil {
  199. err = errors.New(fmt.Sprint("合同结束日期转换失败:", tmpErr))
  200. return
  201. }
  202. endDate = tmpEndDate
  203. }
  204. companyName := utils.TrimStr(req.CompanyName)
  205. if companyName == "" {
  206. err = errors.New("客户名称必填")
  207. return
  208. }
  209. creditCode := utils.TrimStr(req.CreditCode)
  210. if companyName == "" {
  211. err = errors.New("社会统一信用代码必填")
  212. return
  213. }
  214. modifyContent := "" //变更记录
  215. nowContract.ContractType = req.ContractType //合同类型
  216. nowContract.StartDate = startDate //合同开始日期
  217. nowContract.EndDate = endDate //合同结束日期
  218. nowContract.OriginalPrice = originalPrice //原始金额
  219. nowContract.Price = price //优惠后的金额
  220. nowContract.PayRemark = utils.TrimStr(req.PayRemark) //付款方式说明,长度255位
  221. nowContract.PayChannel = utils.TrimStr(req.PayChannel) //付款渠道,长度255位
  222. nowContract.CompanyName = companyName //企业客户名称
  223. nowContract.CreditCode = creditCode //组织社会信用代码
  224. nowContract.ProvinceId = req.ProvinceId //省级id
  225. nowContract.Province = utils.TrimStr(req.Province) //省
  226. nowContract.CityId = req.CityId //市级id
  227. nowContract.City = utils.TrimStr(req.City) //市
  228. nowContract.Address = utils.TrimStr(req.Address) //详细地址
  229. nowContract.Fax = utils.TrimStr(req.Fax) //传真
  230. nowContract.Phone = utils.TrimStr(req.Phone) //电话
  231. nowContract.FileUrl = "" //修改合同后,需要移除原有的合同附件
  232. nowContract.Postcode = utils.TrimStr(req.Postcode) //邮编
  233. nowContract.Remark = req.Remark //补充说明
  234. nowContract.SellerRemark = req.SellerRemark //销售备注
  235. nowContract.ModifyTime = time.Now() //更新时间
  236. nowContract.Status = "待提交" //合同状态
  237. //获取服务信息
  238. contractServiceSlice, err := getContractServiceAndDetail(nowContract.ProductId, req.Service, true)
  239. if err != nil {
  240. return
  241. }
  242. //最近一次审批通过或者驳回的申请单
  243. lastContractApproval, err := contract.GetLastContractApprovalByContractIdAndStatus(nowContract.ContractId, "contract")
  244. if err != nil && err.Error() != utils.ErrNoRow() {
  245. return
  246. }
  247. //如果有申请记录,且申请单的状态是已审批,那么审核内容是:修改重审
  248. if lastContractApproval != nil {
  249. //旧的合同信息
  250. var snapshotContract contract.ContractDetail
  251. jsonErr := json.Unmarshal([]byte(lastContractApproval.ContractDetail), &snapshotContract)
  252. if jsonErr != nil {
  253. err = jsonErr
  254. return
  255. }
  256. //applyContent = "修改重审"
  257. modifyContentStrList := make([]string, 0)
  258. //客户信息
  259. updateCompanyInfoStrList := contrastCompanyInfo(snapshotContract, *nowContract)
  260. if len(updateCompanyInfoStrList) > 0 {
  261. updateCompanyInfoStr := ``
  262. if len(updateCompanyInfoStrList) == 1 {
  263. updateCompanyInfoStr = fmt.Sprint("客户信息发生了变化:" + updateCompanyInfoStrList[0])
  264. } else {
  265. updateCompanyInfoStr = fmt.Sprint("客户信息发生了变化:</n>", strings.Join(updateCompanyInfoStrList, "</n>"))
  266. }
  267. modifyContentStrList = append(modifyContentStrList, updateCompanyInfoStr)
  268. }
  269. //金额、付款、合同日期方式
  270. updatePayInfoStrList := contrastPayInfo(snapshotContract, *nowContract)
  271. modifyContentStrList = append(modifyContentStrList, updatePayInfoStrList...)
  272. if len(modifyContentStrList) > 0 {
  273. modifyContent = strings.Join(updatePayInfoStrList, "<br/>")
  274. }
  275. //服务内容
  276. updateServiceStr, tmpErr := contrastServiceInfo(snapshotContract, contractServiceSlice)
  277. if tmpErr != nil {
  278. err = tmpErr
  279. return
  280. }
  281. if updateServiceStr != "" {
  282. modifyContentStrList = append(modifyContentStrList, updateServiceStr)
  283. }
  284. //补充内容
  285. if nowContract.Remark != snapshotContract.Remark {
  286. snapshotContractRemark := snapshotContract.Remark
  287. if snapshotContractRemark == "" {
  288. snapshotContractRemark = "无"
  289. }
  290. nowContractRemark := nowContract.Remark
  291. if nowContractRemark == "" {
  292. nowContractRemark = "无"
  293. }
  294. updateStr := fmt.Sprint("原补充内容:", snapshotContractRemark, "</n>现补充内容:", nowContractRemark)
  295. modifyContentStrList = append(modifyContentStrList, updateStr)
  296. }
  297. if len(modifyContentStrList) > 0 {
  298. modifyContent = strings.Join(modifyContentStrList, "<br/>")
  299. }
  300. }
  301. nowContract.ModifyContent = modifyContent //修改信息
  302. updateDetailCol := []string{"ContractType", "StartDate", "EndDate", "OriginalPrice", "Price", "PayRemark", "PayChannel", "CompanyName", "CreditCode", "ProvinceId", "Province", "CityId", "City", "Address", "Fax", "Phone", "FileUrl", "Postcode", "Remark", "SellerRemark", "ModifyContent", "ModifyTime", "Status"}
  303. //修改合同
  304. err = contract.EditContract(nowContract, updateDetailCol, contractServiceSlice, req.RelationContractId)
  305. //添加操作日志
  306. remark := "编辑合同模板"
  307. _ = contract.AddContractOperationRecord(nowContract.ContractId, nowContract.SellerId, 0, "edit", nowContract.SellerName, remark)
  308. //修改业务合同的已支付金额
  309. if updateBusinessContractPrice > 0 {
  310. go updateContractPaidPriceByPaymentOnBehalfContractId(nowContract.ContractId, -nowContract.Price)
  311. }
  312. //赋值返回
  313. newContract = nowContract
  314. return
  315. }
  316. // contrastCompanyInfo 比对客户信息是否变更
  317. func contrastCompanyInfo(snapshotContract contract.ContractDetail, nowContract contract.Contract) (updateStrList []string) {
  318. //客户信息比对
  319. if nowContract.CompanyName != snapshotContract.CompanyName {
  320. updateStrList = append(updateStrList, fmt.Sprint("原客户名称:", snapshotContract.CompanyName, "</n>现客户名称:", nowContract.CompanyName))
  321. }
  322. if nowContract.CreditCode != snapshotContract.CreditCode {
  323. updateStrList = append(updateStrList, fmt.Sprint("原社会信用码:", snapshotContract.CreditCode, "</n>现社会信用码:", nowContract.CreditCode))
  324. }
  325. if nowContract.Province != snapshotContract.Province || nowContract.City != snapshotContract.City {
  326. updateStrList = append(updateStrList, fmt.Sprint("原公司地址:", snapshotContract.Province, snapshotContract.City, "</n>现公司地址:", nowContract.Province, nowContract.City))
  327. }
  328. if nowContract.Address != snapshotContract.Address {
  329. snapshotContractAddress := snapshotContract.Address
  330. if snapshotContractAddress == "" {
  331. snapshotContractAddress = `无`
  332. }
  333. nowContractAddress := nowContract.Address
  334. if nowContractAddress == "" {
  335. nowContractAddress = `无`
  336. }
  337. updateStrList = append(updateStrList, fmt.Sprint("原详细地址:", snapshotContractAddress, "</n>现详细地址:", nowContractAddress))
  338. }
  339. if nowContract.Fax != snapshotContract.Fax {
  340. snapshotContractFax := snapshotContract.Fax
  341. if snapshotContractFax == "" {
  342. snapshotContractFax = `无`
  343. }
  344. nowContractFax := nowContract.Fax
  345. if nowContractFax == "" {
  346. nowContractFax = `无`
  347. }
  348. updateStrList = append(updateStrList, fmt.Sprint("原传真:", snapshotContractFax, "</n>现传真:", nowContractFax))
  349. }
  350. if nowContract.Phone != snapshotContract.Phone {
  351. snapshotContractPhone := snapshotContract.Phone
  352. if snapshotContractPhone == "" {
  353. snapshotContractPhone = `无`
  354. }
  355. nowContractPhone := nowContract.Phone
  356. if nowContractPhone == "" {
  357. nowContractPhone = `无`
  358. }
  359. updateStrList = append(updateStrList, fmt.Sprint("原电话:", snapshotContractPhone, "</n>现电话:", nowContractPhone))
  360. }
  361. if nowContract.Postcode != snapshotContract.Postcode {
  362. snapshotContractPostcode := snapshotContract.Postcode
  363. if snapshotContractPostcode == "" {
  364. snapshotContractPostcode = `无`
  365. }
  366. nowContractPostcode := nowContract.Postcode
  367. if nowContractPostcode == "" {
  368. nowContractPostcode = `无`
  369. }
  370. updateStrList = append(updateStrList, fmt.Sprint("原邮编:", snapshotContractPostcode, "</n>现邮编:", nowContractPostcode))
  371. }
  372. return
  373. }
  374. // contrastPayInfo 比对合同金额、付款方式是否变更
  375. func contrastPayInfo(snapshotContract contract.ContractDetail, nowContract contract.Contract) (updateStrList []string) {
  376. //合同信息比对
  377. if nowContract.StartDate != snapshotContract.StartDate || nowContract.EndDate != snapshotContract.EndDate {
  378. updateStrList = append(updateStrList, fmt.Sprint("原合同期限:", snapshotContract.StartDate.Format(utils.FormatDate), " ~ ", snapshotContract.EndDate.Format(utils.FormatDate), "</n>现合同期限:", nowContract.StartDate.Format(utils.FormatDate), " ~ ", nowContract.EndDate.Format(utils.FormatDate)))
  379. }
  380. if nowContract.ContractBusinessType == "代付合同" {
  381. if nowContract.Price != snapshotContract.Price {
  382. updateStrList = append(updateStrList, fmt.Sprint("原代付金额:", decimal.NewFromFloat(snapshotContract.Price).String(), "</n>现代付金额:", decimal.NewFromFloat(nowContract.Price).String()))
  383. }
  384. } else {
  385. if nowContract.OriginalPrice != snapshotContract.OriginalPrice {
  386. updateStrList = append(updateStrList, fmt.Sprint("原合同金额:", decimal.NewFromFloat(snapshotContract.OriginalPrice).String(), "</n>现合同金额:", decimal.NewFromFloat(nowContract.OriginalPrice).String()))
  387. }
  388. if nowContract.Price != snapshotContract.Price {
  389. updateStrList = append(updateStrList, fmt.Sprint("原优惠后金额:", decimal.NewFromFloat(snapshotContract.Price).String(), "</n>现优惠后金额:", decimal.NewFromFloat(nowContract.Price).String()))
  390. }
  391. }
  392. if nowContract.PayRemark != snapshotContract.PayRemark {
  393. snapshotContractInfo := snapshotContract.PayRemark
  394. if snapshotContractInfo == "" {
  395. snapshotContractInfo = "无"
  396. }
  397. nowContractInfo := nowContract.PayRemark
  398. if nowContractInfo == "" {
  399. nowContractInfo = "无"
  400. }
  401. updateStrList = append(updateStrList, fmt.Sprint("原付款方式:", snapshotContractInfo, "</n>现付款方式:", nowContractInfo))
  402. }
  403. if nowContract.PayChannel != snapshotContract.PayChannel {
  404. snapshotContractInfo := snapshotContract.PayChannel
  405. if snapshotContractInfo == "" {
  406. snapshotContractInfo = "无"
  407. }
  408. nowContractInfo := nowContract.PayChannel
  409. if nowContractInfo == "" {
  410. nowContractInfo = "无"
  411. }
  412. updateStrList = append(updateStrList, fmt.Sprint("原付款方:", snapshotContractInfo, "</n>现付款方:", nowContractInfo))
  413. }
  414. return
  415. }
  416. // contrastServiceInfo 比对合同服务内容是否变更
  417. func contrastServiceInfo(snapshotContract contract.ContractDetail, contractServiceSlice []*contract.ContractServiceAndDetail) (updateStr string, err error) {
  418. serviceList := snapshotContract.Service
  419. nowServiceList := contractServiceSlice
  420. // CRM8.8-权益的合同服务主客观合并
  421. if snapshotContract.ProductId == 2 {
  422. updateStr = handleRaiContractModifyContentByServices(serviceList, nowServiceList)
  423. return
  424. }
  425. snapshotPermissionList, err := GetPermissionByContractService(snapshotContract.ProductId, serviceList)
  426. if err != nil {
  427. return
  428. }
  429. allPermissionMap := make(map[int]string)
  430. snapshotPermissionIdList := make([]int, 0)
  431. for _, permissionItem := range snapshotPermissionList {
  432. for _, permission := range permissionItem.Items {
  433. allPermissionMap[permission.ChartPermissionId] = permission.PermissionName
  434. if snapshotContract.ProductId == 2 {
  435. allPermissionMap[permission.ChartPermissionId] = permission.Remark
  436. }
  437. }
  438. snapshotPermissionIdList = append(snapshotPermissionIdList, permissionItem.CheckList...)
  439. }
  440. if len(snapshotPermissionIdList) > 0 {
  441. sort.Ints(snapshotPermissionIdList)
  442. }
  443. nowPermissionList, err := GetPermissionByContractService(snapshotContract.ProductId, nowServiceList)
  444. if err != nil {
  445. return
  446. }
  447. nowPermissionIdList := make([]int, 0)
  448. for _, permissionItem := range nowPermissionList {
  449. nowPermissionIdList = append(nowPermissionIdList, permissionItem.CheckList...)
  450. }
  451. if len(nowPermissionIdList) > 0 {
  452. sort.Ints(nowPermissionIdList)
  453. }
  454. //长度不等
  455. if len(snapshotPermissionIdList) != len(nowPermissionIdList) {
  456. goto FalseContrast
  457. }
  458. for i := 0; i < len(snapshotPermissionIdList); i++ {
  459. if snapshotPermissionIdList[i] != nowPermissionIdList[i] {
  460. //权限id不匹配
  461. goto FalseContrast
  462. }
  463. }
  464. return
  465. FalseContrast:
  466. snapshotContractServiceStrList := make([]string, 0)
  467. for _, id := range snapshotPermissionIdList {
  468. if permissionName, ok := allPermissionMap[id]; ok {
  469. snapshotContractServiceStrList = append(snapshotContractServiceStrList, permissionName)
  470. }
  471. }
  472. nowContractServiceStrList := make([]string, 0)
  473. for _, id := range nowPermissionIdList {
  474. if permissionName, ok := allPermissionMap[id]; ok {
  475. nowContractServiceStrList = append(nowContractServiceStrList, permissionName)
  476. }
  477. }
  478. snapshotContractServiceStr := `无`
  479. if len(snapshotContractServiceStrList) > 0 {
  480. snapshotContractServiceStr = strings.Join(snapshotContractServiceStrList, ",")
  481. }
  482. nowContractServiceStr := `无`
  483. if len(nowContractServiceStrList) > 0 {
  484. nowContractServiceStr = strings.Join(nowContractServiceStrList, ",")
  485. }
  486. updateStr = fmt.Sprint("原服务内容:", snapshotContractServiceStr, "</n>现服务内容:", nowContractServiceStr)
  487. return
  488. }
  489. // DeleteContract 删除合同
  490. func DeleteContract(contractId int, opUser *system.Admin) (err error) {
  491. //查询当前合同信息
  492. nowContract, err := contract.GetContractById(contractId)
  493. if err != nil {
  494. if err.Error() == utils.ErrNoRow() {
  495. err = errors.New(fmt.Sprint("根据合同编号:", contractId, " 找不到初始合同"))
  496. }
  497. return
  498. }
  499. if nowContract.SellerId != opUser.AdminId {
  500. err = errors.New("当前账号无操作权限")
  501. return
  502. }
  503. ignoreStatus := []string{"已审批", "待审批"}
  504. if strings.Contains(strings.Join(ignoreStatus, ","), nowContract.Status) {
  505. err = errors.New("合同状态异常,不允许删除,当前合同状态:" + nowContract.Status)
  506. return
  507. }
  508. //如果删除状态 >0,那么代表已经被删除了
  509. if nowContract.IsDelete > 0 {
  510. err = errors.New("该合同已删除")
  511. return
  512. }
  513. //假删除
  514. err = contract.DeleteContract(nowContract)
  515. if err != nil {
  516. return
  517. }
  518. //添加操作日志
  519. //remark := "编辑合同模板"
  520. //_ = contract.AddContractOperationRecord(nowContract.ContractId, nowContract.SellerId, 0, "edit", nowContract.SellerName, remark)
  521. return
  522. }
  523. // InvalidContract 作废合同
  524. func InvalidContract(contractId int, opUser *system.Admin) (err error) {
  525. //查询当前合同信息
  526. nowContract, err := contract.GetContractById(contractId)
  527. if err != nil {
  528. if err.Error() == utils.ErrNoRow() {
  529. err = errors.New(fmt.Sprint("根据合同编号:", contractId, " 找不到初始合同"))
  530. }
  531. return
  532. }
  533. if nowContract.SellerId != opUser.AdminId && opUser.RoleTypeCode != utils.ROLE_TYPE_CODE_COMPLIANCE {
  534. err = errors.New("当前账号无操作权限")
  535. return
  536. }
  537. if nowContract.Status != "已审批" {
  538. err = errors.New("合同状态异常,不允许作废,当前合同状态:" + nowContract.Status)
  539. return
  540. }
  541. //如果删除状态 >0,那么代表已经被删除了
  542. if nowContract.IsDelete > 0 {
  543. err = errors.New("该合同已删除")
  544. return
  545. }
  546. //合同作废
  547. err = contract.InvalidContract(nowContract)
  548. if err != nil {
  549. return
  550. }
  551. //添加操作日志
  552. remark := "作废合同模板"
  553. _ = contract.AddContractOperationRecord(nowContract.ContractId, opUser.AdminId, 0, "invalid", opUser.AdminName, remark)
  554. //修改业务合同的已支付金额
  555. if nowContract.ContractBusinessType == "代付合同" {
  556. go updateContractPaidPriceByPaymentOnBehalfContractId(nowContract.ContractId, -nowContract.Price)
  557. }
  558. return
  559. }
  560. // UploadFile 上传更新合同附件
  561. func UploadFile(contractId int, ext string, fileMulti multipart.File, opUser *system.Admin) (err error) {
  562. //获取合同信息
  563. contractInfo, err := contract.GetContractById(contractId)
  564. if err != nil {
  565. return
  566. }
  567. //合同状态判断
  568. if contractInfo.Status != "已审批" {
  569. err = errors.New("合同状态异常,不允许更新合同附件,当前合同状态:" + contractInfo.Status)
  570. return
  571. }
  572. if contractInfo.SellerId != opUser.AdminId {
  573. err = errors.New("合同异常,只允许本人更新合同附件")
  574. return
  575. }
  576. //保存的文件名
  577. fileName := contractInfo.CompanyName + "_" + contractInfo.ContractCode
  578. //非正式环境下,文件名上面还是加上随机数
  579. if utils.RunMode != "release" {
  580. fileName += "_" + utils.GetRandStringNoSpecialChar(10)
  581. }
  582. fileName += ext
  583. //上传到阿里云
  584. resourceUrl, err := services.UploadToOssAndFileName(fileMulti, fileName)
  585. if err != nil {
  586. err = errors.New("文件保存失败,Err:" + err.Error())
  587. return
  588. }
  589. contractInfo.FileUrl = resourceUrl
  590. contractInfo.ModifyTime = time.Now()
  591. err = contractInfo.Update([]string{"FileUrl", "ModifyTime"})
  592. if err != nil {
  593. return
  594. }
  595. //添加操作日志
  596. remark := "更新合同附件"
  597. _ = contract.AddContractOperationRecord(contractInfo.ContractId, opUser.AdminId, 0, "update_file", opUser.RealName, remark)
  598. return
  599. }
  600. // UploadCheckBackFile 上传签回合同附件
  601. func UploadCheckBackFile(contractId int, ext string, fileMulti multipart.File, opUser *system.Admin) (resourceUrl string, err error) {
  602. //获取合同信息
  603. contractInfo, err := contract.GetContractById(contractId)
  604. if err != nil {
  605. return
  606. }
  607. //合同状态判断
  608. if contractInfo.Status != "已审批" && contractInfo.Status != "已签回" {
  609. err = errors.New("合同状态异常,不允许上传签回合同附件,当前合同状态:" + contractInfo.Status)
  610. return
  611. }
  612. //保存的文件名
  613. fileName := contractInfo.CompanyName + "_" + contractInfo.ContractCode + "(签回)"
  614. //非正式环境下,文件名上面还是加上随机数
  615. if utils.RunMode != "release" {
  616. fileName += "_" + utils.GetRandStringNoSpecialChar(10)
  617. }
  618. fileName += ext
  619. //上传到阿里云
  620. resourceUrl, err = services.UploadToOssAndFileName(fileMulti, fileName)
  621. if err != nil {
  622. err = errors.New("文件保存失败,Err:" + err.Error())
  623. return
  624. }
  625. contractInfo.CheckBackFileUrl = resourceUrl
  626. contractInfo.Status = "已签回"
  627. contractInfo.ModifyTime = time.Now()
  628. contractInfo.CheckBackFileTime = time.Now()
  629. err = contractInfo.Update([]string{"CheckBackFileUrl", "Status", "ModifyTime", "CheckBackFileTime"})
  630. if err != nil {
  631. return
  632. }
  633. //同步更新客户那边提交审批的合同
  634. o := orm.NewOrm()
  635. sql := `update company_contract set img_url = ? where contract_code=? and source="系统合同" `
  636. _, err = o.Raw(sql, contractInfo.CheckBackFileUrl, contractInfo.ContractCode).Exec()
  637. //添加操作日志
  638. remark := "上传签回合同附件"
  639. _ = contract.AddContractOperationRecord(contractInfo.ContractId, opUser.AdminId, 0, "upload", opUser.RealName, remark)
  640. return
  641. }
  642. // UploadRescindFile 上传解约合同附件
  643. func UploadRescindFile(contractId int, ext string, fileMulti multipart.File, opUser *system.Admin) (err error) {
  644. //获取合同信息
  645. contractInfo, err := contract.GetContractById(contractId)
  646. if err != nil {
  647. return
  648. }
  649. //合同状态判断
  650. if contractInfo.Status != "已签回" {
  651. err = errors.New("合同状态异常,不允许上传解约合同附件,当前合同状态:" + contractInfo.Status)
  652. return
  653. }
  654. //保存的文件名
  655. fileName := contractInfo.CompanyName + "_" + contractInfo.ContractCode + "(解约)"
  656. //非正式环境下,文件名上面还是加上随机数
  657. if utils.RunMode != "release" {
  658. fileName += "_" + utils.GetRandStringNoSpecialChar(10)
  659. }
  660. fileName += ext
  661. //上传到阿里云
  662. resourceUrl, err := services.UploadToOssAndFileName(fileMulti, fileName)
  663. if err != nil {
  664. err = errors.New("文件保存失败,Err:" + err.Error())
  665. return
  666. }
  667. contractInfo.RescindFileUrl = resourceUrl
  668. contractInfo.Status = "已解约"
  669. contractInfo.ModifyTime = time.Now()
  670. contractInfo.RescindTime = time.Now()
  671. err = contractInfo.Update([]string{"RescindFileUrl", "Status", "ModifyTime", "RescindTime"})
  672. if err != nil {
  673. return
  674. }
  675. //添加操作日志
  676. remark := "上传解约合同附件"
  677. _ = contract.AddContractOperationRecord(contractInfo.ContractId, opUser.AdminId, 0, "rescind", opUser.RealName, remark)
  678. //修改业务合同的已支付金额
  679. if contractInfo.ContractBusinessType == "代付合同" {
  680. go updateContractPaidPriceByPaymentOnBehalfContractId(contractInfo.ContractId, -contractInfo.Price)
  681. }
  682. return
  683. }
  684. // 根据id获取合同详情(包含服务)
  685. func GetContractDetail(contractId int) (contractDetail *contract.ContractDetail, err error) {
  686. contractDetail, err = getContractDetail(contractId)
  687. if err != nil {
  688. if err.Error() == utils.ErrNoRow() {
  689. err = errors.New("找不到该合同")
  690. }
  691. return
  692. }
  693. relationContractDetailList := make([]*contract.ContractDetail, 0)
  694. switch contractDetail.ContractBusinessType {
  695. case "业务合同":
  696. tmpList, tmpErr := contract.GetContractRelationListByRelationContractId(contractDetail.ContractId)
  697. if tmpErr != nil {
  698. err = errors.New("查询业务关联合同异常:" + tmpErr.Error())
  699. return
  700. }
  701. //获取所有关联合同详情
  702. for _, relationContract := range tmpList {
  703. tmpContractDetail, tmpErr := getContractDetail(relationContract.PaymentOnBehalfContractId)
  704. if tmpErr != nil {
  705. err = errors.New("查询业务关联合同详情异常:" + tmpErr.Error())
  706. return
  707. }
  708. relationContractDetailList = append(relationContractDetailList, tmpContractDetail)
  709. }
  710. case "代付合同":
  711. tmpList, tmpErr := contract.GetContractRelationListByPaymentOnBehalfContractId(contractDetail.ContractId)
  712. if tmpErr != nil {
  713. err = errors.New("查询代付关联合同异常:" + tmpErr.Error())
  714. return
  715. }
  716. //获取所有关联合同详情
  717. for _, relationContract := range tmpList {
  718. tmpContractDetail, tmpErr := getContractDetail(relationContract.ContractId)
  719. if tmpErr != nil {
  720. err = errors.New("查询业务关联合同详情异常:" + tmpErr.Error())
  721. return
  722. }
  723. relationContractDetailList = append(relationContractDetailList, tmpContractDetail)
  724. }
  725. }
  726. contractDetail.RelationContractDetailList = relationContractDetailList
  727. return
  728. }
  729. // getContractDetail 根据id获取合同详情(包含服务)
  730. func getContractDetail(contractId int) (contractDetail *contract.ContractDetail, err error) {
  731. //获取合同基础信息详情
  732. contractDetail, err = contract.GetContractDetailById(contractId)
  733. if err != nil {
  734. if err.Error() == utils.ErrNoRow() {
  735. err = errors.New("找不到该合同")
  736. }
  737. return
  738. }
  739. //获取合同服务内容详情
  740. serviceList, err := getContractServiceAndDetailList(contractId)
  741. if err != nil {
  742. err = errors.New(fmt.Sprint("查找合同服务异常", err))
  743. return
  744. }
  745. contractDetail.Service = serviceList
  746. return
  747. }
  748. // getContractServiceAndDetailList 根据合同Id获取服务详情列表
  749. func getContractServiceAndDetailList(contractId int) (serviceList []*contract.ContractServiceAndDetail, err error) {
  750. serviceList, err = contract.GetContractServiceAndDetailList(contractId)
  751. if err != nil {
  752. err = errors.New(fmt.Sprint("查找合同服务异常", err))
  753. return
  754. }
  755. // 权益合同主客观合并
  756. //if mergeEquity && len(serviceList) > 0 && serviceList[0].ProductId == 2 {
  757. // mergeList, e := EquityMergeSubjectAndObject(serviceList)
  758. // if e != nil {
  759. // err = errors.New(fmt.Sprint("合并权益合同服务异常", err))
  760. // return
  761. // }
  762. // serviceList = mergeList
  763. //}
  764. newLen := len(serviceList)
  765. for i := 0; newLen > i; i++ {
  766. if serviceList[i].HasDetail == "是" {
  767. list, detailErr := contract.GetContractServiceDetailListByServiceId(serviceList[i].ContractServiceId)
  768. if detailErr != nil {
  769. err = errors.New(fmt.Sprint("查找合同服务详情异常", detailErr))
  770. return
  771. }
  772. serviceList[i].DetailList = list
  773. }
  774. }
  775. return
  776. }
  777. // GetContractDetailByAddContractReq 根据请求参数获取合同详情结构体数据
  778. func GetContractDetailByAddContractReq(req request.AddContractReq, sellerId, productId int, sellerName string) (contractDetail *contract.ContractDetail, err error) {
  779. originalPrice := req.OriginalPrice
  780. price := req.Price
  781. if originalPrice < 0 {
  782. err = errors.New("合同金额不能小于0")
  783. return
  784. }
  785. //如果优惠后金额小于等于0,那么就是等于优惠前的金额
  786. if price <= 0 {
  787. price = originalPrice
  788. }
  789. companyName := req.CompanyName
  790. if companyName == "" {
  791. err = errors.New("客户名称必填")
  792. return
  793. }
  794. creditCode := req.CreditCode
  795. if companyName == "" {
  796. err = errors.New("社会统一信用代码必填")
  797. return
  798. }
  799. contractCode, err := contract.GetCompanyContractCode(productId, req.ContractBusinessType)
  800. if err != nil {
  801. err = errors.New(fmt.Sprint("合同编号生成异常,Err:", err))
  802. return
  803. }
  804. //校验合同模板类型
  805. contractTemplate, err := contract.GetContractTemplateByTemplateId(req.TemplateId)
  806. if err != nil {
  807. return
  808. }
  809. if contractTemplate.ProductId != productId {
  810. err = errors.New("模板类型与当前账户类型不符")
  811. return
  812. }
  813. contractDetail = &contract.ContractDetail{
  814. ContractId: int(time.Now().Unix()),
  815. ContractCode: contractCode,
  816. SellerId: sellerId,
  817. SellerName: sellerName,
  818. ProductId: productId,
  819. ContractBusinessType: req.ContractBusinessType,
  820. ContractType: req.ContractType,
  821. Status: "待提交",
  822. OriginalPrice: originalPrice,
  823. Price: price,
  824. PayRemark: req.PayRemark, //付款方式说明,长度255位
  825. PayChannel: req.PayChannel, //付款渠道,长度255位
  826. CompanyName: companyName,
  827. CreditCode: creditCode,
  828. ProvinceId: req.ProvinceId,
  829. Province: req.Province,
  830. CityId: req.CityId,
  831. City: req.City,
  832. Address: req.Address,
  833. Fax: req.Fax,
  834. Phone: req.Phone,
  835. Postcode: req.Postcode,
  836. Remark: req.Remark,
  837. TemplateId: req.TemplateId,
  838. SourceId: req.SourceId, //来源合同id
  839. ModifyTime: time.Now(),
  840. CreateTime: time.Now(),
  841. }
  842. //合同日期
  843. if req.ContractBusinessType == "代付合同" {
  844. //关联合同
  845. relationContractDetailList := make([]*contract.ContractDetail, 0)
  846. tmpContractDetail, tmpErr := getContractDetail(req.RelationContractId)
  847. if tmpErr != nil {
  848. err = errors.New("查询业务关联合同详情异常:" + tmpErr.Error())
  849. return
  850. }
  851. relationContractDetailList = append(relationContractDetailList, tmpContractDetail)
  852. contractDetail.RelationContractDetailList = relationContractDetailList
  853. } else {
  854. tmpStartDate, tmpErr := time.Parse(utils.FormatDate, req.StartDate)
  855. if tmpErr != nil {
  856. err = errors.New(fmt.Sprint("合同开始日期转换失败:", tmpErr))
  857. return
  858. }
  859. contractDetail.StartDate = tmpStartDate
  860. tmpEndDate, tmpErr := time.Parse(utils.FormatDate, req.EndDate)
  861. if tmpErr != nil {
  862. err = errors.New(fmt.Sprint("合同结束日期转换失败:", tmpErr))
  863. return
  864. }
  865. contractDetail.EndDate = tmpEndDate
  866. contractServiceSlice, tmpErr := getContractServiceAndDetail(productId, req.Service, false)
  867. if tmpErr != nil {
  868. err = tmpErr
  869. return
  870. }
  871. contractDetail.Service = contractServiceSlice
  872. }
  873. return
  874. }
  875. // 根据请求数据获取套餐服务详情信息
  876. func getContractServiceAndDetail(productId int, reqService []request.AddContractServiceReq, base642Image bool) (contractServiceSlice []*contract.ContractServiceAndDetail, err error) {
  877. contractServiceSlice = make([]*contract.ContractServiceAndDetail, 0)
  878. if len(reqService) < 0 {
  879. err = errors.New("请至少选择一种套餐")
  880. return
  881. }
  882. for i := 0; i < len(reqService); i++ {
  883. item := reqService[i]
  884. detail := item.Detail
  885. contractServiceDetailSlice := make([]*contract.ContractServiceDetail, 0)
  886. if len(detail) > 0 {
  887. for j := 0; j < len(detail); j++ {
  888. detailItem := detail[j]
  889. cellMap := make(map[string]string)
  890. for k := 0; k < len(detailItem); k++ {
  891. key := fmt.Sprint("cell_", k+1)
  892. tmpVal, jsonErr := json.Marshal(detailItem[k])
  893. if jsonErr != nil {
  894. err = errors.New(fmt.Sprint("json转换失败:", jsonErr))
  895. return
  896. }
  897. cellMap[key] = string(tmpVal)
  898. }
  899. contractServiceDetail := &contract.ContractServiceDetail{
  900. Col1: func(cellMap map[string]string) string {
  901. tmpVal, ok := cellMap["cell_1"]
  902. if ok {
  903. return tmpVal
  904. } else {
  905. return ""
  906. }
  907. }(cellMap),
  908. Col2: func(cellMap map[string]string) string {
  909. tmpVal, ok := cellMap["cell_2"]
  910. if ok {
  911. return tmpVal
  912. } else {
  913. return ""
  914. }
  915. }(cellMap),
  916. Col3: func(cellMap map[string]string) string {
  917. tmpVal, ok := cellMap["cell_3"]
  918. if ok {
  919. return tmpVal
  920. } else {
  921. return ""
  922. }
  923. }(cellMap),
  924. Col4: func(cellMap map[string]string) string {
  925. tmpVal, ok := cellMap["cell_4"]
  926. if ok {
  927. return tmpVal
  928. } else {
  929. return ""
  930. }
  931. }(cellMap),
  932. Col5: func(cellMap map[string]string) string {
  933. tmpVal, ok := cellMap["cell_5"]
  934. if ok {
  935. return tmpVal
  936. } else {
  937. return ""
  938. }
  939. }(cellMap),
  940. Col6: func(cellMap map[string]string) string {
  941. tmpVal, ok := cellMap["cell_6"]
  942. if ok {
  943. return tmpVal
  944. } else {
  945. return ""
  946. }
  947. }(cellMap),
  948. Col7: func(cellMap map[string]string) string {
  949. tmpVal, ok := cellMap["cell_7"]
  950. if ok {
  951. return tmpVal
  952. } else {
  953. return ""
  954. }
  955. }(cellMap),
  956. ServiceTemplateId: item.ServiceTemplateId,
  957. CreateTime: time.Now(),
  958. }
  959. contractServiceDetailSlice = append(contractServiceDetailSlice, contractServiceDetail)
  960. }
  961. }
  962. hasDetail := "否"
  963. if len(contractServiceDetailSlice) > 0 {
  964. hasDetail = "是"
  965. }
  966. //报价单图片地址
  967. valueStr := item.Value
  968. if base642Image {
  969. b, _ := regexp.MatchString(`^data:\s*image\/(\w+);base64,`, valueStr)
  970. if b {
  971. imageUrl, uploadErr := UploadImageBase64(valueStr)
  972. if uploadErr != nil {
  973. err = errors.New(fmt.Sprint("base64图片上传失败:", uploadErr))
  974. return
  975. }
  976. valueStr = imageUrl
  977. }
  978. }
  979. //寻找该系统模板
  980. systemContractServiceTem, tmpErr := contract.GetContractServiceTemplateById(item.ServiceTemplateId)
  981. if tmpErr != nil {
  982. err = errors.New("找不到该模板")
  983. return
  984. }
  985. tmpContractService := &contract.ContractServiceAndDetail{
  986. ServiceTemplateId: item.ServiceTemplateId,
  987. Title: item.Title,
  988. Value: valueStr,
  989. ProductId: productId,
  990. //CreateTime: time.Now(),
  991. HasDetail: hasDetail,
  992. TableValue: systemContractServiceTem.TableValue,
  993. DetailList: contractServiceDetailSlice,
  994. ChartPermissionId: systemContractServiceTem.ChartPermissionId,
  995. }
  996. contractServiceSlice = append(contractServiceSlice, tmpContractService)
  997. }
  998. return
  999. }
  1000. // 获取品种列数据(因为前端可以随意插入列数据,所以需要根据列名来搜索对应的品种列)
  1001. func GetProductCelData(detail contract.ContractServiceDetail, tableCel *request.AddContractServiceDetailReq) (err error) {
  1002. t := reflect.TypeOf(detail)
  1003. v := reflect.ValueOf(detail)
  1004. for k := 0; k < t.NumField(); k++ {
  1005. //获取结构体的参数名
  1006. tmpName := t.Field(k).Name
  1007. if strings.Contains(tmpName, "Col") {
  1008. //获取结构体该参数名的值
  1009. tmpValue := v.Field(k).String()
  1010. //如果值不为空的话,那么做下json转换
  1011. if tmpValue != "" {
  1012. tmpErr := json.Unmarshal([]byte(tmpValue), tableCel)
  1013. if tmpErr != nil {
  1014. err = tmpErr
  1015. continue
  1016. }
  1017. if tableCel.HeadName == "品种" {
  1018. err = nil
  1019. return
  1020. }
  1021. }
  1022. }
  1023. }
  1024. return
  1025. }
  1026. // 将base64的图片上传至oss
  1027. func UploadImageBase64(base64Str string) (resourceUrl string, err error) {
  1028. ext := ".png"
  1029. uploadDir := "./static"
  1030. randStr := utils.GetRandStringNoSpecialChar(28)
  1031. fileName := randStr + ext
  1032. fpath := uploadDir + "/" + fileName
  1033. b, _ := regexp.MatchString(`^data:\s*image\/(\w+);base64,`, base64Str)
  1034. if !b {
  1035. err = errors.New("图片格式不正确")
  1036. return
  1037. }
  1038. re, _ := regexp.Compile(`^data:\s*image\/(\w+);base64,`)
  1039. base64Str = re.ReplaceAllString(base64Str, "")
  1040. base64Str = strings.Replace(base64Str, " ", "", -1)
  1041. base64Str = strings.Replace(base64Str, " ", "", -1)
  1042. //imgByte, err := base64.StdEncoding.DecodeString(base64Str)
  1043. //err=ioutil.WriteFile(fpath,imgByte,os.ModeAppend)
  1044. //if err!=nil {
  1045. // br.Msg = "图片保存失败"
  1046. // br.ErrMsg = "图片保存失败,Err:"+err.Error()
  1047. // return
  1048. //}
  1049. err = utils.SaveBase64ToFile(base64Str, fpath)
  1050. if err != nil {
  1051. return
  1052. }
  1053. fmt.Println("end")
  1054. defer os.Remove(fpath)
  1055. savePath := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  1056. savePath += fileName
  1057. //上传到阿里云
  1058. err = services.UploadVideoAliyun(fileName, fpath, savePath)
  1059. if err != nil {
  1060. return
  1061. }
  1062. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  1063. utils.FileLog.Info("end update oss ")
  1064. resourceUrl = utils.Imghost + savePath
  1065. item := new(models.Resource)
  1066. item.ResourceUrl = resourceUrl
  1067. item.ResourceType = 1
  1068. item.CreateTime = time.Now()
  1069. _, err = models.AddResource(item)
  1070. if err != nil {
  1071. return
  1072. }
  1073. return
  1074. }
  1075. // GetPermissionByContractService 通过合同服务,获取权限id列表
  1076. func GetPermissionByContractService(productId int, serviceList []*contract.ContractServiceAndDetail) (permissionList []*company.PermissionLookList, err error) {
  1077. //获取已经勾选的的权限
  1078. checkPermissionIdMap, err := GetServicePermissionMap(serviceList)
  1079. if err != nil {
  1080. return
  1081. }
  1082. permissionList, err = GetPermissionByPermissionIdMap(productId, checkPermissionIdMap)
  1083. return
  1084. }
  1085. // GetPermissionByPermissionIdMap 通过权限id的map,获取权限列表
  1086. func GetPermissionByPermissionIdMap(productId int, checkPermissionIdMap map[int]int) (permissionList []*company.PermissionLookList, err error) {
  1087. //子权限切片集合
  1088. allPermissions, err := company.GetPermissionLookItemsByProductId(productId)
  1089. if err != nil {
  1090. err = fmt.Errorf("获取权限失败,Err:%s", err.Error())
  1091. return
  1092. }
  1093. permissionMap := make(map[int][]*company.PermissionLookItem, 0)
  1094. for _, v := range allPermissions {
  1095. if v.ParentId > 0 {
  1096. permissionMap[v.ParentId] = append(permissionMap[v.ParentId], v)
  1097. }
  1098. }
  1099. //遍历获取
  1100. for _, v := range allPermissions {
  1101. if v.ParentId == 0 {
  1102. checkList := make([]int, 0)
  1103. plist := new(company.PermissionLookList)
  1104. plist.Items = make([]*company.PermissionLookItem, 0)
  1105. items, ok1 := permissionMap[v.ChartPermissionId]
  1106. if ok1 {
  1107. for _, n := range items {
  1108. if _, ok := checkPermissionIdMap[n.ChartPermissionId]; ok {
  1109. checkList = append(checkList, n.ChartPermissionId)
  1110. } else if _, ok2 := checkPermissionIdMap[n.ChartPermissionId+utils.PERMISSION_ID_UPGRADE]; ok2 {
  1111. checkList = append(checkList, n.ChartPermissionId)
  1112. n.IsUpgrade = 1
  1113. }
  1114. }
  1115. plist.Items = items
  1116. }
  1117. plist.ClassifyName = v.PermissionName
  1118. plist.CheckList = checkList
  1119. permissionList = append(permissionList, plist)
  1120. }
  1121. }
  1122. return
  1123. }
  1124. // GetServicePermissionMap 获取合同服务中的权限id map
  1125. func GetServicePermissionMap(serviceList []*contract.ContractServiceAndDetail) (checkPermissionIdMap map[int]int, err error) {
  1126. checkPermissionIdMap = make(map[int]int)
  1127. //获取已经勾选的的权限
  1128. for _, contractService := range serviceList {
  1129. //如果是权益,那么研选必要(2022-07-06 10:29:11移除)
  1130. //if contractService.ProductId == 2 {
  1131. // chartPermissionId := 31 //研选服务
  1132. // checkPermissionIdMap[chartPermissionId] = chartPermissionId
  1133. //}
  1134. //看看系统中有没有映射对应的权限,如果有的话,那么直接返回,没有那么可能是特殊服务,需要去遍历
  1135. if contractService.ChartPermissionId > 0 {
  1136. checkPermissionIdMap[contractService.ChartPermissionId] = contractService.ChartPermissionId
  1137. continue
  1138. }
  1139. switch contractService.ServiceTemplateId {
  1140. case 1: //ficc 大套餐
  1141. allFiccPermissions, e := company.GetPermissionLookItemsByProductId(utils.COMPANY_PRODUCT_FICC_ID)
  1142. if e != nil {
  1143. err = fmt.Errorf("获取权限失败 Err:%v", e)
  1144. return
  1145. }
  1146. permissionMap := make(map[int][]*company.PermissionLookItem, 0)
  1147. for _, v := range allFiccPermissions {
  1148. if v.ParentId > 0 {
  1149. permissionMap[v.ParentId] = append(permissionMap[v.ParentId], v)
  1150. }
  1151. }
  1152. for _, v := range allFiccPermissions {
  1153. if v.ParentId == 0 {
  1154. //合同这边市场策略不需要体现出来,所以调整返回
  1155. if v.PermissionName == "市场策略" {
  1156. continue
  1157. }
  1158. items, ok := permissionMap[v.ChartPermissionId]
  1159. if ok {
  1160. for _, n := range items {
  1161. checkPermissionIdMap[n.ChartPermissionId] = n.ChartPermissionId
  1162. }
  1163. }
  1164. }
  1165. }
  1166. case 2: //ficc小套餐
  1167. permissionValues := []string{
  1168. "FICC周报", "商品双周报+线上电话会讨论会<br/>(由弘则的研究员主持线上讨论)", "数据点评",
  1169. }
  1170. for _, detail := range contractService.DetailList {
  1171. var tableCel request.AddContractServiceDetailReq
  1172. tmpErr := json.Unmarshal([]byte(detail.Col1), &tableCel)
  1173. if tmpErr != nil {
  1174. err = tmpErr
  1175. return
  1176. }
  1177. if strings.Contains(strings.Join(permissionValues, ","), tableCel.Value) {
  1178. //获取品种列数据
  1179. var tableCel2 request.AddContractServiceDetailReq
  1180. tmpErr := GetProductCelData(*detail, &tableCel2)
  1181. if tmpErr != nil {
  1182. err = tmpErr
  1183. return
  1184. }
  1185. for _, serviceId := range tableCel2.ValueId {
  1186. checkPermissionIdMap[serviceId] = serviceId
  1187. }
  1188. }
  1189. }
  1190. case 4, 5, 6: //权益大套餐
  1191. permissionFiccClassifyArr := []string{"权益"}
  1192. for _, v := range permissionFiccClassifyArr {
  1193. items, tmpErr := company.GetPermissionLookItems(2, v)
  1194. if tmpErr != nil {
  1195. err = tmpErr
  1196. return
  1197. }
  1198. for _, n := range items {
  1199. //如果是专家行业,那么 结束当前循环,进入下一循环(产品需求:专家行业不在里面)
  1200. if n.ChartPermissionId == 29 || n.ChartPermissionId == 31 {
  1201. continue
  1202. }
  1203. checkPermissionIdMap[n.ChartPermissionId] = n.ChartPermissionId
  1204. }
  1205. }
  1206. }
  1207. }
  1208. return
  1209. }
  1210. // GetServicePackageType 获取合同服务中的 大小套餐类型
  1211. func GetServicePackageType(serviceList []*contract.ContractServiceAndDetail) (packageType int, err error) {
  1212. //获取已经勾选的的权限
  1213. for _, contractService := range serviceList {
  1214. switch contractService.ServiceTemplateId {
  1215. case 1: //ficc 大套餐
  1216. packageType = 1
  1217. case 2: //ficc小套餐
  1218. packageType = 2
  1219. case 4, 5, 6: //权益大套餐
  1220. //packageType = 1
  1221. }
  1222. }
  1223. return
  1224. }
  1225. // GetRaiServicePackageType 获取合同服务中的 权益的大小套餐类型
  1226. func GetRaiServicePackageType(serviceList []*contract.ContractServiceAndDetail) (raiPackageType int) {
  1227. for _, contractService := range serviceList {
  1228. switch contractService.ServiceTemplateId {
  1229. case 5: // 45w大套餐
  1230. raiPackageType = 2
  1231. case 6: // 70w大套餐
  1232. raiPackageType = 1
  1233. }
  1234. if raiPackageType > 0 {
  1235. break
  1236. }
  1237. }
  1238. return
  1239. }
  1240. // CheckContractPrice 校验代付合同金额是否 大于 业务合同金额(可能存在多份合同,需要遍历,如果大于的话,校验不通过,需要驳回)
  1241. func CheckContractPrice(contractInfo *contract.Contract, price float64) (ok bool, err error) {
  1242. list, err := contract.GetContractRelationListByContractId(contractInfo.ContractId)
  1243. if err != nil {
  1244. return
  1245. }
  1246. payedPrice := 0.0
  1247. for _, v := range list {
  1248. payedPrice += v.Price
  1249. }
  1250. if (contractInfo.Price - payedPrice) < price {
  1251. return
  1252. }
  1253. ok = true
  1254. return
  1255. }
  1256. // UploadCheckBackFileFromSeal 更新用印上传签回合同附件
  1257. func UploadCheckBackFileFromSeal(contractId int, fileUrl string, opUser *system.Admin) (err error) {
  1258. // 获取合同信息
  1259. contractInfo, err := contract.GetContractById(contractId)
  1260. if err != nil {
  1261. return
  1262. }
  1263. // 合同状态判断
  1264. if contractInfo.Status != "已审批" && contractInfo.Status != "已签回" {
  1265. err = errors.New("合同状态异常,不允许上传签回合同附件,当前合同状态:" + contractInfo.Status)
  1266. return
  1267. }
  1268. contractInfo.CheckBackFileUrl = fileUrl
  1269. contractInfo.Status = "已签回"
  1270. contractInfo.ModifyTime = time.Now()
  1271. contractInfo.CheckBackFileTime = time.Now()
  1272. err = contractInfo.Update([]string{"CheckBackFileUrl", "Status", "ModifyTime", "CheckBackFileTime"})
  1273. if err != nil {
  1274. return
  1275. }
  1276. // 同步更新客户那边提交审批的合同
  1277. o := orm.NewOrm()
  1278. sql := `update company_contract set img_url = ? where contract_code=? and source = "系统合同" `
  1279. _, err = o.Raw(sql, contractInfo.CheckBackFileUrl, contractInfo.ContractCode).Exec()
  1280. // 添加操作日志
  1281. remark := "上传签回合同附件"
  1282. _ = contract.AddContractOperationRecord(contractInfo.ContractId, opUser.AdminId, 0, "upload", opUser.RealName, remark)
  1283. return
  1284. }
  1285. //func init() {
  1286. // fmt.Println("contract init start")
  1287. // go FixEquityContractService()
  1288. // fmt.Println("contract init end")
  1289. //}
  1290. // FixEquityContractService 修复权益合同服务内容-CRM8.8
  1291. func FixEquityContractService() (err error) {
  1292. defer func() {
  1293. if err != nil {
  1294. fmt.Println("FixEquityContractService Err: " + err.Error())
  1295. }
  1296. }()
  1297. // 获取所有权益的合同(不考虑状态)
  1298. productId := 2
  1299. contractList, e := contract.GetContractListByProductId(productId)
  1300. if e != nil {
  1301. err = errors.New("获取权益合同列表失败")
  1302. return
  1303. }
  1304. contractLen := len(contractList)
  1305. if contractLen == 0 {
  1306. fmt.Println("无合同需要修复")
  1307. return
  1308. }
  1309. fmt.Println("待修复权益合同数", contractLen)
  1310. //return
  1311. // 合同IDs
  1312. contractIdArr := make([]string, 0)
  1313. contractIdServices := make(map[int][]*contract.ContractService, 0)
  1314. for i := 0; i < contractLen; i++ {
  1315. contractIdArr = append(contractIdArr, strconv.Itoa(contractList[i].ContractId))
  1316. newServices := make([]*contract.ContractService, 0)
  1317. contractIdServices[contractList[i].ContractId] = newServices
  1318. }
  1319. contractIds := strings.Join(contractIdArr, ",")
  1320. // 合同服务内容
  1321. serviceList, e := contract.GetContractServiceListByIds(contractIds)
  1322. if e != nil {
  1323. err = errors.New("获取权益合同服务内容列表失败")
  1324. return
  1325. }
  1326. servicesLen := len(serviceList)
  1327. if servicesLen == 0 {
  1328. fmt.Println("无合同服务需要修复")
  1329. return
  1330. }
  1331. for i := 0; i < servicesLen; i++ {
  1332. contractIdServices[serviceList[i].ContractId] = append(contractIdServices[serviceList[i].ContractId], serviceList[i])
  1333. }
  1334. // 服务套餐模板
  1335. templateList, e := contract.GetAllContractServiceTemplateList()
  1336. if e != nil {
  1337. err = errors.New("获取服务套餐模板列表失败")
  1338. return
  1339. }
  1340. // 主客观服务套餐
  1341. titleArr := []string{"医药", "消费", "科技", "智造"}
  1342. subTempMap := make(map[string]*contract.ContractServiceTemplate, 0)
  1343. objTempMap := make(map[string]*contract.ContractServiceTemplate, 0)
  1344. templateIdMap := make(map[int]*contract.ContractServiceTemplate, 0)
  1345. templateLen := len(templateList)
  1346. for i := 0; i < templateLen; i++ {
  1347. templateIdMap[templateList[i].ServiceTemplateId] = templateList[i]
  1348. }
  1349. for i := 0; i < templateLen; i++ {
  1350. if templateList[i].Title == "主观" {
  1351. parentTemp := templateIdMap[templateList[i].Pid]
  1352. subTempMap[parentTemp.Title] = templateList[i]
  1353. continue
  1354. }
  1355. if templateList[i].Title == "客观" {
  1356. parentTemp := templateIdMap[templateList[i].Pid]
  1357. objTempMap[parentTemp.Title] = templateList[i]
  1358. continue
  1359. }
  1360. }
  1361. // 遍历合同
  1362. for i := 0; i < contractLen; i++ {
  1363. contractId := contractList[i].ContractId
  1364. fmt.Printf("正在修复第%d个, 合同ID: %d\n", i+1, contractId)
  1365. // 合同服务内容
  1366. contractServices := contractIdServices[contractId]
  1367. insertArr := make([]*contract.ContractService, 0)
  1368. serviceLen := len(contractServices)
  1369. // 是否含有医药、消费、科技、智造
  1370. for _, v := range titleArr {
  1371. for ii := 0; ii < serviceLen; ii++ {
  1372. createTime := contractServices[ii].CreateTime
  1373. // 含有四种套餐之一
  1374. if contractServices[ii].Title == v {
  1375. template := templateIdMap[contractServices[ii].ServiceTemplateId]
  1376. pid := template.ServiceTemplateId
  1377. insertSubject := true
  1378. insertObject := true
  1379. // 去重, 校验是否已存在主客观
  1380. for iii := 0; iii < serviceLen; iii++ {
  1381. t := templateIdMap[contractServices[iii].ServiceTemplateId]
  1382. if t.Pid == pid && t.Title == "主观" {
  1383. insertSubject = false
  1384. continue
  1385. }
  1386. if t.Pid == pid && t.Title == "客观" {
  1387. insertObject = false
  1388. continue
  1389. }
  1390. }
  1391. if insertSubject {
  1392. subTemp := subTempMap[v]
  1393. title := v + "(" + subTemp.Title + ")"
  1394. insertArr = append(insertArr, &contract.ContractService{
  1395. ContractId: contractId,
  1396. ProductId: productId,
  1397. ServiceTemplateId: subTemp.ServiceTemplateId,
  1398. Title: title,
  1399. Value: subTemp.Value,
  1400. TableValue: subTemp.TableValue,
  1401. HasDetail: "否",
  1402. ChartPermissionId: subTemp.ChartPermissionId,
  1403. CreateTime: createTime,
  1404. })
  1405. }
  1406. if insertObject {
  1407. objTemp := objTempMap[v]
  1408. title := v + "(" + objTemp.Title + ")"
  1409. insertArr = append(insertArr, &contract.ContractService{
  1410. ContractId: contractId,
  1411. ProductId: productId,
  1412. ServiceTemplateId: objTemp.ServiceTemplateId,
  1413. Title: title,
  1414. Value: objTemp.Value,
  1415. TableValue: objTemp.TableValue,
  1416. HasDetail: "否",
  1417. ChartPermissionId: objTemp.ChartPermissionId,
  1418. CreateTime: createTime,
  1419. })
  1420. }
  1421. break
  1422. }
  1423. }
  1424. }
  1425. // 新增主客观
  1426. if len(insertArr) > 0 {
  1427. if e := contract.MultiCreateContractService(insertArr); e != nil {
  1428. fmt.Printf("第%d个修复失败, 合同ID: %d, Err: %s\n", i+1, contractId, e.Error())
  1429. return
  1430. }
  1431. fmt.Printf("第%d个修复成功, 合同ID: %d\n", i+1, contractId)
  1432. } else {
  1433. fmt.Printf("第%d个已修复过, 忽略合同ID: %d\n", i+1, contractId)
  1434. }
  1435. }
  1436. return
  1437. }
  1438. // CRM8.8-权益合同主客观套餐合并
  1439. func EquityMergeSubjectAndObject(serviceList []*contract.ContractServiceAndDetail) (mergeList []*contract.ContractServiceAndDetail) {
  1440. serviceLen := len(serviceList)
  1441. if serviceLen == 0 {
  1442. return serviceList
  1443. }
  1444. mergeArr := []string{"医药", "消费", "科技", "智造"}
  1445. // 获取模板列表
  1446. templateList, e := contract.GetAllContractServiceTemplateList()
  1447. if e != nil {
  1448. return serviceList
  1449. }
  1450. parentTempMap := make(map[string]int, 0)
  1451. templateMap := make(map[int]*contract.ContractServiceTemplate, 0)
  1452. for _, v := range templateList {
  1453. if utils.InArrayByStr(mergeArr, v.Title) {
  1454. parentTempMap[v.Title] = v.ServiceTemplateId
  1455. }
  1456. templateMap[v.ServiceTemplateId] = v
  1457. }
  1458. // 计算每个行业的子套餐数, 并判断所有套餐所属行业
  1459. countIndustryMap := make(map[string]int, 0)
  1460. serviceIndustryMap := make(map[int]string, 0)
  1461. industryServiceMap := make(map[string]*contract.ContractServiceAndDetail, 0)
  1462. childrenServiceMap := make(map[string]*contract.ContractServiceAndDetail, 0)
  1463. for i := 0; i < serviceLen; i++ {
  1464. temp := templateMap[serviceList[i].ServiceTemplateId]
  1465. if temp == nil {
  1466. continue
  1467. }
  1468. // 行业套餐
  1469. if utils.InArrayByStr(mergeArr, temp.Title) {
  1470. serviceIndustryMap[i] = temp.Title
  1471. industryServiceMap[temp.Title] = serviceList[i]
  1472. continue
  1473. }
  1474. // 主/客观
  1475. parentTemp := templateMap[temp.Pid]
  1476. if parentTemp != nil && utils.InArrayByStr(mergeArr, parentTemp.Title) {
  1477. countIndustryMap[parentTemp.Title] += 1
  1478. serviceIndustryMap[i] = parentTemp.Title
  1479. childrenServiceMap[parentTemp.Title] = serviceList[i]
  1480. }
  1481. }
  1482. mergeList = make([]*contract.ContractServiceAndDetail, 0)
  1483. // 遍历每一个套餐, 取出所属的行业, 不属于合并的行业则直接加入数组
  1484. // 属于合并的行业, 则校验行业子套餐数, 若子套餐数为1, 则取取主/客观套餐, 否则取行业套餐
  1485. mergeIndustryMap := make(map[string]int, 0)
  1486. for i := 0; i < serviceLen; i++ {
  1487. industryName := serviceIndustryMap[i]
  1488. // 不需要合并的行业
  1489. if industryName == "" {
  1490. mergeList = append(mergeList, serviceList[i])
  1491. continue
  1492. }
  1493. // 未合并则进行合并
  1494. if mergeIndustryMap[industryName] > 0 {
  1495. continue
  1496. }
  1497. count := countIndustryMap[industryName]
  1498. if count == 1 {
  1499. // 取主/客观套餐
  1500. mergeList = append(mergeList, childrenServiceMap[industryName])
  1501. } else {
  1502. // 0或者2都取行业套餐
  1503. mergeList = append(mergeList, industryServiceMap[industryName])
  1504. }
  1505. mergeIndustryMap[industryName] += 1
  1506. }
  1507. return
  1508. }
  1509. // CRM8.8-权益合同主客观权限的合并
  1510. func EquityMergeSubjectAndObjectPermission(list []*company.CompanyContractPermissionName) (newList []*company.CompanyContractPermissionName) {
  1511. if len(list) == 0 {
  1512. return list
  1513. }
  1514. // contractPermissionMap示例:
  1515. // map[
  1516. // 665:map[
  1517. // 专家:[0xc0002e24d0]
  1518. // 买方研选:[0xc0002e2630]
  1519. // 医药:[0xc0002e2370 0xc0002e28f0]
  1520. // 智造:[0xc0002e2160 0xc0002e26e0]
  1521. // 消费:[0xc0002e22c0 0xc0002e2840]
  1522. // 科技:[0xc0002e2210 0xc0002e2790]
  1523. // 策略:[0xc0002e2420]
  1524. // 路演服务:[0xc0002e2580]
  1525. // ]
  1526. // 666:map[
  1527. // 智造:[0xc0002e29a0 0xc0002e2b00]
  1528. // 科技:[0xc0002e2a50 0xc0002e2bb0]
  1529. // ]
  1530. // ]
  1531. contractPermissionMap := make(map[int]map[string][]*company.CompanyContractPermissionName)
  1532. for _, v := range list {
  1533. permissionMap, ok := contractPermissionMap[v.CompanyContractId]
  1534. if ok {
  1535. permissionItemMap, ok2 := permissionMap[v.ChartPermissionName]
  1536. if !ok2 {
  1537. permissionItemMap = make([]*company.CompanyContractPermissionName, 0)
  1538. }
  1539. permissionItemMap = append(permissionItemMap, v)
  1540. permissionMap[v.ChartPermissionName] = permissionItemMap
  1541. } else {
  1542. permissionMap = make(map[string][]*company.CompanyContractPermissionName)
  1543. permissionMap[v.ChartPermissionName] = append(permissionMap[v.ChartPermissionName], v)
  1544. }
  1545. contractPermissionMap[v.CompanyContractId] = permissionMap
  1546. }
  1547. newList = make([]*company.CompanyContractPermissionName, 0)
  1548. for _, v := range contractPermissionMap {
  1549. for _, p := range v {
  1550. if len(p) == 1 {
  1551. p[0].ChartPermissionName = p[0].PermissionRemark
  1552. }
  1553. newList = append(newList, p[0])
  1554. }
  1555. }
  1556. return
  1557. }
  1558. // HandleEquityPermissionLookList 权益-PermissionLookList主客观合并
  1559. func HandleEquityPermissionLookList(permissionLookList []*company.PermissionLookList) []*company.PermissionLookList {
  1560. if len(permissionLookList) == 0 {
  1561. return permissionLookList
  1562. }
  1563. checkList := permissionLookList[0].CheckList
  1564. permissionList := permissionLookList[0].Items
  1565. newPermissionList := HandleEquityPermissionLookItem(checkList, permissionList)
  1566. permissionLookList[0].Items = newPermissionList
  1567. return permissionLookList
  1568. }
  1569. // HandleEquityContractPermissionList 权益-ContractPermissionList主客观合并
  1570. func HandleEquityContractPermissionList(contractPermissionList []*company.ContractPermissionList) []*company.ContractPermissionList {
  1571. if len(contractPermissionList) == 0 {
  1572. return contractPermissionList
  1573. }
  1574. checkList := contractPermissionList[0].CheckList
  1575. permissionList := contractPermissionList[0].Items
  1576. newPermissionList := HandleEquityPermissionLookItem(checkList, permissionList)
  1577. contractPermissionList[0].Items = newPermissionList
  1578. return contractPermissionList
  1579. }
  1580. // HandleEquityPermissionLookItem 权益-权限展示的主客观合并处理
  1581. func HandleEquityPermissionLookItem(checkList []int, permissionList []*company.PermissionLookItem) (newPermissionList []*company.PermissionLookItem) {
  1582. permissionLen := len(permissionList)
  1583. if len(checkList) <= 0 || permissionLen <= 0 {
  1584. return permissionList
  1585. }
  1586. // 若某个行业的主客观权限均被满足,则只留其中一个权限
  1587. // 1.取出每个行业对应的其中一个权限
  1588. industryName := []string{"医药", "消费", "科技", "智造"}
  1589. namePermissionMap := make(map[string]*company.PermissionLookItem)
  1590. for i := 0; i < permissionLen; i++ {
  1591. pName := permissionList[i].PermissionName
  1592. if utils.InArrayByStr(industryName, pName) && namePermissionMap[pName] != nil {
  1593. namePermissionMap[pName] = permissionList[i]
  1594. }
  1595. }
  1596. // 2.计算哪些行业主客观权限都有
  1597. countIndustryMap := make(map[string]int, 0)
  1598. for i := 0; i < permissionLen; i++ {
  1599. p := permissionList[i]
  1600. if utils.InArrayByStr(industryName, p.PermissionName) && utils.InArrayByInt(checkList, p.ChartPermissionId) {
  1601. countIndustryMap[p.PermissionName] += 1
  1602. }
  1603. }
  1604. // 3.重新组成一个权限列表
  1605. mergeIndustryMap := make(map[string]int, 0)
  1606. newPermissionList = make([]*company.PermissionLookItem, 0)
  1607. for i := 0; i < permissionLen; i++ {
  1608. item := permissionList[i]
  1609. if utils.InArrayByStr(industryName, item.PermissionName) {
  1610. // 只有主客观之一, permissionName取remark
  1611. if countIndustryMap[item.PermissionName] == 1 {
  1612. // CRM13.2 标准合同新增升级套餐
  1613. if item.IsUpgrade == 1 {
  1614. item.PermissionName += "(升级)"
  1615. newPermissionList = append(newPermissionList, item)
  1616. } else {
  1617. item.PermissionName = item.Remark
  1618. newPermissionList = append(newPermissionList, item)
  1619. }
  1620. continue
  1621. }
  1622. // 主客观都有
  1623. if countIndustryMap[item.PermissionName] > 1 && mergeIndustryMap[item.PermissionName] == 0 {
  1624. mergeIndustryMap[item.PermissionName] += 1
  1625. // CRM13.2 标准合同新增升级套餐
  1626. if item.IsUpgrade == 1 {
  1627. item.PermissionName += "(升级)"
  1628. }
  1629. newPermissionList = append(newPermissionList, item)
  1630. }
  1631. } else {
  1632. newPermissionList = append(newPermissionList, item)
  1633. }
  1634. }
  1635. return
  1636. }
  1637. // handleRaiContractModifyContentByServices 权益合同-服务内容变更内容
  1638. func handleRaiContractModifyContentByServices(originService []*contract.ContractServiceAndDetail, newService []*contract.ContractServiceAndDetail) (tips string) {
  1639. if originService == nil || newService == nil {
  1640. return
  1641. }
  1642. oldArr := make([]string, 0)
  1643. newArr := make([]string, 0)
  1644. oldStr := "无"
  1645. newStr := "无"
  1646. o := EquityMergeSubjectAndObject(originService)
  1647. n := EquityMergeSubjectAndObject(newService)
  1648. for i := range o {
  1649. oldArr = append(oldArr, o[i].Title)
  1650. }
  1651. if len(oldArr) > 0 {
  1652. oldStr = strings.Join(oldArr, ",")
  1653. }
  1654. for i := range n {
  1655. newArr = append(newArr, n[i].Title)
  1656. }
  1657. if len(newArr) > 0 {
  1658. newStr = strings.Join(newArr, ",")
  1659. }
  1660. tips = fmt.Sprint("原服务内容:", oldStr, "</n>现服务内容:", newStr)
  1661. return
  1662. }
  1663. // 获取权益近一年是否有新签合同
  1664. func GetCompanyContractCountRaiByLastYear(companyId int, startDate string) (total int, err error) {
  1665. firstContractRai, err := company.GetFirstContractRai(companyId)
  1666. if err != nil && err.Error() != utils.ErrNoRow() {
  1667. return
  1668. }
  1669. //没有合同这第一份合同就属于新签合同
  1670. if firstContractRai == nil {
  1671. err = nil
  1672. total = 1
  1673. return
  1674. }
  1675. //判断是否是在一年以内
  1676. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  1677. startDateTime = startDateTime.AddDate(-1, 0, 0)
  1678. startDateTimeFirst, _ := time.Parse(utils.FormatDate, firstContractRai.StartDate)
  1679. if startDateTime.Before(startDateTimeFirst) {
  1680. total = 1
  1681. }
  1682. return
  1683. }
  1684. func initCRM15_5() {
  1685. var condition string
  1686. var pars []interface{}
  1687. condition = " AND rai_contract_type = '新签合同' AND product_id = 2 "
  1688. companyContractList, e := company.GetCompanyContractList(condition, pars)
  1689. if e != nil && e.Error() != utils.ErrNoRow() {
  1690. fmt.Println(e)
  1691. return
  1692. }
  1693. var CompanyContractIdS []int
  1694. for k, v := range companyContractList {
  1695. fmt.Println(k)
  1696. firstContractRai, err := company.GetFirstContractRai(v.CompanyId)
  1697. if err != nil {
  1698. fmt.Println(err)
  1699. continue
  1700. }
  1701. if firstContractRai.CompanyContractId == v.CompanyContractId {
  1702. continue
  1703. }
  1704. //判断是否是在一年以内
  1705. startDateTime, _ := time.Parse(utils.FormatDate, v.StartDate)
  1706. startDateTime = startDateTime.AddDate(-1, 0, 0)
  1707. startDateTimeFirst, _ := time.Parse(utils.FormatDate, firstContractRai.StartDate)
  1708. if !startDateTime.Before(startDateTimeFirst) {
  1709. CompanyContractIdS = append(CompanyContractIdS, v.CompanyContractId)
  1710. }
  1711. }
  1712. fmt.Println("companyContractIds", len(CompanyContractIdS))
  1713. fmt.Println("companyContractIds", (CompanyContractIdS))
  1714. //
  1715. //fmt.Println(strings.Join(companyContractIds, ","))
  1716. //err := company.UpdateCompanyContractRaiContractTypeInit(strings.Join(companyContractIds, ","))
  1717. //fmt.Println(err)
  1718. return
  1719. }