register.go 97 KB

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