register.go 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937
  1. package contract
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "github.com/go-playground/validator/v10"
  8. "github.com/shopspring/decimal"
  9. "github.com/tealeg/xlsx"
  10. "hongze/fms_api/controller/resp"
  11. "hongze/fms_api/global"
  12. "hongze/fms_api/models/base"
  13. "hongze/fms_api/models/crm"
  14. "hongze/fms_api/models/fms"
  15. "hongze/fms_api/models/system"
  16. "hongze/fms_api/services/alarm_msg"
  17. crmService "hongze/fms_api/services/crm"
  18. fmsService "hongze/fms_api/services/fms"
  19. "hongze/fms_api/utils"
  20. "net/http"
  21. "os"
  22. "path"
  23. "strconv"
  24. "strings"
  25. "time"
  26. )
  27. // RegisterController 合同登记
  28. type RegisterController struct{}
  29. // List
  30. // @Title 合同登记列表
  31. // @Description 合同登记列表
  32. // @Param Keyword query string false "关键词"
  33. // @Param StartDate query string false "合同开始日期"
  34. // @Param EndDate query string false "合同结束日期"
  35. // @Param ServiceType query int false "套餐类型"
  36. // @Param ContractType query int false "合同类型"
  37. // @Param RegisterStatus query int false "登记状态"
  38. // @Success 200 {object} fms.ContractRegisterItem
  39. // @router /contract/register/list [get]
  40. func (rg *RegisterController) List(c *gin.Context) {
  41. var req fms.ContractRegisterListReq
  42. if e := c.BindQuery(&req); e != nil {
  43. err, ok := e.(validator.ValidationErrors)
  44. if !ok {
  45. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  46. return
  47. }
  48. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  49. return
  50. }
  51. cond := `1 = 1`
  52. pars := make([]interface{}, 0)
  53. // 合同编号/客户姓名/销售/实际使用方
  54. if req.Keyword != "" {
  55. kw := "%" + req.Keyword + "%"
  56. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR rai_seller_name LIKE ? OR actual_company_name LIKE ?)`
  57. pars = append(pars, kw, kw, kw, kw, kw)
  58. }
  59. if req.StartDate != "" && req.EndDate != "" {
  60. st := fmt.Sprint(req.StartDate, " 00:00:00")
  61. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  62. cond += ` AND (create_time BETWEEN ? AND ?)`
  63. pars = append(pars, st, ed)
  64. }
  65. if req.ContractType != 0 {
  66. cond += ` AND contract_type = ?`
  67. pars = append(pars, req.ContractType)
  68. }
  69. if req.RegisterStatus != 0 {
  70. cond += ` AND register_status = ?`
  71. pars = append(pars, req.RegisterStatus)
  72. }
  73. // 套餐筛选
  74. if req.ServiceTypes != "" {
  75. serviceTypes := strings.Split(req.ServiceTypes, ",")
  76. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  77. if e != nil {
  78. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  79. return
  80. }
  81. if len(registerIds) > 0 {
  82. cond += ` AND contract_register_id IN ?`
  83. pars = append(pars, registerIds)
  84. } else {
  85. cond += ` AND 1 = 2`
  86. }
  87. }
  88. page := new(base.Page)
  89. page.SetPageSize(req.PageSize)
  90. page.SetCurrent(req.Current)
  91. page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
  92. total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
  93. if e != nil {
  94. resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
  95. return
  96. }
  97. registerIds := make([]int, 0)
  98. for i := range list {
  99. registerIds = append(registerIds, list[i].ContractRegisterId)
  100. }
  101. serviceMap := make(map[int]string, 0)
  102. invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  103. paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  104. if len(registerIds) > 0 {
  105. // 获取所有的服务套餐
  106. serviceMap, _, e = fmsService.GetContractServiceNameFormat(registerIds)
  107. if e != nil {
  108. resp.FailMsg("获取失败", e.Error(), c)
  109. return
  110. }
  111. // 获取开票/到款列表
  112. invoiceCond := `contract_register_id IN ?`
  113. invoicePars := make([]interface{}, 0)
  114. invoicePars = append(invoicePars, registerIds)
  115. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  116. if e != nil {
  117. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  118. return
  119. }
  120. for i := range invoiceList {
  121. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  122. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  123. }
  124. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  125. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  126. }
  127. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  128. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  129. }
  130. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  131. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  132. }
  133. }
  134. }
  135. respList := make([]*fms.ContractRegisterList, 0)
  136. for i := range list {
  137. v := new(fms.ContractRegisterList)
  138. v.ContractRegisterItem = list[i]
  139. v.ServicesName = serviceMap[list[i].ContractRegisterId]
  140. v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
  141. v.PaymentList = paymentMap[list[i].ContractRegisterId]
  142. respList = append(respList, v)
  143. }
  144. page.SetTotal(total)
  145. baseData := new(base.BaseData)
  146. baseData.SetPage(page)
  147. baseData.SetList(respList)
  148. resp.OkData("获取成功", baseData, c)
  149. }
  150. // Add
  151. // @Title 新增合同登记
  152. // @Description 新增合同登记
  153. // @Param request body fms.ContractRegisterAddReq true "type json string"
  154. // @Success 200 string "操作成功"
  155. // @router /contract/register/add [post]
  156. func (rg *RegisterController) Add(c *gin.Context) {
  157. req := new(fms.ContractRegisterAddReq)
  158. err := c.ShouldBind(&req)
  159. if err != nil {
  160. errs, ok := err.(validator.ValidationErrors)
  161. if !ok {
  162. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  163. return
  164. }
  165. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  166. return
  167. }
  168. claims, _ := c.Get("adminInfo")
  169. adminInfo := claims.(*system.SysAdmin)
  170. // 日期校验
  171. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  172. if e != nil {
  173. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  174. return
  175. }
  176. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  177. if e != nil {
  178. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  179. return
  180. }
  181. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  182. if req.SignDate != "" {
  183. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  184. if e != nil {
  185. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  186. return
  187. }
  188. signDate = signDateTime
  189. }
  190. // 是否存在相同合同编号的登记
  191. ob := new(fms.ContractRegister)
  192. existCond := `contract_code = ?`
  193. existPars := make([]interface{}, 0)
  194. existPars = append(existPars, req.ContractCode)
  195. exist, e := ob.FetchByCondition(existCond, existPars)
  196. if e != nil && e != utils.ErrNoRow {
  197. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  198. return
  199. }
  200. if exist != nil && exist.ContractRegisterId > 0 {
  201. resp.Fail("合同编号已存在", c)
  202. return
  203. }
  204. // 货币及汇率
  205. rateList, e := fmsService.GetTodayCurrencyRateList()
  206. if e != nil {
  207. resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), c)
  208. return
  209. }
  210. var rate float64
  211. for i := range rateList {
  212. if req.CurrencyUnit == rateList[i].Code {
  213. rate = rateList[i].RMBRate
  214. break
  215. }
  216. }
  217. if rate <= 0 {
  218. resp.FailMsg("操作失败", "货币汇率信息有误", c)
  219. return
  220. }
  221. // 查询销售信息
  222. var (
  223. sellerId int
  224. raiSellerId int
  225. sellerName string
  226. raiSellerName string
  227. )
  228. if req.SellerIds != "" {
  229. admin := new(crm.Admin)
  230. sellerIds := strings.Split(req.SellerIds, ",")
  231. if len(sellerIds) > 2 {
  232. resp.Fail("最多只能选择两个销售", c)
  233. return
  234. }
  235. var pars []interface{}
  236. cond := ` admin_id in (?) `
  237. pars = append(pars, sellerIds)
  238. sellers, e := admin.List(cond, pars)
  239. if e != nil {
  240. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  241. return
  242. }
  243. for _, v := range sellers {
  244. if v.DepartmentId == crm.SellerDepartmentId {
  245. sellerId = v.AdminId
  246. sellerName = v.AdminName
  247. }else if v.DepartmentId == crm.RaiSellerDepartmentId {
  248. raiSellerId = v.AdminId
  249. raiSellerName = v.AdminName
  250. }
  251. }
  252. }
  253. //新老客户判断
  254. /*newCompany := req.NewCompany
  255. if req.ContractType == 1 {
  256. newCompany = 1
  257. }else if req.ContractType == 2 || req.ContractType == 3 {
  258. newCompany = 0
  259. }
  260. if newCompany != req.NewCompany {
  261. resp.Fail("请输入正确的客户类型", c)
  262. return
  263. }*/
  264. nowTime := time.Now().Local()
  265. ob.ContractCode = req.ContractCode
  266. ob.RelateContractCode = req.RelateContractCode
  267. ob.CrmContractId = req.CrmContractId
  268. ob.ContractSource = req.ContractSource
  269. ob.CompanyName = req.CompanyName
  270. ob.ActualCompanyName = req.ActualCompanyName
  271. ob.ProductIds = req.ProductIds
  272. ob.SellerId = sellerId
  273. ob.SellerName = sellerName
  274. ob.RaiSellerId = raiSellerId
  275. ob.RaiSellerName = raiSellerName
  276. ob.ContractType = req.ContractType
  277. ob.ContractAmount = req.ContractAmount
  278. ob.CurrencyUnit = req.CurrencyUnit
  279. ob.RMBRate = rate
  280. ob.StartDate = startDate
  281. ob.EndDate = endDate
  282. ob.SignDate = signDate
  283. ob.AgreedPayTime = req.AgreedPayTime
  284. ob.ContractStatus = req.ContractStatus
  285. ob.RegisterStatus = fms.ContractRegisterStatusIng
  286. ob.Remark = req.Remark
  287. ob.ServiceRemark = req.ServiceRemark
  288. ob.HasPayment = req.HasPayment
  289. ob.NewCompany = req.NewCompany
  290. ob.Set()
  291. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  292. if req.HasPayment == 1 || req.ContractStatus == fms.ContractStatusEnd {
  293. ob.RegisterStatus = fms.ContractRegisterStatusComplete
  294. }
  295. // 新增套餐金额详情内容
  296. serviceAmountMap := make(map[int]float64)
  297. serviceAmountList, e := fmsService.HandleContractServiceAmount(req.ServiceAmount, serviceAmountMap, req.CurrencyUnit)
  298. if e != nil {
  299. resp.FailMsg("操作失败", "新增合同套餐金额信息失败, Err: "+e.Error(), c)
  300. return
  301. }
  302. //判断产品信息
  303. productIds := make(map[int]struct{})
  304. productIdsStr := ""
  305. for _, v := range serviceAmountList {
  306. productIds[v.ProductId] = struct{}{}
  307. }
  308. for proId, _ := range productIds {
  309. productIdsStr += strconv.Itoa(proId)+","
  310. }
  311. productIdsStr = strings.Trim(productIdsStr, ",")
  312. ob.ProductIds = productIdsStr
  313. // 套餐信息
  314. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  315. if e != nil {
  316. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  317. return
  318. }
  319. // 新增合同及套餐
  320. if req.Supplement == 1 {
  321. //新增到款信息
  322. if ob.HasPayment == 1 {
  323. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  324. return
  325. }
  326. //新增合同信息
  327. if e = fms.CreateContractRegisterAndServicesAndPayMent(ob, serviceList, req.PrePayId); e != nil {
  328. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  329. return
  330. }
  331. prePayOB := new(fms.ContractPrePayment)
  332. ppItem, e := prePayOB.Fetch(req.PrePayId)
  333. if e != nil {
  334. if e == utils.ErrNoRow {
  335. resp.Fail("预到款不存在或已被删除", c)
  336. return
  337. }
  338. resp.FailMsg("获取预到款记录失败", "Err:"+e.Error(), c)
  339. return
  340. }
  341. // 合同有效时长(计算付款方式)
  342. dayDiff := ob.EndDate.Sub(ob.StartDate).Hours() / 24
  343. // 获取销售分组信息
  344. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  345. if e != nil {
  346. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  347. return
  348. }
  349. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  350. for i := range sellerList {
  351. sellerMap[sellerList[i].SellerId] = sellerList[i]
  352. }
  353. v := &fms.ContractInvoice{
  354. ContractRegisterId: ob.ContractRegisterId,
  355. ContractCode: ob.ContractCode,
  356. Amount: ppItem.Amount,
  357. OriginAmount: ppItem.OriginAmount,
  358. CurrencyUnit: ppItem.CurrencyUnit,
  359. InvoiceType: fms.ContractInvoiceTypePay,
  360. InvoiceDate: ppItem.CreateTime,
  361. AdminId: int(adminInfo.AdminId),
  362. AdminName: adminInfo.RealName,
  363. Remark: ppItem.Remark,
  364. IsPrePay: 1,
  365. }
  366. v.Set()
  367. // 到款登记-付款方式
  368. v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
  369. // 新增的记录
  370. logList := make([]*fms.ContractRegisterLog, 0)
  371. opData := ""
  372. opDataByte, e := json.Marshal(req)
  373. if e != nil {
  374. return
  375. }
  376. opData = string(opDataByte)
  377. opType := fms.ContractInvoiceTypePrePay
  378. newAmount := decimal.NewFromFloat(0).Round(2)
  379. a := decimal.NewFromFloat(v.Amount).Round(2)
  380. newAmount = newAmount.Add(a)
  381. ia, _ := newAmount.Round(2).Float64()
  382. logList = append(logList, &fms.ContractRegisterLog{
  383. ContractRegisterId: ob.ContractRegisterId,
  384. AdminId: int(adminInfo.AdminId),
  385. AdminName: adminInfo.RealName,
  386. OpData: opData,
  387. OpType: opType,
  388. CreateTime: nowTime,
  389. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  390. })
  391. if e := v.Create(); e != nil {
  392. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  393. return
  394. }
  395. //最后删除预到款记录
  396. e = ppItem.Delete()
  397. if e != nil {
  398. resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
  399. return
  400. }
  401. // 校验金额-是否修改状态
  402. go fmsService.CheckContractRegisterAmount(ob.ContractRegisterId)
  403. // 开票到款汇总
  404. go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
  405. // 操作日志
  406. go func() {
  407. logOB := new(fms.ContractRegisterLog)
  408. if e := logOB.AddInBatches(logList); e != nil {
  409. return
  410. }
  411. }()
  412. } else {
  413. if e = fms.CreateContractRegisterAndServices(ob, serviceList, serviceAmountList); e != nil {
  414. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  415. return
  416. }
  417. }
  418. // 操作日志
  419. go func() {
  420. opData := ""
  421. opDataByte, e := json.Marshal(req)
  422. if e != nil {
  423. return
  424. }
  425. opData = string(opDataByte)
  426. logItem := new(fms.ContractRegisterLog)
  427. logItem.ContractRegisterId = ob.ContractRegisterId
  428. logItem.AdminId = int(adminInfo.AdminId)
  429. logItem.AdminName = adminInfo.RealName
  430. logItem.OpData = opData
  431. logItem.OpType = fms.ContractRegisterOpTypeSave
  432. logItem.CreateTime = nowTime
  433. logItem.Remark = req.Remark
  434. if e = logItem.Create(); e != nil {
  435. return
  436. }
  437. }()
  438. resp.Ok("操作成功", c)
  439. }
  440. // Edit
  441. // @Title 编辑合同登记
  442. // @Description 编辑合同登记
  443. // @Param request body fms.ContractRegisterEditReq true "type json string"
  444. // @Success 200 string "操作成功"
  445. // @router /contract/register/edit [post]
  446. func (rg *RegisterController) Edit(c *gin.Context) {
  447. req := new(fms.ContractRegisterEditReq)
  448. err := c.ShouldBind(&req)
  449. if err != nil {
  450. errs, ok := err.(validator.ValidationErrors)
  451. if !ok {
  452. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  453. return
  454. }
  455. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  456. return
  457. }
  458. claims, _ := c.Get("adminInfo")
  459. adminInfo := claims.(*system.SysAdmin)
  460. // 日期校验
  461. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  462. if e != nil {
  463. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  464. return
  465. }
  466. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  467. if e != nil {
  468. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  469. return
  470. }
  471. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  472. if req.SignDate != "" {
  473. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  474. if e != nil {
  475. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  476. return
  477. }
  478. signDate = signDateTime
  479. }
  480. ob := new(fms.ContractRegister)
  481. item, e := ob.Fetch(req.ContractRegisterId)
  482. if e != nil {
  483. if e == utils.ErrNoRow {
  484. resp.Fail("登记记录不存在或已被删除", c)
  485. return
  486. }
  487. resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
  488. return
  489. }
  490. // 查询销售信息
  491. var (
  492. sellerId int
  493. raiSellerId int
  494. sellerName string
  495. raiSellerName string
  496. )
  497. if req.SellerIds != "" {
  498. admin := new(crm.Admin)
  499. sellerIds := strings.Split(req.SellerIds, ",")
  500. if len(sellerIds) > 2 {
  501. resp.Fail("最多只能选择两个销售", c)
  502. return
  503. }
  504. var pars []interface{}
  505. cond := ` admin_id in (?) `
  506. pars = append(pars, sellerIds)
  507. sellers, e := admin.List(cond, pars)
  508. if e != nil {
  509. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  510. return
  511. }
  512. for _, v := range sellers {
  513. if v.DepartmentId == crm.SellerDepartmentId {
  514. sellerId = v.AdminId
  515. sellerName = v.AdminName
  516. }else if v.DepartmentId == crm.RaiSellerDepartmentId {
  517. raiSellerId = v.AdminId
  518. raiSellerName = v.AdminName
  519. }
  520. }
  521. }
  522. // 是否存在相同合同编号的登记
  523. existCond := `contract_code = ?`
  524. existPars := make([]interface{}, 0)
  525. existPars = append(existPars, req.ContractCode)
  526. exist, e := ob.FetchByCondition(existCond, existPars)
  527. if e != nil && e != utils.ErrNoRow {
  528. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  529. return
  530. }
  531. if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
  532. resp.Fail("合同编号已存在", c)
  533. return
  534. }
  535. originHasPayment := item.HasPayment
  536. updateCols := []string{
  537. "ProductIds","ContractCode", "RelateContractCode", "CrmContractId", "ContractSource", "CompanyName", "ActualCompanyName",
  538. "SellerId", "SellerName", "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime",
  539. "ContractStatus", "RegisterStatus", "Remark", "ServiceRemark", "HasPayment", "NewCompany", "ModifyTime",
  540. }
  541. nowTime := time.Now().Local()
  542. item.ProductIds = req.ProductIds
  543. item.ContractCode = req.ContractCode
  544. item.RelateContractCode = req.RelateContractCode
  545. item.CrmContractId = req.CrmContractId
  546. item.ContractSource = req.ContractSource
  547. item.CompanyName = req.CompanyName
  548. item.ActualCompanyName = req.ActualCompanyName
  549. item.SellerId = sellerId
  550. item.SellerName = sellerName
  551. item.RaiSellerId = raiSellerId
  552. item.RaiSellerName = raiSellerName
  553. item.ContractType = req.ContractType
  554. item.ContractAmount = req.ContractAmount
  555. item.StartDate = startDate
  556. item.EndDate = endDate
  557. item.SignDate = signDate
  558. item.AgreedPayTime = req.AgreedPayTime
  559. item.ContractStatus = req.ContractStatus
  560. item.RegisterStatus = fms.ContractRegisterStatusIng
  561. item.Remark = req.Remark
  562. item.ServiceRemark = req.ServiceRemark
  563. item.HasPayment = req.HasPayment
  564. item.NewCompany = req.NewCompany
  565. item.ModifyTime = nowTime
  566. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  567. if req.HasPayment == 1 {
  568. item.RegisterStatus = fms.ContractRegisterStatusComplete
  569. updateCols = append(updateCols, "RegisterStatus")
  570. }
  571. // 开票到款信息
  572. invoiceOB := new(fms.ContractInvoice)
  573. invoiceCond := `contract_register_id = ?`
  574. invoicePars := make([]interface{}, 0)
  575. invoicePars = append(invoicePars, req.ContractRegisterId)
  576. invoiceList, e := invoiceOB.List(invoiceCond, invoicePars, "")
  577. if e != nil {
  578. resp.FailMsg("操作失败", "获取合同开票到款列表失败, Err: "+e.Error(), c)
  579. return
  580. }
  581. invoiceUpdateCols := make([]string, 0)
  582. // 开票到款操作类型: 0-无; 1-更新; 2-删除;
  583. logRemark := req.Remark
  584. invoiceHandleType := 0
  585. if originHasPayment == 0 && req.HasPayment == 1 {
  586. // 若从无代付修改为有代付, 则删除无代付期间新增的所有开票到款登记
  587. invoiceHandleType = 2
  588. } else {
  589. // 修改了货币单位后,同步更新汇率及开票到款的换算金额
  590. if req.CurrencyUnit != item.CurrencyUnit {
  591. rateList, e := fmsService.GetTodayCurrencyRateList()
  592. if e != nil {
  593. resp.FailMsg("操作失败", "获取货币列表及汇率失败, Err: "+e.Error(), c)
  594. return
  595. }
  596. var rate float64
  597. for i := range rateList {
  598. if rateList[i].Code == req.CurrencyUnit {
  599. rate = rateList[i].RMBRate
  600. break
  601. }
  602. }
  603. if rate < 0 {
  604. resp.FailMsg("操作失败", "货币汇率有误", c)
  605. return
  606. }
  607. item.CurrencyUnit = req.CurrencyUnit
  608. item.RMBRate = rate
  609. updateCols = append(updateCols, "CurrencyUnit", "RMBRate")
  610. // 调整开票到款换算后的金额, 保留两位小数
  611. for i := range invoiceList {
  612. invoiceList[i].CurrencyUnit = req.CurrencyUnit
  613. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceList[i].OriginAmount/rate), 64)
  614. invoiceList[i].Amount = a
  615. }
  616. invoiceUpdateCols = append(invoiceUpdateCols, "CurrencyUnit", "Amount")
  617. invoiceHandleType = 1
  618. logRemark = fmt.Sprintf("金额单位由%s修改为%s\n%s", item.CurrencyUnit, req.CurrencyUnit, logRemark)
  619. }
  620. }
  621. // 新增套餐金额详情内容
  622. serviceAmountMap := make(map[int]float64)
  623. serviceAmountList, e := fmsService.HandleContractServiceAmount(req.ServiceAmount, serviceAmountMap, req.CurrencyUnit)
  624. if e != nil {
  625. resp.FailMsg("操作失败", "新增合同套餐金额信息失败, Err: "+e.Error(), c)
  626. return
  627. }
  628. //判断产品信息
  629. productIds := make(map[int]struct{})
  630. productIdsStr := ""
  631. for _, v := range serviceAmountList {
  632. productIds[v.ProductId] = struct{}{}
  633. }
  634. for proId, _ := range productIds {
  635. productIdsStr += strconv.Itoa(proId)+","
  636. }
  637. productIdsStr = strings.Trim(productIdsStr, ",")
  638. item.ProductIds = productIdsStr
  639. // 套餐信息
  640. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  641. if e != nil {
  642. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  643. return
  644. }
  645. // 更新合同登记、套餐、开票到款
  646. if e = fms.UpdateContractRegister(item, updateCols, serviceList, invoiceList, invoiceUpdateCols, invoiceHandleType, serviceAmountList); e != nil {
  647. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  648. return
  649. }
  650. // 自动分配套餐金额
  651. go fmsService.CalculatePaymentServiceAmount(item.ContractRegisterId)
  652. // 校验金额-是否修改状态
  653. go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
  654. // 操作日志
  655. go func() {
  656. opData := ""
  657. opDataByte, e := json.Marshal(req)
  658. if e != nil {
  659. return
  660. }
  661. opData = string(opDataByte)
  662. logItem := new(fms.ContractRegisterLog)
  663. logItem.ContractRegisterId = item.ContractRegisterId
  664. logItem.AdminId = int(adminInfo.AdminId)
  665. logItem.AdminName = adminInfo.RealName
  666. logItem.OpData = opData
  667. logItem.OpType = fms.ContractRegisterOpTypeEdit
  668. logItem.CreateTime = nowTime
  669. logItem.Remark = logRemark
  670. if e = logItem.Create(); e != nil {
  671. return
  672. }
  673. }()
  674. resp.Ok("操作成功", c)
  675. }
  676. // Del
  677. // @Title 删除合同登记
  678. // @Description 删除合同登记
  679. // @Param request body fms.ContractRegisterDelReq true "type json string"
  680. // @Success 200 string "操作成功"
  681. // @router /contract/register/del [post]
  682. func (rg *RegisterController) Del(c *gin.Context) {
  683. req := new(fms.ContractRegisterDelReq)
  684. err := c.ShouldBind(&req)
  685. if err != nil {
  686. errs, ok := err.(validator.ValidationErrors)
  687. if !ok {
  688. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  689. return
  690. }
  691. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  692. return
  693. }
  694. claims, _ := c.Get("adminInfo")
  695. adminInfo := claims.(*system.SysAdmin)
  696. ob := new(fms.ContractRegister)
  697. item, e := ob.Fetch(req.ContractRegisterId)
  698. if e != nil {
  699. if e == utils.ErrNoRow {
  700. resp.Fail("合同登记不存在或已被删除", c)
  701. return
  702. }
  703. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  704. return
  705. }
  706. nowTime := time.Now().Local()
  707. item.IsDeleted = 1
  708. item.ModifyTime = nowTime
  709. updateCols := []string{"IsDeleted", "ModifyTime"}
  710. if e = item.Update(updateCols); e != nil {
  711. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  712. return
  713. }
  714. // 删除对应的开票到款登记
  715. go func() {
  716. if e = fms.DeleteContractInvoicesByRegisterId(item.ContractRegisterId); e != nil {
  717. alarm_msg.SendAlarmMsg(fmt.Sprintf("删除合同登记%d后, 删除开票到款记录失败, ErrMsg: %s", item.ContractRegisterId, e.Error()), 3)
  718. return
  719. }
  720. if e = fms.DeleteInvoicePaymentSummaryByRegisterId(item.ContractRegisterId); e != nil {
  721. alarm_msg.SendAlarmMsg(fmt.Sprintf("删除合同登记%d后, 删除开票到款汇总数据失败, ErrMsg: %s", item.ContractRegisterId, e.Error()), 3)
  722. return
  723. }
  724. }()
  725. // 操作日志
  726. go func() {
  727. opData := ""
  728. opDataByte, e := json.Marshal(req)
  729. if e != nil {
  730. return
  731. }
  732. opData = string(opDataByte)
  733. logItem := new(fms.ContractRegisterLog)
  734. logItem.ContractRegisterId = req.ContractRegisterId
  735. logItem.AdminId = int(adminInfo.AdminId)
  736. logItem.AdminName = adminInfo.RealName
  737. logItem.OpData = opData
  738. logItem.OpType = fms.ContractRegisterOpTypeDel
  739. logItem.CreateTime = nowTime
  740. if e = logItem.Create(); e != nil {
  741. return
  742. }
  743. }()
  744. resp.Ok("操作成功", c)
  745. }
  746. // Detail
  747. // @Title 合同登记详情
  748. // @Description 合同登记详情
  749. // @Param ContractRegisterId query int false "合同登记ID"
  750. // @Success 200 {object} fms.ContractRegisterDetail
  751. // @router /contract/register/detail [get]
  752. func (rg *RegisterController) Detail(c *gin.Context) {
  753. var req fms.ContractRegisterDetailReq
  754. if e := c.BindQuery(&req); e != nil {
  755. err, ok := e.(validator.ValidationErrors)
  756. if !ok {
  757. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  758. return
  759. }
  760. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  761. return
  762. }
  763. result := new(fms.ContractRegisterDetail)
  764. // 合同登记信息
  765. item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
  766. if e != nil {
  767. resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
  768. return
  769. }
  770. result.ContractRegisterItem = item
  771. // 套餐信息
  772. serviceAmountTempList, e := fms.GetContractServiceAmountByRegisterId(req.ContractRegisterId)
  773. if e != nil {
  774. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  775. return
  776. }
  777. serviceAmountList := make([]*fms.ContractServiceAmountItem, 0)
  778. for _, v := range serviceAmountTempList {
  779. tmp := &fms.ContractServiceAmountItem{
  780. ContractRegisterId: v.ContractRegisterId,
  781. ProductId: v.ProductId,
  782. ServiceAmount: v.ServiceAmount,
  783. CurrencyUnit: v.CurrencyUnit,
  784. }
  785. serviceAmountList = append(serviceAmountList, tmp)
  786. }
  787. result.ServiceAmountList = serviceAmountList
  788. // 套餐金额信息
  789. serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
  790. if e != nil {
  791. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  792. return
  793. }
  794. result.ServiceList = serviceList
  795. // 开票/到款信息
  796. invoiceCond := `contract_register_id = ?`
  797. invoicePars := make([]interface{}, 0)
  798. invoicePars = append(invoicePars, req.ContractRegisterId)
  799. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  800. if e != nil {
  801. resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
  802. return
  803. }
  804. result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
  805. result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
  806. for i := range invoiceList {
  807. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  808. result.InvoiceList = append(result.InvoiceList, invoiceList[i])
  809. continue
  810. }
  811. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  812. result.PaymentList = append(result.PaymentList, invoiceList[i])
  813. }
  814. }
  815. // 合同登记进度
  816. logCond := `contract_register_id = ?`
  817. logPars := make([]interface{}, 0)
  818. logPars = append(logPars, req.ContractRegisterId)
  819. logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
  820. if e != nil {
  821. resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
  822. return
  823. }
  824. result.Logs = logList
  825. resp.OkData("获取成功", result, c)
  826. }
  827. // UpdateStatus
  828. // @Title 修改合同状态
  829. // @Description 修改合同状态
  830. // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
  831. // @Success 200 string "操作成功"
  832. // @router /contract/register/update_status [post]
  833. func (rg *RegisterController) UpdateStatus(c *gin.Context) {
  834. req := new(fms.ContractRegisterUpdateStatusReq)
  835. err := c.ShouldBind(&req)
  836. if err != nil {
  837. errs, ok := err.(validator.ValidationErrors)
  838. if !ok {
  839. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  840. return
  841. }
  842. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  843. return
  844. }
  845. claims, _ := c.Get("adminInfo")
  846. adminInfo := claims.(*system.SysAdmin)
  847. ob := new(fms.ContractRegister)
  848. item, e := ob.Fetch(req.ContractRegisterId)
  849. if e != nil {
  850. if e == utils.ErrNoRow {
  851. resp.Fail("合同登记不存在或已被删除", c)
  852. return
  853. }
  854. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  855. return
  856. }
  857. nowTime := time.Now().Local()
  858. item.ContractStatus = req.ContractStatus
  859. item.ModifyTime = nowTime
  860. updateCols := []string{"ContractStatus", "ModifyTime"}
  861. if e = item.Update(updateCols); e != nil {
  862. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  863. return
  864. }
  865. // 校验金额-是否修改状态
  866. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  867. // 操作日志
  868. go func() {
  869. opData := ""
  870. opDataByte, e := json.Marshal(req)
  871. if e != nil {
  872. return
  873. }
  874. opData = string(opDataByte)
  875. logItem := new(fms.ContractRegisterLog)
  876. logItem.ContractRegisterId = req.ContractRegisterId
  877. logItem.AdminId = int(adminInfo.AdminId)
  878. logItem.AdminName = adminInfo.RealName
  879. logItem.OpData = opData
  880. logItem.OpType = fms.ContractRegisterOpTypeStatus
  881. logItem.CreateTime = nowTime
  882. if e = logItem.Create(); e != nil {
  883. return
  884. }
  885. }()
  886. resp.Ok("操作成功", c)
  887. }
  888. // Invoice
  889. // @Title 开票/到款登记
  890. // @Description 开票/到款登记
  891. // @Param request body fms.ContractInvoiceSaveReq true "type json string"
  892. // @Success 200 string "操作成功"
  893. // @router /contract/register/invoice [post]
  894. func (rg *RegisterController) Invoice(c *gin.Context) {
  895. req := new(fms.ContractInvoiceSaveReq)
  896. err := c.ShouldBind(&req)
  897. if err != nil {
  898. errs, ok := err.(validator.ValidationErrors)
  899. if !ok {
  900. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  901. return
  902. }
  903. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  904. return
  905. }
  906. claims, _ := c.Get("adminInfo")
  907. adminInfo := claims.(*system.SysAdmin)
  908. registerOB := new(fms.ContractRegister)
  909. item, e := registerOB.Fetch(req.ContractRegisterId)
  910. if e != nil {
  911. if e == utils.ErrNoRow {
  912. resp.Fail("合同登记不存在或已被删除", c)
  913. return
  914. }
  915. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  916. return
  917. }
  918. // 合同存在代付不允许开票/到款登记
  919. if item.HasPayment == 1 {
  920. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  921. return
  922. }
  923. noChangeInvoiceIds := make([]int, 0)
  924. newInvoice := make([]*fms.ContractInvoice, 0)
  925. if len(req.AmountList) > 0 {
  926. // 合同有效时长(计算付款方式)
  927. dayDiff := item.EndDate.Sub(item.StartDate).Hours() / 24
  928. // 获取销售分组信息
  929. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  930. if e != nil {
  931. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  932. return
  933. }
  934. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  935. for i := range sellerList {
  936. sellerMap[sellerList[i].SellerId] = sellerList[i]
  937. }
  938. for i := range req.AmountList {
  939. if req.AmountList[i].Amount <= 0 {
  940. resp.Fail("登记金额有误", c)
  941. return
  942. }
  943. if req.AmountList[i].InvoiceDate == "" {
  944. resp.Fail("请选择日期", c)
  945. return
  946. }
  947. if req.AmountList[i].ServiceProductId != 1 && req.AmountList[i].ServiceProductId !=2 {
  948. resp.Fail("请选择套餐类型", c)
  949. return
  950. }
  951. // 开票登记销售必填
  952. if req.InvoiceType == fms.ContractInvoiceTypeMake && req.AmountList[i].SellerId <= 0 {
  953. resp.Fail("请选择销售", c)
  954. return
  955. }
  956. t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
  957. if e != nil {
  958. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  959. return
  960. }
  961. if req.AmountList[i].InvoiceId > 0 {
  962. noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
  963. continue
  964. }
  965. if req.AmountList[i].InvoiceId == 0 {
  966. v := &fms.ContractInvoice{
  967. ContractRegisterId: req.ContractRegisterId,
  968. ContractCode: item.ContractCode,
  969. Amount: req.AmountList[i].Amount,
  970. OriginAmount: req.AmountList[i].OriginAmount,
  971. CurrencyUnit: item.CurrencyUnit,
  972. InvoiceType: req.InvoiceType,
  973. ServiceProductId: req.AmountList[i].ServiceProductId,
  974. InvoiceDate: t,
  975. AdminId: int(adminInfo.AdminId),
  976. AdminName: adminInfo.RealName,
  977. Remark: req.AmountList[i].Remark,
  978. }
  979. v.Set()
  980. // 开票登记-销售信息
  981. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  982. sellerItem := sellerMap[req.AmountList[i].SellerId]
  983. if sellerItem == nil {
  984. resp.Fail("销售信息异常", c)
  985. return
  986. }
  987. if req.AmountList[i].ServiceProductId == crm.CompanyProductFicc && sellerItem.DepartmentId != crm.SellerDepartmentId {
  988. resp.Fail("销售类型和所选套餐类型不一致", c)
  989. return
  990. }
  991. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  992. resp.Fail("销售类型和所选套餐类型不一致", c)
  993. return
  994. }
  995. v.SellerId = sellerItem.SellerId
  996. v.SellerName = sellerItem.SellerName
  997. v.SellerGroupId = sellerItem.GroupId
  998. v.SellerGroupName = sellerItem.GroupName
  999. v.SellerTeamId = sellerItem.TeamId
  1000. v.SellerTeamName = sellerItem.TeamName
  1001. }
  1002. // 到款登记-付款方式
  1003. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1004. v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
  1005. }
  1006. newInvoice = append(newInvoice, v)
  1007. }
  1008. }
  1009. }
  1010. // 获取原有的登记信息
  1011. invoiceCond := `contract_register_id = ? AND invoice_type = ? `
  1012. invoicePars := make([]interface{}, 0)
  1013. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  1014. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  1015. if e != nil {
  1016. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  1017. return
  1018. }
  1019. // 比对原有和现有的登记信息
  1020. logList := make([]*fms.ContractRegisterLog, 0)
  1021. opData := ""
  1022. opDataByte, e := json.Marshal(req)
  1023. if e != nil {
  1024. return
  1025. }
  1026. opData = string(opDataByte)
  1027. opType := fms.ContractRegisterOpTypeInvoice
  1028. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1029. opType = fms.ContractRegisterOpTypePayment
  1030. }
  1031. nowTime := time.Now().Local()
  1032. // 需要删除的记录
  1033. deleteInvoiceIds := make([]int, 0)
  1034. for i := range originInvoiceList {
  1035. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  1036. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  1037. logList = append(logList, &fms.ContractRegisterLog{
  1038. ContractRegisterId: req.ContractRegisterId,
  1039. AdminId: int(adminInfo.AdminId),
  1040. AdminName: adminInfo.RealName,
  1041. OpData: opData,
  1042. OpType: opType,
  1043. CreateTime: nowTime,
  1044. AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  1045. })
  1046. }
  1047. }
  1048. // todo 判断是否符合均分金额的条件,如果符合,需要生成金额分配记录表
  1049. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1050. err = fmsService.CalculatePaymentServiceAmount(req.ContractRegisterId)
  1051. if err != nil {
  1052. resp.FailMsg("自动分配金额失败", "自动分配金额失败, Err: "+err.Error(), c)
  1053. return
  1054. }
  1055. }
  1056. // 新增的记录
  1057. if len(newInvoice) > 0 {
  1058. newAmount := decimal.NewFromFloat(0).Round(2)
  1059. for i := range newInvoice {
  1060. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  1061. newAmount = newAmount.Add(a)
  1062. }
  1063. ia, _ := newAmount.Round(2).Float64()
  1064. logList = append(logList, &fms.ContractRegisterLog{
  1065. ContractRegisterId: req.ContractRegisterId,
  1066. AdminId: int(adminInfo.AdminId),
  1067. AdminName: adminInfo.RealName,
  1068. OpData: opData,
  1069. OpType: opType,
  1070. CreateTime: nowTime,
  1071. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  1072. })
  1073. }
  1074. // 删除并新增登记
  1075. ob := new(fms.ContractInvoice)
  1076. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  1077. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  1078. return
  1079. }
  1080. // 校验金额-是否修改状态
  1081. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  1082. // 开票到款汇总
  1083. go fmsService.SummaryInvoicePaymentByContractRegisterId(req.ContractRegisterId)
  1084. // 操作日志
  1085. go func() {
  1086. logOB := new(fms.ContractRegisterLog)
  1087. if e := logOB.AddInBatches(logList); e != nil {
  1088. return
  1089. }
  1090. }()
  1091. resp.Ok("操作成功", c)
  1092. }
  1093. // Export
  1094. // @Title 合同登记-导出
  1095. // @Description 合同登记-导出
  1096. // @Param Keyword query string false "关键词"
  1097. // @Param StartDate query string false "合同开始日期"
  1098. // @Param EndDate query string false "合同结束日期"
  1099. // @Param ServiceType query int false "套餐类型"
  1100. // @Param ContractType query int false "合同类型"
  1101. // @Param RegisterStatus query int false "登记状态"
  1102. // @Success 200 string "操作成功"
  1103. // @router /contract/register/export [get]
  1104. func (rg *RegisterController) Export(c *gin.Context) {
  1105. var req fms.ContractRegisterListReq
  1106. if e := c.BindQuery(&req); e != nil {
  1107. err, ok := e.(validator.ValidationErrors)
  1108. if !ok {
  1109. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1110. return
  1111. }
  1112. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1113. return
  1114. }
  1115. cond := `1 = 1`
  1116. pars := make([]interface{}, 0)
  1117. // 合同编号/客户姓名/销售/实际使用方
  1118. if req.Keyword != "" {
  1119. kw := "%" + req.Keyword + "%"
  1120. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  1121. pars = append(pars, kw, kw, kw, kw)
  1122. }
  1123. if req.StartDate != "" && req.EndDate != "" {
  1124. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1125. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1126. cond += ` AND (create_time BETWEEN ? AND ?)`
  1127. pars = append(pars, st, ed)
  1128. }
  1129. if req.ContractType != 0 {
  1130. cond += ` AND contract_type = ?`
  1131. pars = append(pars, req.ContractType)
  1132. }
  1133. if req.RegisterStatus != 0 {
  1134. cond += ` AND register_status = ?`
  1135. pars = append(pars, req.RegisterStatus)
  1136. }
  1137. if req.ServiceTypes != "" {
  1138. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1139. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1140. if e != nil {
  1141. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1142. return
  1143. }
  1144. if len(registerIds) > 0 {
  1145. cond += ` AND contract_register_id IN ?`
  1146. pars = append(pars, registerIds)
  1147. } else {
  1148. cond += ` AND 1 = 2`
  1149. }
  1150. }
  1151. // 获取列表数据
  1152. cr := new(fms.ContractRegister)
  1153. list, e := cr.List(cond, pars)
  1154. if e != nil {
  1155. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  1156. return
  1157. }
  1158. if len(list) == 0 {
  1159. resp.Fail("无有效数据可导出", c)
  1160. return
  1161. }
  1162. registerIds := make([]int, 0)
  1163. for i := range list {
  1164. registerIds = append(registerIds, list[i].ContractRegisterId)
  1165. }
  1166. // 获取小套餐品种
  1167. cpCond := `product_id = ? AND permission_name <> ?`
  1168. cpPars := make([]interface{}, 0)
  1169. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  1170. cp := new(crm.ChartPermission)
  1171. permissionList, e := cp.List(cpCond, cpPars)
  1172. if e != nil {
  1173. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  1174. return
  1175. }
  1176. permissionLen := len(permissionList)
  1177. permissionNameIdMap := make(map[string]int)
  1178. for i := range permissionList {
  1179. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1180. }
  1181. // 获取所有FICC套餐服务
  1182. serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  1183. if e != nil {
  1184. resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  1185. return
  1186. }
  1187. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1188. otherService := make([]*fms.ContractServiceTemplateItem, 0)
  1189. for i := range serviceList {
  1190. if serviceList[i].Title != "FICC大套餐" && serviceList[i].Title != "FICC小套餐" {
  1191. otherService = append(otherService, serviceList[i])
  1192. }
  1193. }
  1194. otherServiceLen := len(otherService)
  1195. // 获取所有权益套餐服务
  1196. raiServiceList, e := fms.GetContractServiceTemplateAllByProductId(crm.CompanyProductRai)
  1197. if e != nil {
  1198. resp.FailData("获取权益套餐服务失败", "Err:"+e.Error(), c)
  1199. return
  1200. }
  1201. raiServiceIdMap := make(map[int]*fms.ContractServiceTemplateItem)
  1202. for i := range raiServiceList {
  1203. raiServiceIdMap[raiServiceList[i].ServiceTemplateId] = raiServiceList[i]
  1204. }
  1205. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1206. raiOtherService := make([]*fms.ContractServiceTemplateItem, 0)
  1207. raiServiceNotShowMap := make(map[int]struct{})
  1208. for _, v := range raiServiceList {
  1209. if v.Pid > 0 && raiServiceIdMap[v.Pid].Pid > 0 {
  1210. raiServiceNotShowMap[v.Pid] = struct{}{}
  1211. raiServiceNotShowMap[raiServiceIdMap[v.Pid].Pid] = struct{}{}
  1212. }else if v.Pid > 0 {
  1213. raiServiceNotShowMap[v.Pid] = struct{}{}
  1214. }
  1215. }
  1216. for _, v := range raiServiceList {
  1217. if _, ok := raiServiceNotShowMap[v.ServiceTemplateId]; !ok {
  1218. if v.Pid > 0 {
  1219. v.ParentTitle = raiServiceIdMap[v.Pid].Title
  1220. }
  1221. raiOtherService = append(raiOtherService, v)
  1222. }
  1223. }
  1224. otherServiceLen += len(raiOtherService)
  1225. //套餐金额map
  1226. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount)
  1227. // 套餐/开票/到款列表
  1228. serviceMap := make(map[int][]*fms.ContractServiceWithParentTitle)
  1229. serviceChartPermissionsMap := make(map[int][]int)
  1230. invoiceMap := make(map[int][]*fms.ContractInvoice)
  1231. paymentMap := make(map[int][]*fms.ContractInvoice)
  1232. maxInvoice := 0
  1233. maxPayment := 0
  1234. if len(registerIds) > 0 {
  1235. // 获取套餐信息
  1236. csCond := `cv.contract_register_id IN ?`
  1237. csPars := make([]interface{}, 0)
  1238. csPars = append(csPars, registerIds)
  1239. cs := new(fms.ContractService)
  1240. serviceList, e := cs.ListWithWithParentTitle(csCond, csPars)
  1241. if e != nil {
  1242. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  1243. return
  1244. }
  1245. for i := range serviceList {
  1246. cid := serviceList[i].ContractRegisterId
  1247. if serviceMap[cid] == nil {
  1248. serviceMap[cid] = make([]*fms.ContractServiceWithParentTitle, 0)
  1249. }
  1250. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  1251. // 小套餐权限
  1252. if serviceChartPermissionsMap[cid] == nil {
  1253. serviceChartPermissionsMap[cid] = make([]int, 0)
  1254. }
  1255. if serviceList[i].ChartPermissionIds != "" {
  1256. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  1257. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  1258. }
  1259. }
  1260. // 获取合同的套餐金额信息
  1261. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(registerIds)
  1262. if e != nil {
  1263. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1264. return
  1265. }
  1266. for _, v := range serviceAmountList {
  1267. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1268. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1269. }
  1270. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1271. }
  1272. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  1273. ci := new(fms.ContractInvoice)
  1274. csCond = `contract_register_id IN ?`
  1275. csPars = make([]interface{}, 0)
  1276. csPars = append(csPars, registerIds)
  1277. invoiceList, e := ci.List(csCond, csPars, "")
  1278. if e != nil {
  1279. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1280. return
  1281. }
  1282. for k := range invoiceList {
  1283. cid := invoiceList[k].ContractRegisterId
  1284. if invoiceMap[cid] == nil {
  1285. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  1286. }
  1287. if paymentMap[cid] == nil {
  1288. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  1289. }
  1290. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  1291. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  1292. continue
  1293. }
  1294. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  1295. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  1296. continue
  1297. }
  1298. }
  1299. // 取最大开票/到款数
  1300. for j := range invoiceMap {
  1301. if len(invoiceMap[j]) > maxInvoice {
  1302. maxInvoice = len(invoiceMap[j])
  1303. }
  1304. }
  1305. for p := range paymentMap {
  1306. if len(paymentMap[p]) > maxPayment {
  1307. maxPayment = len(paymentMap[p])
  1308. }
  1309. }
  1310. }
  1311. serviceProductIdMap := map[int]string{
  1312. 1:"FICC套餐",
  1313. 2:"权益套餐",
  1314. }
  1315. // 生成Excel文件
  1316. xlsxFile := xlsx.NewFile()
  1317. style := xlsx.NewStyle()
  1318. alignment := xlsx.Alignment{
  1319. Horizontal: "center",
  1320. Vertical: "center",
  1321. WrapText: true,
  1322. }
  1323. style.Alignment = alignment
  1324. style.ApplyAlignment = true
  1325. sheetName := "财务列表"
  1326. sheet, err := xlsxFile.AddSheet(sheetName)
  1327. if err != nil {
  1328. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1329. return
  1330. }
  1331. // 1行表头
  1332. hInt := 0
  1333. titleRow := sheet.AddRow()
  1334. titleRow.SetHeight(40)
  1335. // 1行1列-右合并两格, 下合并1行
  1336. cell1 := titleRow.AddCell()
  1337. cell1.HMerge = 4
  1338. cell1.VMerge = 1
  1339. cell1.SetString("FICC客户签约表")
  1340. cell1.SetStyle(style)
  1341. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  1342. titleRow.AddCell().SetString("")
  1343. titleRow.AddCell().SetString("")
  1344. titleRow.AddCell().SetString("")
  1345. titleRow.AddCell().SetString("")
  1346. hInt += 5
  1347. // 1行2列
  1348. cell2 := titleRow.AddCell()
  1349. cell2.VMerge = 1
  1350. cell2.SetString("FICC大套餐")
  1351. cell2.SetStyle(style)
  1352. hInt ++
  1353. // 1行3列-右合并小套餐数
  1354. if permissionLen >= 1 {
  1355. cell3 := titleRow.AddCell()
  1356. hInt ++
  1357. cell3.HMerge = permissionLen - 1
  1358. cell3.VMerge = 1
  1359. cell3.SetString("FICC小套餐")
  1360. cell3.SetStyle(style)
  1361. // 同上右增单元格小套餐数-1的空白单元格用于合并
  1362. for i := 0; i < permissionLen-1; i++ {
  1363. titleRow.AddCell().SetString("")
  1364. hInt ++
  1365. }
  1366. }
  1367. for i := range otherService {
  1368. cellOther := titleRow.AddCell()
  1369. cellOther.VMerge = 1
  1370. hInt ++
  1371. cellOther.SetString(otherService[i].Title)
  1372. cellOther.SetStyle(style)
  1373. }
  1374. //权益大套餐
  1375. cell4 := titleRow.AddCell()
  1376. cell4.HMerge = 1
  1377. cell4.VMerge = 1
  1378. cell4.SetString("权益大套餐")
  1379. cell4.SetStyle(style)
  1380. titleRow.AddCell().SetString("")
  1381. hInt +=2
  1382. //权益分行业套餐
  1383. cell5 := titleRow.AddCell()
  1384. cell5.HMerge = 8
  1385. cell5.SetString("权益分行业套餐")
  1386. cell5.SetStyle(style)
  1387. titleRow.AddCell().SetString("")
  1388. titleRow.AddCell().SetString("")
  1389. titleRow.AddCell().SetString("")
  1390. titleRow.AddCell().SetString("")
  1391. titleRow.AddCell().SetString("")
  1392. titleRow.AddCell().SetString("")
  1393. titleRow.AddCell().SetString("")
  1394. titleRow.AddCell().SetString("")
  1395. //第二行,前面几个单元格用于第一行的合并
  1396. titleRow2 := sheet.AddRow()
  1397. titleRow2.SetHeight(30)
  1398. for i:= 0; i<hInt;i++ {
  1399. titleRow2.AddCell().SetString("")
  1400. }
  1401. //权益分行业套餐
  1402. row2Cell1 := titleRow2.AddCell()
  1403. row2Cell1.HMerge = 1
  1404. row2Cell1.SetString("医药")
  1405. row2Cell1.SetStyle(style)
  1406. titleRow2.AddCell().SetString("")
  1407. row2Cell2 := titleRow2.AddCell()
  1408. row2Cell2.HMerge = 1
  1409. row2Cell2.SetString("消费")
  1410. row2Cell2.SetStyle(style)
  1411. titleRow2.AddCell().SetString("")
  1412. row2Cell3 := titleRow2.AddCell()
  1413. row2Cell3.HMerge = 1
  1414. row2Cell3.SetString("科技")
  1415. row2Cell3.SetStyle(style)
  1416. titleRow2.AddCell().SetString("")
  1417. row2Cell4 := titleRow2.AddCell()
  1418. row2Cell4.HMerge = 1
  1419. row2Cell4.SetString("智造")
  1420. row2Cell4.SetStyle(style)
  1421. titleRow2.AddCell().SetString("")
  1422. row2Cell5 := titleRow2.AddCell()
  1423. row2Cell5.SetString("策略")
  1424. row2Cell5.SetStyle(style)
  1425. // 第三行表头
  1426. titleRow3 := sheet.AddRow()
  1427. titleRow3.SetHeight(60)
  1428. row3Title := make([]string, 0)
  1429. row3TitleParent := make([]string, 0)
  1430. row3Title = append(row3Title, "客户名称", "新客户\n0-是\n1-否", "合同类型\n续约-0\n新增-1\n代付-2\n补充协议-3", "FICC销售", "权益销售", "FICC大套餐")
  1431. for i := range permissionList {
  1432. row3Title = append(row3Title, permissionList[i].PermissionName)
  1433. }
  1434. // 其他套餐
  1435. for i := range otherService {
  1436. row3Title = append(row3Title, otherService[i].Title)
  1437. }
  1438. // 定义二级套餐名称
  1439. for i:= range row3Title {
  1440. row3TitleParent = append(row3TitleParent, row3Title[i])
  1441. }
  1442. // 权益三级套餐
  1443. for i := range raiOtherService {
  1444. row3Title = append(row3Title, raiOtherService[i].Title)
  1445. if raiOtherService[i].ParentTitle != "" {
  1446. row3TitleParent = append(row3TitleParent, raiOtherService[i].ParentTitle)
  1447. }else{
  1448. row3TitleParent = append(row3TitleParent, raiOtherService[i].Title)
  1449. }
  1450. }
  1451. row3Title = append(row3Title, "套餐备注", "开始时间", "到期时间", "2022年合同金额", "金额单位", "FICC套餐总金额", "权益套餐总金额", "约定付款时间", "签订日", "合同状态",
  1452. "合同编号", "合规备注")
  1453. // 设置表头
  1454. for i := range row3Title {
  1455. v := titleRow3.AddCell()
  1456. v.SetString(row3Title[i])
  1457. v.SetStyle(style)
  1458. }
  1459. // 第二行表头-开票/收款(动态添加)
  1460. invoiceTitle := []string{"开票日", "开票金额", "套餐类型", "销售", "备注"}
  1461. for i := 0; i < maxInvoice; i++ {
  1462. n := i + 1
  1463. for ii := range invoiceTitle {
  1464. c := titleRow3.AddCell()
  1465. t := fmt.Sprintf("%s%d", invoiceTitle[ii], n)
  1466. c.SetString(t)
  1467. c.SetStyle(style)
  1468. row3Title = append(row3Title, t)
  1469. }
  1470. }
  1471. paymentTitle := []string{"到款日", "到款金额", "套餐类型", "备注"}
  1472. for i := 0; i < maxPayment; i++ {
  1473. n := i + 1
  1474. for ii := range paymentTitle {
  1475. c := titleRow3.AddCell()
  1476. t := fmt.Sprintf("%s%d", paymentTitle[ii], n)
  1477. c.SetString(t)
  1478. c.SetStyle(style)
  1479. row3Title = append(row3Title, t)
  1480. }
  1481. }
  1482. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  1483. row2NameKeyMap := make(map[string]int)
  1484. for i := range row3Title {
  1485. row2NameKeyMap[row3Title[i]] = i
  1486. }
  1487. newCompanyMap := map[int]string{0: "1", 1: "0"}
  1488. contractTMap := map[int]int{
  1489. fms.ContractTypeNew: 1,
  1490. fms.ContractTypeRenew: 0,
  1491. fms.ContractTypeAgentPay: 2, // 代付合同
  1492. fms.ContractTypePlus: 3, // 补充协议
  1493. }
  1494. for _, v := range list {
  1495. k := -1 // 套餐匹配用
  1496. dataRow := sheet.AddRow()
  1497. dataRow.SetHeight(20)
  1498. k += 4
  1499. dataRow.AddCell().SetString(v.CompanyName)
  1500. dataRow.AddCell().SetString(newCompanyMap[v.NewCompany])
  1501. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
  1502. dataRow.AddCell().SetString(v.SellerName)
  1503. dataRow.AddCell().SetString(v.RaiSellerName)
  1504. // 大套餐
  1505. k += 1
  1506. col4Name := row3Title[k]
  1507. svList := serviceMap[v.ContractRegisterId]
  1508. col4 := ""
  1509. if svList != nil && len(svList) > 0 {
  1510. for isv := range svList {
  1511. if svList[isv].Title == col4Name {
  1512. col4 = "是"
  1513. break
  1514. }
  1515. }
  1516. }
  1517. dataRow.AddCell().SetString(col4)
  1518. // 小套餐
  1519. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  1520. for i := 0; i < permissionLen; i++ {
  1521. k += 1
  1522. colName := row3Title[k]
  1523. chartPermissionId := permissionNameIdMap[colName]
  1524. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  1525. dataRow.AddCell().SetString("是")
  1526. } else {
  1527. dataRow.AddCell().SetString("")
  1528. }
  1529. }
  1530. // 除大小套餐外的其他套餐(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  1531. for i := 0; i < otherServiceLen; i++ {
  1532. k += 1
  1533. otherColName := row3Title[k]
  1534. otherCol := ""
  1535. if svList != nil && len(svList) > 0 {
  1536. for isv := range svList {
  1537. if svList[isv].Title == otherColName {
  1538. // 判断权益套餐权限时,需要同时判断父级name
  1539. if otherColName == "主观" || otherColName == "客观" {
  1540. if row3TitleParent[k] == svList[isv].ParentTitle {
  1541. otherCol = "是"
  1542. break
  1543. }
  1544. }else{
  1545. otherCol = "是"
  1546. break
  1547. }
  1548. }
  1549. }
  1550. }
  1551. dataRow.AddCell().SetString(otherCol)
  1552. }
  1553. // 其他信息
  1554. ficcAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductFicc]
  1555. raiAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductRai]
  1556. dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
  1557. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  1558. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  1559. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
  1560. dataRow.AddCell().SetString(v.CurrencyUnit) // 货币单位
  1561. dataRow.AddCell().SetString(fmt.Sprint("¥", ficcAmount.ServiceAmount)) // FICC套餐总金额
  1562. dataRow.AddCell().SetString(fmt.Sprint("¥", raiAmount.ServiceAmount)) // 权益套餐总金额
  1563. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  1564. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  1565. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  1566. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1567. dataRow.AddCell().SetString(v.Remark) // 合规备注
  1568. // 开票/到款信息
  1569. ivList := invoiceMap[v.ContractRegisterId]
  1570. ivListLen := len(ivList)
  1571. for ia := 0; ia < maxInvoice; ia++ {
  1572. if ia < ivListLen {
  1573. if ivList != nil && ivList[ia] != nil {
  1574. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  1575. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].OriginAmount)) // 开票金额
  1576. dataRow.AddCell().SetString(serviceProductIdMap[ivList[ia].ServiceProductId]) // 套餐类型
  1577. dataRow.AddCell().SetString(ivList[ia].SellerName) // 销售名称
  1578. dataRow.AddCell().SetString(ivList[ia].Remark) // 开票备注
  1579. continue
  1580. }
  1581. }
  1582. // 这里要把不够的填充为空
  1583. dataRow.AddCell().SetString("")
  1584. dataRow.AddCell().SetString("")
  1585. dataRow.AddCell().SetString("")
  1586. dataRow.AddCell().SetString("")
  1587. dataRow.AddCell().SetString("")
  1588. }
  1589. pyList := paymentMap[v.ContractRegisterId]
  1590. pyListLen := len(pyList)
  1591. for ib := 0; ib < maxPayment; ib++ {
  1592. if ib < pyListLen {
  1593. if pyList != nil && pyList[ib] != nil {
  1594. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  1595. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].OriginAmount)) // 收款金额
  1596. dataRow.AddCell().SetString(serviceProductIdMap[pyList[ib].ServiceProductId]) // 套餐类型
  1597. dataRow.AddCell().SetString(pyList[ib].Remark) // 收款备注
  1598. continue
  1599. }
  1600. }
  1601. // 这里要把不够的填充为空
  1602. dataRow.AddCell().SetString("")
  1603. dataRow.AddCell().SetString("")
  1604. dataRow.AddCell().SetString("")
  1605. dataRow.AddCell().SetString("")
  1606. }
  1607. }
  1608. // 输出文件
  1609. var buffer bytes.Buffer
  1610. _ = xlsxFile.Write(&buffer)
  1611. content := bytes.NewReader(buffer.Bytes())
  1612. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1613. fileName := sheetName + randStr + ".xlsx"
  1614. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1615. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1616. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1617. }
  1618. // InvoiceList
  1619. // @Title 开票/到款列表
  1620. // @Description 开票/到款列表
  1621. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1622. // @Param ContractCode query string false "合同编号"
  1623. // @Param StartDate query string false "开始日期"
  1624. // @Param EndDate query string false "结束日期"
  1625. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1626. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1627. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1628. // @Success 200 {object} fms.ContractInvoiceItem
  1629. // @router /contract/register/invoice_list [get]
  1630. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  1631. var req fms.ContractInvoiceListReq
  1632. if e := c.BindQuery(&req); e != nil {
  1633. err, ok := e.(validator.ValidationErrors)
  1634. if !ok {
  1635. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1636. return
  1637. }
  1638. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1639. return
  1640. }
  1641. pageSize := req.PageSize
  1642. pageIndex := req.Current
  1643. if pageSize <= 0 {
  1644. pageSize = utils.PageSize20
  1645. }
  1646. if pageIndex <= 0 {
  1647. pageIndex = 1
  1648. }
  1649. cond := `invoice_type = ?`
  1650. pars := make([]interface{}, 0)
  1651. pars = append(pars, req.InvoiceType)
  1652. // 合同编号
  1653. if req.ContractCode != "" {
  1654. kw := fmt.Sprint("%", req.ContractCode, "%")
  1655. pars = append(pars, kw)
  1656. // 开票列表同时模糊查询销售名称
  1657. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  1658. cond += ` AND (contract_code LIKE ? )`
  1659. pars = append(pars, kw)
  1660. } else {
  1661. cond += ` AND contract_code LIKE ?`
  1662. pars = append(pars, kw)
  1663. }
  1664. }
  1665. if req.StartDate != "" && req.EndDate != "" {
  1666. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1667. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1668. cond += ` AND (invoice_time BETWEEN ? AND ?)`
  1669. pars = append(pars, st, ed)
  1670. }
  1671. if req.MinAmount > 0 {
  1672. cond += ` AND amount >= ?`
  1673. pars = append(pars, req.MinAmount)
  1674. }
  1675. if req.MaxAmount > 0 {
  1676. cond += ` AND amount <= ?`
  1677. pars = append(pars, req.MaxAmount)
  1678. }
  1679. // 套餐类型
  1680. if req.ServiceProductId > 0 {
  1681. cond += ` AND service_product_id = ?`
  1682. pars = append(pars, req.ServiceProductId)
  1683. }
  1684. // 销售
  1685. if req.SellerIds != "" {
  1686. sellerIds := strings.Split(req.SellerIds, ",")
  1687. cond += ` AND (seller_id in (?))`
  1688. pars = append(pars, sellerIds)
  1689. }
  1690. // 货币列表
  1691. currencyOB := new(fms.CurrencyUnit)
  1692. currencyCond := `enable = 1`
  1693. currencyPars := make([]interface{}, 0)
  1694. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1695. if e != nil {
  1696. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1697. return
  1698. }
  1699. unitMap := make(map[string]string)
  1700. currencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1701. for i := range currencyList {
  1702. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1703. currencyTotals = append(currencyTotals, &fms.InvoiceListCurrencyTotal{
  1704. Name: currencyList[i].Name,
  1705. UnitName: currencyList[i].UnitName,
  1706. Code: currencyList[i].Code,
  1707. FlagImg: currencyList[i].FlagImg,
  1708. })
  1709. }
  1710. page := new(base.Page)
  1711. page.SetPageSize(pageSize)
  1712. page.SetCurrent(pageIndex)
  1713. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  1714. if req.IsExport == 1 {
  1715. page.SetPageSize(10000)
  1716. page.SetCurrent(1)
  1717. }
  1718. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  1719. if e != nil {
  1720. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  1721. return
  1722. }
  1723. page.SetTotal(total)
  1724. contractRegisterIds := make([]int, 0)
  1725. contractStatusMap := make(map[int]int)
  1726. for i := range list {
  1727. list[i].UnitName = unitMap[list[i].CurrencyUnit]
  1728. contractRegisterIds = append(contractRegisterIds, list[i].ContractRegisterId)
  1729. }
  1730. if len(contractRegisterIds) > 0 {
  1731. contractRegisters, err := fms.GetContractInfoByRegisterIds(contractRegisterIds)
  1732. if err != nil {
  1733. resp.FailMsg("查询合同信息失败", "查询合同信息失败, Err: "+err.Error(), c)
  1734. return
  1735. }
  1736. for _, v := range contractRegisters {
  1737. contractStatusMap[v.ContractRegisterId] = v.ContractStatus
  1738. }
  1739. }
  1740. for i := range list {
  1741. list[i].ContractStatus = contractStatusMap[list[i].ContractRegisterId]
  1742. }
  1743. // 分币种合计金额
  1744. var amountTotal float64
  1745. sumList, e := fms.GetInvoiceListCurrencySum(cond, pars, "currency_unit")
  1746. if e != nil {
  1747. resp.FailMsg("获取失败", "获取开票/到款列表合计金额失败, Err: "+e.Error(), c)
  1748. return
  1749. }
  1750. sumMap := make(map[string]float64)
  1751. for i := range sumList {
  1752. amountTotal += sumList[i].AmountTotal
  1753. sumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  1754. }
  1755. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotal), 64)
  1756. for i := range currencyTotals {
  1757. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", sumMap[currencyTotals[i].Code]), 64)
  1758. currencyTotals[i].Amount = a
  1759. }
  1760. respData := &fms.InvoiceListRespData{
  1761. Page: page,
  1762. List: list,
  1763. AmountTotal: amountTotal,
  1764. CurrencyTotal: currencyTotals,
  1765. }
  1766. // 是否导出
  1767. if req.IsExport == 1 {
  1768. ExportInvoiceList(c, req, respData)
  1769. return
  1770. }
  1771. resp.OkData("获取成功", respData, c)
  1772. }
  1773. // ExportInvoiceList 导出开票/到款列表
  1774. func ExportInvoiceList(c *gin.Context, req fms.ContractInvoiceListReq, results *fms.InvoiceListRespData) {
  1775. list := make([]*fms.ContractInvoiceItem, 0)
  1776. if val, ok := results.List.([]*fms.ContractInvoiceItem); ok {
  1777. list = val
  1778. } else {
  1779. resp.Fail("列表数据有误", c)
  1780. return
  1781. }
  1782. if len(list) == 0 {
  1783. resp.Fail("列表数据为空", c)
  1784. return
  1785. }
  1786. listName := "开票"
  1787. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1788. listName = "到款"
  1789. }
  1790. // 生成Excel文件
  1791. xlsxFile := xlsx.NewFile()
  1792. style := xlsx.NewStyle()
  1793. alignment := xlsx.Alignment{
  1794. Horizontal: "center",
  1795. Vertical: "center",
  1796. WrapText: true,
  1797. }
  1798. style.Alignment = alignment
  1799. style.ApplyAlignment = true
  1800. sheet, err := xlsxFile.AddSheet(fmt.Sprintf("%s列表", listName))
  1801. if err != nil {
  1802. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1803. return
  1804. }
  1805. // 前两行显示合计金额, 第三行空出与列表数据隔一行
  1806. rowA := sheet.AddRow()
  1807. cellAA := rowA.AddCell()
  1808. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.AmountTotal))
  1809. rowBData := "已开票金额:"
  1810. for _, v := range results.CurrencyTotal {
  1811. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  1812. }
  1813. rowB := sheet.AddRow()
  1814. rowB.AddCell().SetString(rowBData)
  1815. sheet.AddRow()
  1816. // 列表数据表头
  1817. titles := []string{"合同编号", "套餐类型", fmt.Sprintf("%s金额", listName), "金额单位", "换算金额(元)",
  1818. fmt.Sprintf("%s日期", listName), "销售", "备注"}
  1819. titleRow := sheet.AddRow()
  1820. titleRow.SetHeight(40)
  1821. for i := range titles {
  1822. c := titleRow.AddCell()
  1823. c.SetString(titles[i])
  1824. c.SetStyle(style)
  1825. }
  1826. ServiceTemplateStrMap := map[int]string{
  1827. crm.CompanyProductFicc: "FICC套餐",
  1828. crm.CompanyProductRai: "权益套餐",
  1829. }
  1830. // 单元格赋值
  1831. for _, v := range list {
  1832. dataRow := sheet.AddRow()
  1833. dataRow.SetHeight(20)
  1834. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1835. dataRow.AddCell().SetString(ServiceTemplateStrMap[v.ServiceProductId]) // 套餐类型
  1836. dataRow.AddCell().SetString(fmt.Sprint(v.OriginAmount)) // 开票金额
  1837. dataRow.AddCell().SetString(v.UnitName) // 金额单位
  1838. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 换算金额(元)
  1839. dataRow.AddCell().SetString(v.InvoiceDate) // 开票日
  1840. dataRow.AddCell().SetString(v.SellerName) // 销售
  1841. dataRow.AddCell().SetString(v.Remark) // 备注
  1842. }
  1843. // 输出文件
  1844. var buffer bytes.Buffer
  1845. _ = xlsxFile.Write(&buffer)
  1846. content := bytes.NewReader(buffer.Bytes())
  1847. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1848. fileName := fmt.Sprintf("%s列表_%s.xlsx", listName, randStr)
  1849. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1850. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1851. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1852. }
  1853. // Import
  1854. // @Title 合同登记-导入
  1855. // @Description 合同登记-导入
  1856. // @Success 200 string "操作成功"
  1857. // @router /contract/register/import [post]
  1858. func (rg *RegisterController) Import(c *gin.Context) {
  1859. h, err := c.FormFile("File")
  1860. if err != nil {
  1861. resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  1862. return
  1863. }
  1864. ext := path.Ext(h.Filename)
  1865. if ext != ".xlsx" && ext != ".xls" {
  1866. resp.Fail("请上传Excel文件", c)
  1867. return
  1868. }
  1869. uploadDir := "static/xls"
  1870. err = os.MkdirAll(uploadDir, 766)
  1871. if err != nil {
  1872. resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  1873. return
  1874. }
  1875. uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  1876. err = c.SaveUploadedFile(h, uploadPath)
  1877. if err != nil {
  1878. resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  1879. return
  1880. }
  1881. defer func() {
  1882. _ = os.Remove(uploadPath)
  1883. }()
  1884. xlFile, err := xlsx.OpenFile(uploadPath)
  1885. if err != nil {
  1886. resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  1887. return
  1888. }
  1889. // 获取所有已登记,根据合同编号去重
  1890. contractCodeArr := make([]string, 0)
  1891. registerOB := new(fms.ContractRegister)
  1892. registerCond := ``
  1893. registerPars := make([]interface{}, 0)
  1894. registerList, e := registerOB.List(registerCond, registerPars)
  1895. if e != nil {
  1896. resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  1897. return
  1898. }
  1899. for i := range registerList {
  1900. contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  1901. }
  1902. // 获取所有销售Map
  1903. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  1904. if e != nil {
  1905. resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  1906. return
  1907. }
  1908. sellerMap := make(map[string]*crm.SellerAdminWithGroupTeam)
  1909. for i := range sellerList {
  1910. sellerMap[sellerList[i].SellerName] = sellerList[i]
  1911. }
  1912. // 获取品种权限Map
  1913. chartPermissionNameIdMap := make(map[string]int)
  1914. cpCond := `product_id = ?`
  1915. cpPars := make([]interface{}, 0)
  1916. cpPars = append(cpPars, crm.CompanyProductFicc)
  1917. cp := new(crm.ChartPermission)
  1918. permissionList, e := cp.List(cpCond, cpPars)
  1919. if e != nil {
  1920. resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  1921. return
  1922. }
  1923. for i := range permissionList {
  1924. chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1925. }
  1926. // 获取所有套餐模板
  1927. serviceTempCond := ``
  1928. serviceTempPars := make([]interface{}, 0)
  1929. serviceTempOB := new(fms.ContractServiceTemplate)
  1930. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  1931. if e != nil {
  1932. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  1933. return
  1934. }
  1935. serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
  1936. serviceTempFullNameMap := make(map[string]*fms.ContractServiceTemplate)
  1937. serviceTempIdMap := make(map[int]*fms.ContractServiceTemplate)
  1938. for i := range serviceTempList {
  1939. serviceTempIdMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  1940. serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
  1941. }
  1942. for i := range serviceTempList {
  1943. fullName := serviceTempList[i].Title
  1944. if serviceTempList[i].Pid > 0 {
  1945. parentItem := serviceTempIdMap[serviceTempList[i].Pid]
  1946. fullName += "_"+parentItem.Title
  1947. if parentItem.Pid > 0 {
  1948. fullName += "_"+serviceTempIdMap[parentItem.Pid].Title
  1949. }
  1950. }
  1951. serviceTempFullNameMap[fullName] = serviceTempList[i]
  1952. }
  1953. //权益行业套餐名称
  1954. raiIndustryMap := map[int]string{
  1955. 36:"医药",
  1956. 37:"医药",
  1957. 38:"消费",
  1958. 39:"消费",
  1959. 40:"科技",
  1960. 41:"科技",
  1961. 42:"智造",
  1962. 43:"智造",
  1963. 44:"策略",
  1964. }
  1965. // 获取货币列表及汇率(汇率为导入日的汇率)
  1966. rateList, e := fmsService.GetTodayCurrencyRateList()
  1967. if e != nil {
  1968. resp.FailData("获取货币列表及汇率失败", "Err:"+e.Error(), c)
  1969. return
  1970. }
  1971. rateMap := make(map[string]float64)
  1972. for i := range rateList {
  1973. rateMap[rateList[i].Code] = rateList[i].RMBRate
  1974. }
  1975. titleMap := make(map[int]string)
  1976. newIds := make([]int, 0)
  1977. newCompanyArr := []string{"0", "1"}
  1978. newCompanyMap := map[string]int{"0": 1, "1": 0}
  1979. contractTypeArr := []string{"0", "1", "2", "3"}
  1980. contractTypeMap := map[string]int{
  1981. "0": fms.ContractTypeRenew,
  1982. "1": fms.ContractTypeNew,
  1983. "2": fms.ContractTypeAgentPay,
  1984. "3": fms.ContractTypePlus,
  1985. }
  1986. // 更新登记状态
  1987. defer func() {
  1988. if len(newIds) > 0 {
  1989. go func() {
  1990. for i := range newIds {
  1991. fmsService.CheckContractRegisterAmount(newIds[i])
  1992. fmsService.SummaryInvoicePaymentByContractRegisterId(newIds[i])
  1993. }
  1994. }()
  1995. }
  1996. }()
  1997. invoiceMax := 3
  1998. checkDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local)
  1999. for _, sheet := range xlFile.Sheets {
  2000. // 遍历行读取
  2001. maxRow := sheet.MaxRow
  2002. for i := 0; i < maxRow; i++ {
  2003. // 第三行开始读取表头
  2004. if i == 2 {
  2005. row := sheet.Row(i)
  2006. cells := row.Cells
  2007. for k, cell := range cells {
  2008. text := cell.String()
  2009. titleMap[k] = text
  2010. // 只检验前面部分表头, 后面很多动态列
  2011. if k == 0 {
  2012. if text != "客户名称" {
  2013. resp.Fail("【客户名称】列名称有误, 请参考模板导入", c)
  2014. return
  2015. }
  2016. continue
  2017. } else if k == 1 {
  2018. if !strings.Contains(text, "新客户") {
  2019. resp.Fail("【新客户】列名称有误, 请参考模板导入", c)
  2020. return
  2021. }
  2022. continue
  2023. } else if k == 2 {
  2024. if !strings.Contains(text, "合同类型") {
  2025. resp.Fail("【合同类型】列名称有误, 请参考模板导入", c)
  2026. return
  2027. }
  2028. continue
  2029. } else if k == 3 {
  2030. if text != "FICC销售" {
  2031. resp.Fail("【FICC销售】列名称有误, 请参考模板导入", c)
  2032. return
  2033. }
  2034. continue
  2035. } else if k == 4 {
  2036. if text != "权益销售" {
  2037. resp.Fail("【权益销售】列名称有误, 请参考模板导入", c)
  2038. return
  2039. }
  2040. continue
  2041. } else if k == 5 {
  2042. if text != "FICC大套餐" {
  2043. resp.Fail("【FICC大套餐】列名称有误, 请参考模板导入", c)
  2044. return
  2045. }
  2046. continue
  2047. }
  2048. }
  2049. }else if i >= 3 {
  2050. // 数据行
  2051. row := sheet.Row(i)
  2052. cells := row.Cells
  2053. // 登记信息
  2054. rowRegister := new(fms.ContractRegister)
  2055. // 套餐
  2056. rowServices := make([]*fms.ContractService, 0)
  2057. // 套餐金额
  2058. rowServiceAmount := make([]*fms.ContractServiceAmount, 0)
  2059. // 开票/到款
  2060. rowInvoices := make([]*fms.ContractInvoice, 0)
  2061. for ir := 0; ir < invoiceMax; ir++ {
  2062. rowInvoices = append(rowInvoices, new(fms.ContractInvoice))
  2063. }
  2064. rowPayments := make([]*fms.ContractInvoice, 0)
  2065. for ir := 0; ir < invoiceMax; ir++ {
  2066. rowPayments = append(rowPayments, new(fms.ContractInvoice))
  2067. }
  2068. // 小套餐权限
  2069. rowChartPermissionIdArr := make([]string, 0)
  2070. productIds := make(map[int]struct{})
  2071. isSkip := false
  2072. for k, cell := range cells {
  2073. v := utils.TrimStr(cell.String())
  2074. // 客户名称
  2075. if k == 0 {
  2076. if v == "" {
  2077. resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
  2078. return
  2079. }
  2080. rowRegister.CompanyName = v
  2081. continue
  2082. }
  2083. // 是否新客户
  2084. if k == 1 {
  2085. if !utils.InArrayByStr(newCompanyArr, v) {
  2086. resp.Fail(fmt.Sprintf("第%d行新客户有误, 请按模板导入", i+1), c)
  2087. return
  2088. }
  2089. rowRegister.NewCompany = newCompanyMap[v]
  2090. continue
  2091. }
  2092. // 合同类型
  2093. if k == 2 {
  2094. if !utils.InArrayByStr(contractTypeArr, v) {
  2095. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  2096. return
  2097. }
  2098. rowRegister.ContractType = contractTypeMap[v]
  2099. if rowRegister.ContractType == 0 {
  2100. resp.Fail(fmt.Sprintf("第%d行合同类型匹配有误, 请按模板导入", i+1), c)
  2101. return
  2102. }
  2103. continue
  2104. }
  2105. // FICC销售
  2106. if k == 3 {
  2107. if v != "" {
  2108. /*resp.Fail(fmt.Sprintf("第%d行销售名称不可为空, 请按模板导入", i+1), c)
  2109. return*/
  2110. sellerItem := sellerMap[v]
  2111. if sellerItem == nil {
  2112. resp.Fail(fmt.Sprintf("第%d行销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2113. return
  2114. }
  2115. rowRegister.SellerId = sellerItem.SellerId
  2116. rowRegister.SellerName = sellerItem.SellerName
  2117. }
  2118. continue
  2119. }
  2120. // 权益销售
  2121. if k == 4 {
  2122. if v == "" && rowRegister.SellerName == "" {
  2123. resp.Fail(fmt.Sprintf("第FICC销售名称和权益销售名称不可都为空, 请按模板导入", i+1), c)
  2124. return
  2125. }
  2126. sellerItem := sellerMap[v]
  2127. if sellerItem == nil {
  2128. resp.Fail(fmt.Sprintf("第%d行权益销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2129. return
  2130. }
  2131. rowRegister.RaiSellerId = sellerItem.SellerId
  2132. rowRegister.RaiSellerName = sellerItem.SellerName
  2133. continue
  2134. }
  2135. // FICC大套餐
  2136. if k == 5 {
  2137. if v == "是" {
  2138. tempItem := serviceTempNameMap[titleMap[k]]
  2139. if tempItem == nil {
  2140. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2141. return
  2142. }
  2143. cs := &fms.ContractService{
  2144. ProductId: crm.CompanyProductFicc,
  2145. ServiceTemplateId: tempItem.ServiceTemplateId,
  2146. Title: tempItem.Title,
  2147. Value: tempItem.Value,
  2148. TableValue: tempItem.TableValue,
  2149. ChartPermissionId: tempItem.ChartPermissionId,
  2150. }
  2151. cs.Set()
  2152. rowServices = append(rowServices, cs)
  2153. productIds[crm.CompanyProductFicc] = struct{}{}
  2154. }
  2155. continue
  2156. }
  2157. // FICC小套餐
  2158. if k >= 6 && k <= 26 {
  2159. // 小套餐权限
  2160. if v == "是" {
  2161. rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
  2162. productIds[crm.CompanyProductFicc] = struct{}{}
  2163. }
  2164. continue
  2165. }
  2166. // 其他类型套餐
  2167. if k >= 27 && k <= 33 {
  2168. if v == "是" {
  2169. tempItem := serviceTempNameMap[titleMap[k]]
  2170. if tempItem == nil {
  2171. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2172. return
  2173. }
  2174. cs := &fms.ContractService{
  2175. ProductId: crm.CompanyProductFicc,
  2176. ServiceTemplateId: tempItem.ServiceTemplateId,
  2177. Title: tempItem.Title,
  2178. Value: tempItem.Value,
  2179. TableValue: tempItem.TableValue,
  2180. ChartPermissionId: tempItem.ChartPermissionId,
  2181. }
  2182. cs.Set()
  2183. rowServices = append(rowServices, cs)
  2184. productIds[crm.CompanyProductFicc] = struct{}{}
  2185. }
  2186. continue
  2187. }
  2188. if k >=34 && k<=44 {
  2189. if v == "是" {
  2190. // 权益大套餐
  2191. if k <= 35 {
  2192. //新增
  2193. parentName := "权益大套餐"
  2194. tempItem := serviceTempNameMap[titleMap[k]]
  2195. if tempItem == nil {
  2196. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2197. return
  2198. }
  2199. cs := &fms.ContractService{
  2200. ProductId: crm.CompanyProductFicc,
  2201. ServiceTemplateId: tempItem.ServiceTemplateId,
  2202. Title: tempItem.Title,
  2203. Value: tempItem.Value,
  2204. TableValue: tempItem.TableValue,
  2205. ChartPermissionId: tempItem.ChartPermissionId,
  2206. }
  2207. rowServices = append(rowServices, cs)
  2208. tempItem = serviceTempNameMap[parentName]
  2209. if tempItem == nil {
  2210. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2211. return
  2212. }
  2213. cs = &fms.ContractService{
  2214. ProductId: crm.CompanyProductRai,
  2215. ServiceTemplateId: tempItem.ServiceTemplateId,
  2216. Title: tempItem.Title,
  2217. Value: tempItem.Value,
  2218. TableValue: tempItem.TableValue,
  2219. ChartPermissionId: tempItem.ChartPermissionId,
  2220. }
  2221. rowServices = append(rowServices, cs)
  2222. } else {
  2223. rootName := "行业套餐"
  2224. // 新增三条套餐信息
  2225. parentName, _ := raiIndustryMap[k]
  2226. childName := titleMap[k]
  2227. fullName := childName+"_"+parentName+"_"+rootName
  2228. if fullName != "" {
  2229. //增加三级权限
  2230. tempItem := serviceTempFullNameMap[fullName]
  2231. if tempItem == nil {
  2232. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2233. return
  2234. }
  2235. cs := &fms.ContractService{
  2236. ProductId: crm.CompanyProductRai,
  2237. ServiceTemplateId: tempItem.ServiceTemplateId,
  2238. Title: tempItem.Title,
  2239. Value: tempItem.Value,
  2240. TableValue: tempItem.TableValue,
  2241. ChartPermissionId: tempItem.ChartPermissionId,
  2242. }
  2243. rowServices = append(rowServices, cs)
  2244. //增加二级权限
  2245. tempItem = serviceTempFullNameMap[parentName+"_"+rootName]
  2246. if tempItem == nil {
  2247. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2248. return
  2249. }
  2250. cs = &fms.ContractService{
  2251. ProductId: crm.CompanyProductRai,
  2252. ServiceTemplateId: tempItem.ServiceTemplateId,
  2253. Title: tempItem.Title,
  2254. Value: tempItem.Value,
  2255. TableValue: tempItem.TableValue,
  2256. ChartPermissionId: tempItem.ChartPermissionId,
  2257. }
  2258. rowServices = append(rowServices, cs)
  2259. //增加一级权限
  2260. tempItem = serviceTempFullNameMap[rootName]
  2261. if tempItem == nil {
  2262. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2263. return
  2264. }
  2265. cs = &fms.ContractService{
  2266. ProductId: crm.CompanyProductRai,
  2267. ServiceTemplateId: tempItem.ServiceTemplateId,
  2268. Title: tempItem.Title,
  2269. Value: tempItem.Value,
  2270. TableValue: tempItem.TableValue,
  2271. ChartPermissionId: tempItem.ChartPermissionId,
  2272. }
  2273. rowServices = append(rowServices, cs)
  2274. }
  2275. }
  2276. productIds[crm.CompanyProductRai] = struct{}{}
  2277. }
  2278. continue
  2279. }
  2280. // 权益研选等套餐
  2281. if k >= 45 && k<=49 {
  2282. if v == "是" {
  2283. tempItem := serviceTempNameMap[titleMap[k]]
  2284. if tempItem == nil {
  2285. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2286. return
  2287. }
  2288. cs := &fms.ContractService{
  2289. ProductId: crm.CompanyProductRai,
  2290. ServiceTemplateId: tempItem.ServiceTemplateId,
  2291. Title: tempItem.Title,
  2292. Value: tempItem.Value,
  2293. TableValue: tempItem.TableValue,
  2294. ChartPermissionId: tempItem.ChartPermissionId,
  2295. }
  2296. cs.Set()
  2297. rowServices = append(rowServices, cs)
  2298. productIds[crm.CompanyProductRai] = struct{}{}
  2299. }
  2300. continue
  2301. }
  2302. // 套餐备注
  2303. if k == 50 {
  2304. rowRegister.ServiceRemark = v
  2305. continue
  2306. }
  2307. // 开始时间/到期时间
  2308. if k == 51 {
  2309. // 转换失败可能是因为格式为Excel日期格式, 读取出来会是一串数字, 将其转换成日期字符串再处理
  2310. va := cell.Value
  2311. if va == "" {
  2312. resp.Fail(fmt.Sprintf("第%d行开始时间不可为空, 请按模板导入", i+1), c)
  2313. return
  2314. }
  2315. startDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2316. if e != nil {
  2317. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2318. startDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2319. if e != nil {
  2320. resp.Fail(fmt.Sprintf("第%d行开始时间格式转换有误, 请按模板导入", i+1), c)
  2321. return
  2322. }
  2323. }
  2324. // 转换后的日期小于1900-01-01表示当前生成的日期是有问题的
  2325. if startDate.Before(checkDate) {
  2326. resp.Fail(fmt.Sprintf("第%d行开始时间格式有误, 请按模板导入", i+1), c)
  2327. return
  2328. }
  2329. rowRegister.StartDate = startDate
  2330. continue
  2331. }
  2332. if k == 52 {
  2333. va := cell.Value
  2334. if va == "" {
  2335. resp.Fail(fmt.Sprintf("第%d行到期时间不可为空, 请按模板导入", i+1), c)
  2336. return
  2337. }
  2338. endDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2339. if e != nil {
  2340. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2341. endDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2342. if e != nil {
  2343. resp.Fail(fmt.Sprintf("第%d行到期时间格式转换有误, 请按模板导入", i+1), c)
  2344. return
  2345. }
  2346. }
  2347. if endDate.Before(checkDate) {
  2348. resp.Fail(fmt.Sprintf("第%d行到期时间格式有误, 请按模板导入", i+1), c)
  2349. return
  2350. }
  2351. rowRegister.EndDate = endDate
  2352. continue
  2353. }
  2354. // 合同金额
  2355. if k == 53 {
  2356. amountStr := v
  2357. amount, e := strconv.ParseFloat(amountStr, 64)
  2358. if e != nil {
  2359. resp.Fail(fmt.Sprintf("第%d行合同金额有误, 请按模板导入", i+1), c)
  2360. return
  2361. }
  2362. rowRegister.ContractAmount = amount
  2363. continue
  2364. }
  2365. // 金额单位
  2366. if k == 54 {
  2367. rate := rateMap[v]
  2368. if rate <= 0 {
  2369. resp.Fail(fmt.Sprintf("第%d行金额单位有误, 请按模板导入", i+1), c)
  2370. return
  2371. }
  2372. rowRegister.CurrencyUnit = v
  2373. rowRegister.RMBRate = rate
  2374. continue
  2375. }
  2376. // FICC 套餐总金额
  2377. if k == 55 {
  2378. amountStr := v
  2379. amount, e := strconv.ParseFloat(amountStr, 64)
  2380. if e != nil {
  2381. resp.Fail(fmt.Sprintf("第%d行FICC套餐总金额有误, 请按模板导入", i+1), c)
  2382. return
  2383. }
  2384. if amount > 0 {
  2385. tmp := &fms.ContractServiceAmount{
  2386. ProductId: crm.CompanyProductFicc,
  2387. ServiceAmount: amount,
  2388. CurrencyUnit: rowRegister.CurrencyUnit,
  2389. TimeBase: base.TimeBase{},
  2390. }
  2391. rowServiceAmount = append(rowServiceAmount, tmp)
  2392. }
  2393. continue
  2394. }
  2395. // 权益套餐总金额
  2396. if k == 56 {
  2397. amountStr := v
  2398. amount, e := strconv.ParseFloat(amountStr, 64)
  2399. if e != nil {
  2400. resp.Fail(fmt.Sprintf("第%d行权益套餐总金额有误, 请按模板导入", i+1), c)
  2401. return
  2402. }
  2403. if amount > 0 {
  2404. tmp := &fms.ContractServiceAmount{
  2405. ProductId: crm.CompanyProductRai,
  2406. ServiceAmount: amount,
  2407. CurrencyUnit: rowRegister.CurrencyUnit,
  2408. TimeBase: base.TimeBase{},
  2409. }
  2410. rowServiceAmount = append(rowServiceAmount, tmp)
  2411. }
  2412. continue
  2413. }
  2414. // 约定付款日期
  2415. if k == 57 {
  2416. rowRegister.AgreedPayTime = v
  2417. continue
  2418. }
  2419. // 签订日
  2420. if k == 58 {
  2421. va := cell.Value
  2422. if va == "" {
  2423. continue
  2424. }
  2425. signDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2426. if e != nil {
  2427. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2428. signDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2429. if e != nil {
  2430. resp.Fail(fmt.Sprintf("第%d行签订日格式转换有误, 请按模板导入", i+1), c)
  2431. return
  2432. }
  2433. }
  2434. if signDate.Before(checkDate) {
  2435. resp.Fail(fmt.Sprintf("第%d行签订日格式有误, 请按模板导入", i+1), c)
  2436. return
  2437. }
  2438. rowRegister.SignDate = signDate
  2439. continue
  2440. }
  2441. // 合同状态
  2442. if k == 59 {
  2443. rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
  2444. if rowRegister.ContractStatus == 0 {
  2445. resp.Fail(fmt.Sprintf("第%d行合同状态不匹配, 请按模板导入", i+1), c)
  2446. return
  2447. }
  2448. continue
  2449. }
  2450. // 合同编号
  2451. if k == 60 {
  2452. rowContractCode := v
  2453. if rowContractCode == "" {
  2454. resp.Fail(fmt.Sprintf("第%d行合同编号不可为空, 请按模板导入", i+1), c)
  2455. return
  2456. }
  2457. if utils.InArrayByStr(contractCodeArr, rowContractCode) {
  2458. // 此合同已登记, 跳过本行的读取
  2459. isSkip = true
  2460. break
  2461. }
  2462. rowRegister.ContractCode = rowContractCode
  2463. continue
  2464. }
  2465. // 合规备注
  2466. if k == 61 {
  2467. rowRegister.Remark = v
  2468. continue
  2469. }
  2470. // 开票列表
  2471. k2 := 61
  2472. for ir := 0; ir < invoiceMax; ir++ {
  2473. n := ir + 1
  2474. // 开票日
  2475. k2 += 1
  2476. if k == k2 {
  2477. if v != "" {
  2478. va := cell.Value
  2479. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2480. if e != nil {
  2481. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2482. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2483. if e != nil {
  2484. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式转换有误, 请按模板导入", i+1, n), c)
  2485. return
  2486. }
  2487. }
  2488. if invoiceDate.Before(checkDate) {
  2489. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式有误, 请按模板导入", i+1, n), c)
  2490. return
  2491. }
  2492. rowInvoices[ir].InvoiceDate = invoiceDate
  2493. rowInvoices[ir].ContractCode = rowRegister.ContractCode
  2494. rowInvoices[ir].InvoiceType = fms.ContractInvoiceTypeMake
  2495. }
  2496. continue
  2497. }
  2498. // 开票金额
  2499. k2 += 1
  2500. if k == k2 {
  2501. if v != "" {
  2502. amountStr := v
  2503. amount, e := strconv.ParseFloat(amountStr, 64)
  2504. if e != nil {
  2505. resp.Fail(fmt.Sprintf("第%d行开票金额%d有误, 请按模板导入", i+1, n), c)
  2506. return
  2507. }
  2508. if rowRegister.RMBRate <= 0 {
  2509. resp.Fail(fmt.Sprintf("第%d行开票金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  2510. return
  2511. }
  2512. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  2513. rowInvoices[ir].OriginAmount = amount
  2514. rowInvoices[ir].Amount = a
  2515. }
  2516. continue
  2517. }
  2518. // 开票套餐类型
  2519. k2 += 1
  2520. if k == k2 {
  2521. if v != "" {
  2522. if v == "FICC套餐" {
  2523. rowInvoices[ir].ServiceProductId = crm.CompanyProductFicc
  2524. }else if v == "权益套餐"{
  2525. rowInvoices[ir].ServiceProductId = crm.CompanyProductRai
  2526. }else{
  2527. resp.Fail(fmt.Sprintf("第%d行开票套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  2528. return
  2529. }
  2530. }
  2531. continue
  2532. }
  2533. // 开票销售
  2534. k2 += 1
  2535. if k == k2 {
  2536. if v != "" {
  2537. sellerItem := sellerMap[v]
  2538. if sellerItem == nil {
  2539. resp.Fail(fmt.Sprintf("第%d行开票销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2540. return
  2541. }
  2542. rowInvoices[ir].SellerId = sellerItem.SellerId
  2543. rowInvoices[ir].SellerName = sellerItem.SellerName
  2544. rowInvoices[ir].SellerGroupId = sellerItem.GroupId
  2545. rowInvoices[ir].SellerGroupName = sellerItem.GroupName
  2546. rowInvoices[ir].SellerTeamId = sellerItem.TeamId
  2547. rowInvoices[ir].SellerTeamName = sellerItem.TeamName
  2548. }
  2549. continue
  2550. }
  2551. // 备注
  2552. k2 += 1
  2553. if k == k2 {
  2554. if v != "" {
  2555. rowInvoices[ir].Remark = v
  2556. }
  2557. continue
  2558. }
  2559. }
  2560. // 到款列表
  2561. for ir := 0; ir < invoiceMax; ir++ {
  2562. n := ir + 1
  2563. // 到款日
  2564. k2 += 1
  2565. if k == k2 {
  2566. if v != "" {
  2567. va := cell.Value
  2568. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2569. if e != nil {
  2570. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2571. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2572. if e != nil {
  2573. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式转换有误, 请按模板导入", i+1, n), c)
  2574. return
  2575. }
  2576. }
  2577. if invoiceDate.Before(checkDate) {
  2578. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式有误, 请按模板导入", i+1, n), c)
  2579. return
  2580. }
  2581. rowPayments[ir].InvoiceDate = invoiceDate
  2582. rowPayments[ir].ContractCode = rowRegister.ContractCode
  2583. rowPayments[ir].InvoiceType = fms.ContractInvoiceTypePay
  2584. }
  2585. continue
  2586. }
  2587. // 到款金额
  2588. k2 += 1
  2589. if k == k2 {
  2590. if v != "" {
  2591. amountStr := v
  2592. amount, e := strconv.ParseFloat(amountStr, 64)
  2593. if e != nil {
  2594. resp.Fail(fmt.Sprintf("第%d行到款金额%d有误, 请按模板导入", i+1, n), c)
  2595. return
  2596. }
  2597. if rowRegister.RMBRate <= 0 {
  2598. resp.Fail(fmt.Sprintf("第%d行到款金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  2599. return
  2600. }
  2601. // 付款方式
  2602. dayDiff := rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
  2603. contractAmount := rowRegister.ContractAmount
  2604. payType := fmsService.CalculateContractPaymentType(amount, contractAmount, dayDiff)
  2605. rowPayments[ir].PayType = payType
  2606. rowPayments[ir].OriginAmount = amount
  2607. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  2608. rowPayments[ir].Amount = a
  2609. }
  2610. continue
  2611. }
  2612. // 到款套餐类型
  2613. k2 += 1
  2614. if k == k2 {
  2615. if v != "" {
  2616. if v == "FICC套餐" {
  2617. rowPayments[ir].ServiceProductId = crm.CompanyProductFicc
  2618. }else if v == "权益套餐"{
  2619. rowPayments[ir].ServiceProductId = crm.CompanyProductRai
  2620. }else{
  2621. resp.Fail(fmt.Sprintf("第%d行到款套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  2622. return
  2623. }
  2624. }
  2625. continue
  2626. }
  2627. // 备注
  2628. k2 += 1
  2629. if k == k2 {
  2630. if v != "" {
  2631. rowPayments[ir].Remark = v
  2632. }
  2633. continue
  2634. }
  2635. }
  2636. }
  2637. if isSkip {
  2638. continue
  2639. }
  2640. // 小套餐
  2641. if len(rowChartPermissionIdArr) > 0 {
  2642. // 说明有小套餐
  2643. tempItem := serviceTempNameMap["FICC小套餐"]
  2644. if tempItem == nil {
  2645. resp.Fail(fmt.Sprintf("第%d行小套餐名称不匹配, 请按模板导入", i+1), c)
  2646. return
  2647. }
  2648. rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
  2649. cs := &fms.ContractService{
  2650. ProductId: crm.CompanyProductFicc,
  2651. ServiceTemplateId: tempItem.ServiceTemplateId,
  2652. Title: tempItem.Title,
  2653. Value: tempItem.Value,
  2654. TableValue: tempItem.TableValue,
  2655. ChartPermissionId: tempItem.ChartPermissionId,
  2656. ChartPermissionIds: rowChartPermissionIds,
  2657. }
  2658. cs.Set()
  2659. rowServices = append(rowServices, cs)
  2660. }
  2661. // 如果导入的最后一条合同编号为空并且合同编号之后的字段均为空
  2662. // excel这个包读行的时候不会再往后面没数据的地方读取, 所以此处需要重新判断一次
  2663. if rowRegister.ContractCode == "" {
  2664. resp.Fail(fmt.Sprintf("第%d行合同编号为空", i+1), c)
  2665. return
  2666. }
  2667. rowRegister.RegisterStatus = fms.ContractRegisterStatusIng
  2668. rowInvoiceList := make([]*fms.ContractInvoice, 0)
  2669. // 过滤信息不完整的开票到款
  2670. for l := range rowInvoices {
  2671. if rowInvoices[l].ContractCode != "" {
  2672. if rowInvoices[l].OriginAmount <= 0 || rowInvoices[l].SellerId == 0 {
  2673. resp.Fail(fmt.Sprintf("第%d行开票信息必填项不完整", i+1), c)
  2674. return
  2675. }
  2676. rowInvoiceList = append(rowInvoiceList, rowInvoices[l])
  2677. }
  2678. }
  2679. for l := range rowPayments {
  2680. if rowPayments[l].ContractCode != "" {
  2681. if rowPayments[l].OriginAmount <= 0 {
  2682. resp.Fail(fmt.Sprintf("第%d行到款信息必填项不完整", i+1), c)
  2683. return
  2684. }
  2685. rowInvoiceList = append(rowInvoiceList, rowPayments[l])
  2686. }
  2687. }
  2688. // 新增登记、套餐、开票到款信息
  2689. for proId, _ := range productIds {
  2690. rowRegister.ProductIds += strconv.Itoa(proId)+","
  2691. }
  2692. rowRegister.ProductIds = strings.Trim(rowRegister.ProductIds, ",")
  2693. newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, rowInvoiceList, rowServiceAmount)
  2694. if e != nil {
  2695. resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
  2696. return
  2697. }
  2698. // 自动分配套餐金额
  2699. go fmsService.CalculatePaymentServiceAmount(newId)
  2700. newIds = append(newIds, newId)
  2701. }
  2702. }
  2703. }
  2704. resp.Ok("操作成功", c)
  2705. }
  2706. // CurrencyList
  2707. // @Title 货币单位列表
  2708. // @Description 货币单位列表
  2709. // @Success 200 {object} fms.CurrencyUnitItem
  2710. // @router /contract/register/currency_list [get]
  2711. func (rg *RegisterController) CurrencyList(c *gin.Context) {
  2712. list, e := fmsService.GetTodayCurrencyRateList()
  2713. if e != nil {
  2714. resp.FailData("获取失败", "获取今日货币汇率列表失败, Err: "+e.Error(), c)
  2715. return
  2716. }
  2717. resp.OkData("获取成功", list, c)
  2718. }
  2719. // CheckContractName
  2720. // @Title 货币单位列表
  2721. // @Description 货币单位列表
  2722. // @Success 200 {object} fms.CheckContractNameResp
  2723. // @router /contract/register/check_contract_code [get]
  2724. func (rg *RegisterController) CheckContractName(c *gin.Context) {
  2725. var req fms.CheckContractNameReq
  2726. if e := c.BindQuery(&req); e != nil {
  2727. err, ok := e.(validator.ValidationErrors)
  2728. if !ok {
  2729. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  2730. return
  2731. }
  2732. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  2733. return
  2734. }
  2735. existCond :=""
  2736. existPars := make([]interface{}, 0)
  2737. if req.CompanyName != "" {
  2738. // 是否存在相同的合同名称的登记
  2739. existCond = ` company_name = ?`
  2740. existPars = append(existPars, req.CompanyName)
  2741. }
  2742. if req.StartDate != "" && req.EndDate != "" {
  2743. // 日期校验
  2744. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  2745. if e != nil {
  2746. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  2747. return
  2748. }
  2749. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  2750. if e != nil {
  2751. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  2752. return
  2753. }
  2754. if existCond != "" {
  2755. existCond += ` or (start_date =? and end_date=?)`
  2756. }else{
  2757. existCond = ` start_date = ? and end_date=?`
  2758. }
  2759. existPars = append(existPars, startDate, endDate)
  2760. }
  2761. if existCond == "" {
  2762. resp.Fail("请输入合同名称或者合同有效期", c)
  2763. return
  2764. }
  2765. // 是否存在相同合同名称的登记
  2766. ob := new(fms.ContractRegister)
  2767. data := fms.CheckContractNameResp{
  2768. Exist: 0,
  2769. }
  2770. _, e := ob.FetchByCondition(existCond, existPars)
  2771. if e != nil {
  2772. if e == utils.ErrNoRow {
  2773. resp.OkData("查询成功", data, c)
  2774. return
  2775. }
  2776. resp.FailMsg("查询失败", "查询相同登记号失败, Err: "+e.Error(), c)
  2777. return
  2778. }
  2779. data.Exist = 1
  2780. resp.OkData("查询成功", data, c)
  2781. return
  2782. }