register.go 114 KB

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