register.go 126 KB

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