register.go 97 KB

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