register.go 106 KB

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