register.go 126 KB

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