register.go 113 KB

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