register.go 95 KB

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