register.go 124 KB

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