contract.go 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  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. permissionFilterrr := []string{"固收", "路演服务", "研选扣点包", "调研", "专家", "研选订阅"} //不在大套餐中展示的权益权限
  1193. for _, v := range permissionFiccClassifyArr {
  1194. items, tmpErr := company.GetPermissionLookItems(2, v)
  1195. if tmpErr != nil {
  1196. err = tmpErr
  1197. return
  1198. }
  1199. for _, n := range items {
  1200. //如果是专家行业,那么 结束当前循环,进入下一循环(产品需求:专家行业不在里面)
  1201. //if n.ChartPermissionId == 29 || n.ChartPermissionId == 31 {
  1202. // continue
  1203. //}
  1204. if utils.InArrayByStr(permissionFilterrr, n.PermissionName) {
  1205. continue
  1206. }
  1207. checkPermissionIdMap[n.ChartPermissionId] = n.ChartPermissionId
  1208. }
  1209. }
  1210. }
  1211. }
  1212. return
  1213. }
  1214. // GetServicePackageType 获取合同服务中的 大小套餐类型
  1215. func GetServicePackageType(serviceList []*contract.ContractServiceAndDetail) (packageType int, err error) {
  1216. //获取已经勾选的的权限
  1217. for _, contractService := range serviceList {
  1218. switch contractService.ServiceTemplateId {
  1219. case 1: //ficc 大套餐
  1220. packageType = 1
  1221. case 2: //ficc小套餐
  1222. packageType = 2
  1223. case 4, 5, 6: //权益大套餐
  1224. //packageType = 1
  1225. }
  1226. }
  1227. return
  1228. }
  1229. // GetRaiServicePackageType 获取合同服务中的 权益的大小套餐类型
  1230. func GetRaiServicePackageType(serviceList []*contract.ContractServiceAndDetail) (raiPackageType int) {
  1231. for _, contractService := range serviceList {
  1232. switch contractService.ServiceTemplateId {
  1233. case 5: // 45w大套餐
  1234. raiPackageType = 2
  1235. case 6: // 70w大套餐
  1236. raiPackageType = 1
  1237. }
  1238. if raiPackageType > 0 {
  1239. break
  1240. }
  1241. }
  1242. return
  1243. }
  1244. // CheckContractPrice 校验代付合同金额是否 大于 业务合同金额(可能存在多份合同,需要遍历,如果大于的话,校验不通过,需要驳回)
  1245. func CheckContractPrice(contractInfo *contract.Contract, price float64) (ok bool, err error) {
  1246. list, err := contract.GetContractRelationListByContractId(contractInfo.ContractId)
  1247. if err != nil {
  1248. return
  1249. }
  1250. payedPrice := 0.0
  1251. for _, v := range list {
  1252. payedPrice += v.Price
  1253. }
  1254. if (contractInfo.Price - payedPrice) < price {
  1255. return
  1256. }
  1257. ok = true
  1258. return
  1259. }
  1260. // UploadCheckBackFileFromSeal 更新用印上传签回合同附件
  1261. func UploadCheckBackFileFromSeal(contractId int, fileUrl string, opUser *system.Admin) (err error) {
  1262. // 获取合同信息
  1263. contractInfo, err := contract.GetContractById(contractId)
  1264. if err != nil {
  1265. return
  1266. }
  1267. // 合同状态判断
  1268. if contractInfo.Status != "已审批" && contractInfo.Status != "已签回" {
  1269. err = errors.New("合同状态异常,不允许上传签回合同附件,当前合同状态:" + contractInfo.Status)
  1270. return
  1271. }
  1272. contractInfo.CheckBackFileUrl = fileUrl
  1273. contractInfo.Status = "已签回"
  1274. contractInfo.ModifyTime = time.Now()
  1275. contractInfo.CheckBackFileTime = time.Now()
  1276. err = contractInfo.Update([]string{"CheckBackFileUrl", "Status", "ModifyTime", "CheckBackFileTime"})
  1277. if err != nil {
  1278. return
  1279. }
  1280. // 同步更新客户那边提交审批的合同
  1281. o := orm.NewOrm()
  1282. sql := `update company_contract set img_url = ? where contract_code=? and source = "系统合同" `
  1283. _, err = o.Raw(sql, contractInfo.CheckBackFileUrl, contractInfo.ContractCode).Exec()
  1284. // 添加操作日志
  1285. remark := "上传签回合同附件"
  1286. _ = contract.AddContractOperationRecord(contractInfo.ContractId, opUser.AdminId, 0, "upload", opUser.RealName, remark)
  1287. return
  1288. }
  1289. //func init() {
  1290. // fmt.Println("contract init start")
  1291. // go FixEquityContractService()
  1292. // fmt.Println("contract init end")
  1293. //}
  1294. // FixEquityContractService 修复权益合同服务内容-CRM8.8
  1295. func FixEquityContractService() (err error) {
  1296. defer func() {
  1297. if err != nil {
  1298. fmt.Println("FixEquityContractService Err: " + err.Error())
  1299. }
  1300. }()
  1301. // 获取所有权益的合同(不考虑状态)
  1302. productId := 2
  1303. contractList, e := contract.GetContractListByProductId(productId)
  1304. if e != nil {
  1305. err = errors.New("获取权益合同列表失败")
  1306. return
  1307. }
  1308. contractLen := len(contractList)
  1309. if contractLen == 0 {
  1310. fmt.Println("无合同需要修复")
  1311. return
  1312. }
  1313. fmt.Println("待修复权益合同数", contractLen)
  1314. //return
  1315. // 合同IDs
  1316. contractIdArr := make([]string, 0)
  1317. contractIdServices := make(map[int][]*contract.ContractService, 0)
  1318. for i := 0; i < contractLen; i++ {
  1319. contractIdArr = append(contractIdArr, strconv.Itoa(contractList[i].ContractId))
  1320. newServices := make([]*contract.ContractService, 0)
  1321. contractIdServices[contractList[i].ContractId] = newServices
  1322. }
  1323. contractIds := strings.Join(contractIdArr, ",")
  1324. // 合同服务内容
  1325. serviceList, e := contract.GetContractServiceListByIds(contractIds)
  1326. if e != nil {
  1327. err = errors.New("获取权益合同服务内容列表失败")
  1328. return
  1329. }
  1330. servicesLen := len(serviceList)
  1331. if servicesLen == 0 {
  1332. fmt.Println("无合同服务需要修复")
  1333. return
  1334. }
  1335. for i := 0; i < servicesLen; i++ {
  1336. contractIdServices[serviceList[i].ContractId] = append(contractIdServices[serviceList[i].ContractId], serviceList[i])
  1337. }
  1338. // 服务套餐模板
  1339. templateList, e := contract.GetAllContractServiceTemplateList()
  1340. if e != nil {
  1341. err = errors.New("获取服务套餐模板列表失败")
  1342. return
  1343. }
  1344. // 主客观服务套餐
  1345. titleArr := []string{"医药", "消费", "科技", "智造"}
  1346. subTempMap := make(map[string]*contract.ContractServiceTemplate, 0)
  1347. objTempMap := make(map[string]*contract.ContractServiceTemplate, 0)
  1348. templateIdMap := make(map[int]*contract.ContractServiceTemplate, 0)
  1349. templateLen := len(templateList)
  1350. for i := 0; i < templateLen; i++ {
  1351. templateIdMap[templateList[i].ServiceTemplateId] = templateList[i]
  1352. }
  1353. for i := 0; i < templateLen; i++ {
  1354. if templateList[i].Title == "主观" {
  1355. parentTemp := templateIdMap[templateList[i].Pid]
  1356. subTempMap[parentTemp.Title] = templateList[i]
  1357. continue
  1358. }
  1359. if templateList[i].Title == "客观" {
  1360. parentTemp := templateIdMap[templateList[i].Pid]
  1361. objTempMap[parentTemp.Title] = templateList[i]
  1362. continue
  1363. }
  1364. }
  1365. // 遍历合同
  1366. for i := 0; i < contractLen; i++ {
  1367. contractId := contractList[i].ContractId
  1368. fmt.Printf("正在修复第%d个, 合同ID: %d\n", i+1, contractId)
  1369. // 合同服务内容
  1370. contractServices := contractIdServices[contractId]
  1371. insertArr := make([]*contract.ContractService, 0)
  1372. serviceLen := len(contractServices)
  1373. // 是否含有医药、消费、科技、智造
  1374. for _, v := range titleArr {
  1375. for ii := 0; ii < serviceLen; ii++ {
  1376. createTime := contractServices[ii].CreateTime
  1377. // 含有四种套餐之一
  1378. if contractServices[ii].Title == v {
  1379. template := templateIdMap[contractServices[ii].ServiceTemplateId]
  1380. pid := template.ServiceTemplateId
  1381. insertSubject := true
  1382. insertObject := true
  1383. // 去重, 校验是否已存在主客观
  1384. for iii := 0; iii < serviceLen; iii++ {
  1385. t := templateIdMap[contractServices[iii].ServiceTemplateId]
  1386. if t.Pid == pid && t.Title == "主观" {
  1387. insertSubject = false
  1388. continue
  1389. }
  1390. if t.Pid == pid && t.Title == "客观" {
  1391. insertObject = false
  1392. continue
  1393. }
  1394. }
  1395. if insertSubject {
  1396. subTemp := subTempMap[v]
  1397. title := v + "(" + subTemp.Title + ")"
  1398. insertArr = append(insertArr, &contract.ContractService{
  1399. ContractId: contractId,
  1400. ProductId: productId,
  1401. ServiceTemplateId: subTemp.ServiceTemplateId,
  1402. Title: title,
  1403. Value: subTemp.Value,
  1404. TableValue: subTemp.TableValue,
  1405. HasDetail: "否",
  1406. ChartPermissionId: subTemp.ChartPermissionId,
  1407. CreateTime: createTime,
  1408. })
  1409. }
  1410. if insertObject {
  1411. objTemp := objTempMap[v]
  1412. title := v + "(" + objTemp.Title + ")"
  1413. insertArr = append(insertArr, &contract.ContractService{
  1414. ContractId: contractId,
  1415. ProductId: productId,
  1416. ServiceTemplateId: objTemp.ServiceTemplateId,
  1417. Title: title,
  1418. Value: objTemp.Value,
  1419. TableValue: objTemp.TableValue,
  1420. HasDetail: "否",
  1421. ChartPermissionId: objTemp.ChartPermissionId,
  1422. CreateTime: createTime,
  1423. })
  1424. }
  1425. break
  1426. }
  1427. }
  1428. }
  1429. // 新增主客观
  1430. if len(insertArr) > 0 {
  1431. if e := contract.MultiCreateContractService(insertArr); e != nil {
  1432. fmt.Printf("第%d个修复失败, 合同ID: %d, Err: %s\n", i+1, contractId, e.Error())
  1433. return
  1434. }
  1435. fmt.Printf("第%d个修复成功, 合同ID: %d\n", i+1, contractId)
  1436. } else {
  1437. fmt.Printf("第%d个已修复过, 忽略合同ID: %d\n", i+1, contractId)
  1438. }
  1439. }
  1440. return
  1441. }
  1442. // CRM8.8-权益合同主客观套餐合并
  1443. func EquityMergeSubjectAndObject(serviceList []*contract.ContractServiceAndDetail) (mergeList []*contract.ContractServiceAndDetail) {
  1444. serviceLen := len(serviceList)
  1445. if serviceLen == 0 {
  1446. return serviceList
  1447. }
  1448. mergeArr := []string{"医药", "消费", "科技", "智造"}
  1449. // 获取模板列表
  1450. templateList, e := contract.GetAllContractServiceTemplateList()
  1451. if e != nil {
  1452. return serviceList
  1453. }
  1454. parentTempMap := make(map[string]int, 0)
  1455. templateMap := make(map[int]*contract.ContractServiceTemplate, 0)
  1456. for _, v := range templateList {
  1457. if utils.InArrayByStr(mergeArr, v.Title) {
  1458. parentTempMap[v.Title] = v.ServiceTemplateId
  1459. }
  1460. templateMap[v.ServiceTemplateId] = v
  1461. }
  1462. // 计算每个行业的子套餐数, 并判断所有套餐所属行业
  1463. countIndustryMap := make(map[string]int, 0)
  1464. serviceIndustryMap := make(map[int]string, 0)
  1465. industryServiceMap := make(map[string]*contract.ContractServiceAndDetail, 0)
  1466. childrenServiceMap := make(map[string]*contract.ContractServiceAndDetail, 0)
  1467. for i := 0; i < serviceLen; i++ {
  1468. temp := templateMap[serviceList[i].ServiceTemplateId]
  1469. if temp == nil {
  1470. continue
  1471. }
  1472. // 行业套餐
  1473. if utils.InArrayByStr(mergeArr, temp.Title) {
  1474. serviceIndustryMap[i] = temp.Title
  1475. industryServiceMap[temp.Title] = serviceList[i]
  1476. continue
  1477. }
  1478. // 主/客观
  1479. parentTemp := templateMap[temp.Pid]
  1480. if parentTemp != nil && utils.InArrayByStr(mergeArr, parentTemp.Title) {
  1481. countIndustryMap[parentTemp.Title] += 1
  1482. serviceIndustryMap[i] = parentTemp.Title
  1483. childrenServiceMap[parentTemp.Title] = serviceList[i]
  1484. }
  1485. }
  1486. mergeList = make([]*contract.ContractServiceAndDetail, 0)
  1487. // 遍历每一个套餐, 取出所属的行业, 不属于合并的行业则直接加入数组
  1488. // 属于合并的行业, 则校验行业子套餐数, 若子套餐数为1, 则取取主/客观套餐, 否则取行业套餐
  1489. mergeIndustryMap := make(map[string]int, 0)
  1490. for i := 0; i < serviceLen; i++ {
  1491. industryName := serviceIndustryMap[i]
  1492. // 不需要合并的行业
  1493. if industryName == "" {
  1494. mergeList = append(mergeList, serviceList[i])
  1495. continue
  1496. }
  1497. // 未合并则进行合并
  1498. if mergeIndustryMap[industryName] > 0 {
  1499. continue
  1500. }
  1501. count := countIndustryMap[industryName]
  1502. if count == 1 {
  1503. // 取主/客观套餐
  1504. mergeList = append(mergeList, childrenServiceMap[industryName])
  1505. } else {
  1506. // 0或者2都取行业套餐
  1507. mergeList = append(mergeList, industryServiceMap[industryName])
  1508. }
  1509. mergeIndustryMap[industryName] += 1
  1510. }
  1511. return
  1512. }
  1513. // CRM8.8-权益合同主客观权限的合并
  1514. func EquityMergeSubjectAndObjectPermission(list []*company.CompanyContractPermissionName) (newList []*company.CompanyContractPermissionName) {
  1515. if len(list) == 0 {
  1516. return list
  1517. }
  1518. // contractPermissionMap示例:
  1519. // map[
  1520. // 665:map[
  1521. // 专家:[0xc0002e24d0]
  1522. // 买方研选:[0xc0002e2630]
  1523. // 医药:[0xc0002e2370 0xc0002e28f0]
  1524. // 智造:[0xc0002e2160 0xc0002e26e0]
  1525. // 消费:[0xc0002e22c0 0xc0002e2840]
  1526. // 科技:[0xc0002e2210 0xc0002e2790]
  1527. // 策略:[0xc0002e2420]
  1528. // 路演服务:[0xc0002e2580]
  1529. // ]
  1530. // 666:map[
  1531. // 智造:[0xc0002e29a0 0xc0002e2b00]
  1532. // 科技:[0xc0002e2a50 0xc0002e2bb0]
  1533. // ]
  1534. // ]
  1535. contractPermissionMap := make(map[int]map[string][]*company.CompanyContractPermissionName)
  1536. for _, v := range list {
  1537. permissionMap, ok := contractPermissionMap[v.CompanyContractId]
  1538. if ok {
  1539. permissionItemMap, ok2 := permissionMap[v.ChartPermissionName]
  1540. if !ok2 {
  1541. permissionItemMap = make([]*company.CompanyContractPermissionName, 0)
  1542. }
  1543. permissionItemMap = append(permissionItemMap, v)
  1544. permissionMap[v.ChartPermissionName] = permissionItemMap
  1545. } else {
  1546. permissionMap = make(map[string][]*company.CompanyContractPermissionName)
  1547. permissionMap[v.ChartPermissionName] = append(permissionMap[v.ChartPermissionName], v)
  1548. }
  1549. contractPermissionMap[v.CompanyContractId] = permissionMap
  1550. }
  1551. newList = make([]*company.CompanyContractPermissionName, 0)
  1552. for _, v := range contractPermissionMap {
  1553. for _, p := range v {
  1554. if len(p) == 1 {
  1555. p[0].ChartPermissionName = p[0].PermissionRemark
  1556. }
  1557. newList = append(newList, p[0])
  1558. }
  1559. }
  1560. return
  1561. }
  1562. // HandleEquityPermissionLookList 权益-PermissionLookList主客观合并
  1563. func HandleEquityPermissionLookList(permissionLookList []*company.PermissionLookList) []*company.PermissionLookList {
  1564. if len(permissionLookList) == 0 {
  1565. return permissionLookList
  1566. }
  1567. checkList := permissionLookList[0].CheckList
  1568. permissionList := permissionLookList[0].Items
  1569. newPermissionList := HandleEquityPermissionLookItem(checkList, permissionList)
  1570. permissionLookList[0].Items = newPermissionList
  1571. return permissionLookList
  1572. }
  1573. // HandleEquityContractPermissionList 权益-ContractPermissionList主客观合并
  1574. func HandleEquityContractPermissionList(contractPermissionList []*company.ContractPermissionList) []*company.ContractPermissionList {
  1575. if len(contractPermissionList) == 0 {
  1576. return contractPermissionList
  1577. }
  1578. checkList := contractPermissionList[0].CheckList
  1579. permissionList := contractPermissionList[0].Items
  1580. newPermissionList := HandleEquityPermissionLookItem(checkList, permissionList)
  1581. contractPermissionList[0].Items = newPermissionList
  1582. return contractPermissionList
  1583. }
  1584. // HandleEquityPermissionLookItem 权益-权限展示的主客观合并处理
  1585. func HandleEquityPermissionLookItem(checkList []int, permissionList []*company.PermissionLookItem) (newPermissionList []*company.PermissionLookItem) {
  1586. permissionLen := len(permissionList)
  1587. if len(checkList) <= 0 || permissionLen <= 0 {
  1588. return permissionList
  1589. }
  1590. // 若某个行业的主客观权限均被满足,则只留其中一个权限
  1591. // 1.取出每个行业对应的其中一个权限
  1592. industryName := []string{"医药", "消费", "科技", "智造"}
  1593. namePermissionMap := make(map[string]*company.PermissionLookItem)
  1594. for i := 0; i < permissionLen; i++ {
  1595. pName := permissionList[i].PermissionName
  1596. if utils.InArrayByStr(industryName, pName) && namePermissionMap[pName] != nil {
  1597. namePermissionMap[pName] = permissionList[i]
  1598. }
  1599. }
  1600. // 2.计算哪些行业主客观权限都有
  1601. countIndustryMap := make(map[string]int, 0)
  1602. for i := 0; i < permissionLen; i++ {
  1603. p := permissionList[i]
  1604. if utils.InArrayByStr(industryName, p.PermissionName) && utils.InArrayByInt(checkList, p.ChartPermissionId) {
  1605. countIndustryMap[p.PermissionName] += 1
  1606. }
  1607. }
  1608. // 3.重新组成一个权限列表
  1609. mergeIndustryMap := make(map[string]int, 0)
  1610. newPermissionList = make([]*company.PermissionLookItem, 0)
  1611. for i := 0; i < permissionLen; i++ {
  1612. item := permissionList[i]
  1613. if utils.InArrayByStr(industryName, item.PermissionName) {
  1614. // 只有主客观之一, permissionName取remark
  1615. if countIndustryMap[item.PermissionName] == 1 {
  1616. // CRM13.2 标准合同新增升级套餐
  1617. if item.IsUpgrade == 1 {
  1618. item.PermissionName += "(升级)"
  1619. newPermissionList = append(newPermissionList, item)
  1620. } else {
  1621. item.PermissionName = item.Remark
  1622. newPermissionList = append(newPermissionList, item)
  1623. }
  1624. continue
  1625. }
  1626. // 主客观都有
  1627. if countIndustryMap[item.PermissionName] > 1 && mergeIndustryMap[item.PermissionName] == 0 {
  1628. mergeIndustryMap[item.PermissionName] += 1
  1629. // CRM13.2 标准合同新增升级套餐
  1630. if item.IsUpgrade == 1 {
  1631. item.PermissionName += "(升级)"
  1632. }
  1633. newPermissionList = append(newPermissionList, item)
  1634. }
  1635. } else {
  1636. newPermissionList = append(newPermissionList, item)
  1637. }
  1638. }
  1639. return
  1640. }
  1641. // handleRaiContractModifyContentByServices 权益合同-服务内容变更内容
  1642. func handleRaiContractModifyContentByServices(originService []*contract.ContractServiceAndDetail, newService []*contract.ContractServiceAndDetail) (tips string) {
  1643. if originService == nil || newService == nil {
  1644. return
  1645. }
  1646. oldArr := make([]string, 0)
  1647. newArr := make([]string, 0)
  1648. oldStr := "无"
  1649. newStr := "无"
  1650. o := EquityMergeSubjectAndObject(originService)
  1651. n := EquityMergeSubjectAndObject(newService)
  1652. for i := range o {
  1653. oldArr = append(oldArr, o[i].Title)
  1654. }
  1655. if len(oldArr) > 0 {
  1656. oldStr = strings.Join(oldArr, ",")
  1657. }
  1658. for i := range n {
  1659. newArr = append(newArr, n[i].Title)
  1660. }
  1661. if len(newArr) > 0 {
  1662. newStr = strings.Join(newArr, ",")
  1663. }
  1664. tips = fmt.Sprint("原服务内容:", oldStr, "</n>现服务内容:", newStr)
  1665. return
  1666. }
  1667. // 获取权益近一年是否有新签合同
  1668. func GetCompanyContractCountRaiByLastYear(companyId int, startDate string) (total int, err error) {
  1669. firstContractRai, err := company.GetFirstContractRai(companyId)
  1670. if err != nil && err.Error() != utils.ErrNoRow() {
  1671. return
  1672. }
  1673. //没有合同这第一份合同就属于新签合同
  1674. if firstContractRai == nil {
  1675. err = nil
  1676. total = 1
  1677. return
  1678. }
  1679. //判断是否是在一年以内
  1680. startDateTime, _ := time.Parse(utils.FormatDate, startDate)
  1681. startDateTime = startDateTime.AddDate(-1, 0, 0)
  1682. startDateTimeFirst, _ := time.Parse(utils.FormatDate, firstContractRai.StartDate)
  1683. if startDateTime.Before(startDateTimeFirst) {
  1684. total = 1
  1685. }
  1686. return
  1687. }
  1688. func initCRM15_5() {
  1689. var condition string
  1690. var pars []interface{}
  1691. condition = " AND rai_contract_type = '新签合同' AND product_id = 2 "
  1692. companyContractList, e := company.GetCompanyContractList(condition, pars)
  1693. if e != nil && e.Error() != utils.ErrNoRow() {
  1694. fmt.Println(e)
  1695. return
  1696. }
  1697. var CompanyContractIdS []int
  1698. for k, v := range companyContractList {
  1699. fmt.Println(k)
  1700. firstContractRai, err := company.GetFirstContractRai(v.CompanyId)
  1701. if err != nil {
  1702. fmt.Println(err)
  1703. continue
  1704. }
  1705. if firstContractRai.CompanyContractId == v.CompanyContractId {
  1706. continue
  1707. }
  1708. //判断是否是在一年以内
  1709. startDateTime, _ := time.Parse(utils.FormatDate, v.StartDate)
  1710. startDateTime = startDateTime.AddDate(-1, 0, 0)
  1711. startDateTimeFirst, _ := time.Parse(utils.FormatDate, firstContractRai.StartDate)
  1712. if !startDateTime.Before(startDateTimeFirst) {
  1713. CompanyContractIdS = append(CompanyContractIdS, v.CompanyContractId)
  1714. }
  1715. }
  1716. fmt.Println("companyContractIds", len(CompanyContractIdS))
  1717. fmt.Println("companyContractIds", (CompanyContractIdS))
  1718. //
  1719. //fmt.Println(strings.Join(companyContractIds, ","))
  1720. //err := company.UpdateCompanyContractRaiContractTypeInit(strings.Join(companyContractIds, ","))
  1721. //fmt.Println(err)
  1722. return
  1723. }