register.go 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964
  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. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  1403. //修改对应到款的销售
  1404. summaryItem, err := fms.GetInvoicePaymentSummaryByRegisterIdAndInvoiceId(req.ContractRegisterId, req.AmountList[i].InvoiceId)
  1405. if err != nil {
  1406. resp.FailMsg("获取汇总数据失败", "修改到款销售时获取汇总数据失败, Err: "+err.Error(), c)
  1407. return
  1408. }
  1409. if summaryItem.PaymentId > 0 {
  1410. paymentItem := fms.ContractInvoice{}
  1411. paymentItem.ContractInvoiceId = summaryItem.PaymentId
  1412. paymentItem.SellerId = sellerItem.SellerId
  1413. paymentItem.SellerName = sellerItem.SellerName
  1414. paymentItem.SellerGroupId = sellerItem.GroupId
  1415. paymentItem.SellerGroupName = sellerItem.GroupName
  1416. paymentItem.SellerTeamId = sellerItem.TeamId
  1417. paymentItem.SellerTeamName = sellerItem.TeamName
  1418. e = paymentItem.Update([]string{"SellerId", "SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName"})
  1419. if e != nil {
  1420. resp.FailMsg("更新到款销售失败", "更新到款销售失败, Err: "+e.Error(), c)
  1421. return
  1422. }
  1423. }
  1424. }
  1425. noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
  1426. continue
  1427. }
  1428. if req.AmountList[i].InvoiceId == 0 {
  1429. v := &fms.ContractInvoice{
  1430. ContractRegisterId: req.ContractRegisterId,
  1431. ContractCode: item.ContractCode,
  1432. Amount: req.AmountList[i].Amount,
  1433. OriginAmount: req.AmountList[i].OriginAmount,
  1434. CurrencyUnit: item.CurrencyUnit,
  1435. InvoiceType: req.InvoiceType,
  1436. ServiceProductId: req.AmountList[i].ServiceProductId,
  1437. InvoiceDate: t,
  1438. AdminId: int(adminInfo.AdminId),
  1439. AdminName: adminInfo.RealName,
  1440. Remark: req.AmountList[i].Remark,
  1441. }
  1442. v.Set()
  1443. // 开票登记-销售信息
  1444. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  1445. sellerItem := sellerMap[req.AmountList[i].SellerId]
  1446. if sellerItem == nil {
  1447. resp.Fail("销售信息异常", c)
  1448. return
  1449. }
  1450. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  1451. resp.Fail("销售类型和所选套餐类型不一致", c)
  1452. return
  1453. }
  1454. v.SellerId = sellerItem.SellerId
  1455. v.SellerName = sellerItem.SellerName
  1456. v.SellerGroupId = sellerItem.GroupId
  1457. v.SellerGroupName = sellerItem.GroupName
  1458. v.SellerTeamId = sellerItem.TeamId
  1459. v.SellerTeamName = sellerItem.TeamName
  1460. }
  1461. // 到款登记-付款方式
  1462. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1463. sellerItem := sellerMap[req.AmountList[i].SellerId]
  1464. if sellerItem == nil {
  1465. resp.Fail("销售信息异常", c)
  1466. return
  1467. }
  1468. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  1469. resp.Fail("销售类型和所选套餐类型不一致", c)
  1470. return
  1471. }
  1472. v.SellerId = sellerItem.SellerId
  1473. v.SellerName = sellerItem.SellerName
  1474. v.SellerGroupId = sellerItem.GroupId
  1475. v.SellerGroupName = sellerItem.GroupName
  1476. v.SellerTeamId = sellerItem.TeamId
  1477. v.SellerTeamName = sellerItem.TeamName
  1478. v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
  1479. }
  1480. newInvoice = append(newInvoice, v)
  1481. }
  1482. }
  1483. }
  1484. // 获取原有的登记信息
  1485. invoiceCond := `contract_register_id = ? AND invoice_type = ? `
  1486. invoicePars := make([]interface{}, 0)
  1487. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  1488. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  1489. if e != nil {
  1490. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  1491. return
  1492. }
  1493. // 比对原有和现有的登记信息
  1494. logList := make([]*fms.ContractRegisterLog, 0)
  1495. opData := ""
  1496. opDataByte, e := json.Marshal(req)
  1497. if e != nil {
  1498. return
  1499. }
  1500. opData = string(opDataByte)
  1501. opType := fms.ContractRegisterOpTypeInvoice
  1502. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1503. opType = fms.ContractRegisterOpTypePayment
  1504. }
  1505. nowTime := time.Now().Local()
  1506. // 需要删除的记录
  1507. deleteInvoiceIds := make([]int, 0)
  1508. for i := range originInvoiceList {
  1509. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  1510. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  1511. logList = append(logList, &fms.ContractRegisterLog{
  1512. ContractRegisterId: req.ContractRegisterId,
  1513. AdminId: int(adminInfo.AdminId),
  1514. AdminName: adminInfo.RealName,
  1515. OpData: opData,
  1516. OpType: opType,
  1517. CreateTime: nowTime,
  1518. AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  1519. })
  1520. }
  1521. }
  1522. // 新增的记录
  1523. if len(newInvoice) > 0 {
  1524. newAmount := decimal.NewFromFloat(0).Round(2)
  1525. for i := range newInvoice {
  1526. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  1527. newAmount = newAmount.Add(a)
  1528. }
  1529. ia, _ := newAmount.Round(2).Float64()
  1530. logList = append(logList, &fms.ContractRegisterLog{
  1531. ContractRegisterId: req.ContractRegisterId,
  1532. AdminId: int(adminInfo.AdminId),
  1533. AdminName: adminInfo.RealName,
  1534. OpData: opData,
  1535. OpType: opType,
  1536. CreateTime: nowTime,
  1537. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  1538. })
  1539. }
  1540. // 删除并新增登记
  1541. ob := new(fms.ContractInvoice)
  1542. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  1543. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  1544. return
  1545. }
  1546. // todo 判断是否符合均分金额的条件,如果符合,需要生成金额分配记录表
  1547. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1548. err = fmsService.CalculatePaymentServiceAmount(req.ContractRegisterId)
  1549. if err != nil {
  1550. resp.FailMsg("自动分配金额失败", "自动分配金额失败, Err: "+err.Error(), c)
  1551. return
  1552. }
  1553. }
  1554. // 校验金额-是否修改状态
  1555. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  1556. // 开票到款汇总
  1557. fmsService.SummaryInvoicePaymentByContractRegisterId(req.ContractRegisterId)
  1558. //如果是开票,强制修改到款记录的销售
  1559. if len(newInvoice) > 0 && req.InvoiceType == fms.ContractInvoiceTypeMake {
  1560. for _, invoice := range newInvoice {
  1561. summaryItem, err := fms.GetInvoicePaymentSummaryByRegisterIdAndInvoiceId(req.ContractRegisterId, invoice.ContractInvoiceId)
  1562. if err != nil {
  1563. resp.FailMsg("获取汇总数据失败", "修改到款销售时获取汇总数据失败, Err: "+err.Error(), c)
  1564. return
  1565. }
  1566. sellerItem := sellerMap[invoice.SellerId]
  1567. if sellerItem == nil {
  1568. resp.Fail("销售信息异常", c)
  1569. return
  1570. }
  1571. if summaryItem.PaymentId > 0 {
  1572. paymentItem := fms.ContractInvoice{}
  1573. paymentItem.ContractInvoiceId = summaryItem.PaymentId
  1574. paymentItem.SellerId = sellerItem.SellerId
  1575. paymentItem.SellerName = sellerItem.SellerName
  1576. paymentItem.SellerGroupId = sellerItem.GroupId
  1577. paymentItem.SellerGroupName = sellerItem.GroupName
  1578. paymentItem.SellerTeamId = sellerItem.TeamId
  1579. paymentItem.SellerTeamName = sellerItem.TeamName
  1580. e = paymentItem.Update([]string{"SellerId", "SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName"})
  1581. if e != nil {
  1582. resp.FailMsg("更新到款销售失败", "更新到款销售失败, Err: "+e.Error(), c)
  1583. return
  1584. }
  1585. }
  1586. }
  1587. }
  1588. // 操作日志
  1589. go func() {
  1590. logOB := new(fms.ContractRegisterLog)
  1591. if e := logOB.AddInBatches(logList); e != nil {
  1592. return
  1593. }
  1594. }()
  1595. resp.Ok("操作成功", c)
  1596. }
  1597. // Export
  1598. // @Title 合同登记-导出
  1599. // @Description 合同登记-导出
  1600. // @Param Keyword query string false "关键词"
  1601. // @Param StartDate query string false "合同开始日期"
  1602. // @Param EndDate query string false "合同结束日期"
  1603. // @Param ServiceType query int false "套餐类型"
  1604. // @Param ContractType query string false "合同类型"
  1605. // @Param RegisterStatus query int false "登记状态"
  1606. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1607. // @Success 200 string "操作成功"
  1608. // @router /contract/register/export [get]
  1609. func (rg *RegisterController) Export(c *gin.Context) {
  1610. var req fms.ContractRegisterListReq
  1611. if e := c.BindQuery(&req); e != nil {
  1612. err, ok := e.(validator.ValidationErrors)
  1613. if !ok {
  1614. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1615. return
  1616. }
  1617. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1618. return
  1619. }
  1620. cond := `1 = 1`
  1621. pars := make([]interface{}, 0)
  1622. // 合同编号/客户姓名/销售/实际使用方
  1623. if req.Keyword != "" {
  1624. kw := "%" + req.Keyword + "%"
  1625. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  1626. pars = append(pars, kw, kw, kw, kw)
  1627. }
  1628. if req.StartDate != "" && req.EndDate != "" {
  1629. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1630. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1631. cond += ` AND (create_time BETWEEN ? AND ?)`
  1632. pars = append(pars, st, ed)
  1633. }
  1634. if req.ContractType != "" {
  1635. newCond := ""
  1636. typeSlices := strings.Split(req.ContractType, ",")
  1637. for _, v := range typeSlices {
  1638. if v[:1] == "0" {
  1639. //自付
  1640. if v[1:] == "1" {
  1641. newCond += ` (contract_type = 1 AND has_payment=0) `
  1642. } else if v[1:] == "2" {
  1643. newCond += ` (contract_type = 2 AND has_payment=0) `
  1644. } else {
  1645. newCond += ` (contract_type = 4 AND has_payment=0) `
  1646. }
  1647. } else {
  1648. //代付
  1649. if v[1:] == "1" {
  1650. newCond += ` (contract_type = 1 AND has_payment=1) `
  1651. } else if v[1:] == "2" {
  1652. newCond += ` (contract_type = 2 AND has_payment=1) `
  1653. } else {
  1654. newCond += ` (contract_type = 4 AND has_payment=1) `
  1655. }
  1656. }
  1657. newCond += " OR "
  1658. }
  1659. newCond = strings.TrimRight(newCond, "OR ")
  1660. cond += " AND " + "(" + newCond + ")"
  1661. }
  1662. if req.RegisterStatus != 0 {
  1663. cond += ` AND register_status = ?`
  1664. pars = append(pars, req.RegisterStatus)
  1665. }
  1666. if req.ServiceTypes != "" {
  1667. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1668. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1669. if e != nil {
  1670. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1671. return
  1672. }
  1673. if len(registerIds) > 0 {
  1674. cond += ` AND contract_register_id IN ?`
  1675. pars = append(pars, registerIds)
  1676. } else {
  1677. cond += ` AND 1 = 2`
  1678. }
  1679. }
  1680. if req.ListParam == 1 {
  1681. cond += ` AND product_ids = '1' `
  1682. } else if req.ListParam == 2 {
  1683. cond += ` AND product_ids = '2' `
  1684. }
  1685. // 获取列表数据
  1686. cr := new(fms.ContractRegister)
  1687. list, e := cr.List(cond, pars)
  1688. if e != nil {
  1689. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  1690. return
  1691. }
  1692. if len(list) == 0 {
  1693. resp.Fail("无有效数据可导出", c)
  1694. return
  1695. }
  1696. registerIds := make([]int, 0)
  1697. for i := range list {
  1698. registerIds = append(registerIds, list[i].ContractRegisterId)
  1699. }
  1700. // 获取小套餐品种
  1701. cpCond := `product_id = ? AND permission_name <> ?`
  1702. cpPars := make([]interface{}, 0)
  1703. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  1704. cp := new(crm.ChartPermission)
  1705. permissionList, e := cp.List(cpCond, cpPars)
  1706. if e != nil {
  1707. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  1708. return
  1709. }
  1710. permissionLen := len(permissionList)
  1711. permissionNameIdMap := make(map[string]int)
  1712. for i := range permissionList {
  1713. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1714. }
  1715. // 获取所有FICC套餐服务
  1716. serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  1717. if e != nil {
  1718. resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  1719. return
  1720. }
  1721. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1722. otherService := make([]*fms.ContractServiceTemplateItem, 0)
  1723. for i := range serviceList {
  1724. if serviceList[i].Title != "FICC大套餐" && serviceList[i].Title != "FICC小套餐" {
  1725. otherService = append(otherService, serviceList[i])
  1726. }
  1727. }
  1728. otherServiceLen := len(otherService)
  1729. // 获取所有权益套餐服务
  1730. raiServiceList, e := fms.GetContractServiceTemplateAllByProductId(crm.CompanyProductRai)
  1731. if e != nil {
  1732. resp.FailData("获取权益套餐服务失败", "Err:"+e.Error(), c)
  1733. return
  1734. }
  1735. raiServiceIdMap := make(map[int]*fms.ContractServiceTemplateItem)
  1736. for i := range raiServiceList {
  1737. raiServiceIdMap[raiServiceList[i].ServiceTemplateId] = raiServiceList[i]
  1738. }
  1739. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1740. raiOtherService := make([]*fms.ContractServiceTemplateItem, 0)
  1741. raiServiceNotShowMap := make(map[int]struct{})
  1742. for _, v := range raiServiceList {
  1743. if v.Pid > 0 && raiServiceIdMap[v.Pid].Pid > 0 {
  1744. raiServiceNotShowMap[v.Pid] = struct{}{}
  1745. raiServiceNotShowMap[raiServiceIdMap[v.Pid].Pid] = struct{}{}
  1746. } else if v.Pid > 0 {
  1747. raiServiceNotShowMap[v.Pid] = struct{}{}
  1748. }
  1749. }
  1750. for _, v := range raiServiceList {
  1751. if _, ok := raiServiceNotShowMap[v.ServiceTemplateId]; !ok {
  1752. if v.Pid > 0 {
  1753. v.ParentTitle = raiServiceIdMap[v.Pid].Title
  1754. }
  1755. raiOtherService = append(raiOtherService, v)
  1756. }
  1757. }
  1758. otherServiceLen += len(raiOtherService)
  1759. //套餐金额map
  1760. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount)
  1761. // 套餐/开票/到款列表
  1762. serviceMap := make(map[int][]*fms.ContractServiceWithParentTitle)
  1763. serviceChartPermissionsMap := make(map[int][]int)
  1764. invoiceMap := make(map[int][]*fms.ContractInvoice)
  1765. paymentMap := make(map[int][]*fms.ContractInvoice)
  1766. maxInvoice := 0
  1767. maxPayment := 0
  1768. if len(registerIds) > 0 {
  1769. // 获取套餐信息
  1770. csCond := `cv.contract_register_id IN ?`
  1771. csPars := make([]interface{}, 0)
  1772. csPars = append(csPars, registerIds)
  1773. cs := new(fms.ContractService)
  1774. serviceList, e := cs.ListWithWithParentTitle(csCond, csPars)
  1775. if e != nil {
  1776. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  1777. return
  1778. }
  1779. for i := range serviceList {
  1780. cid := serviceList[i].ContractRegisterId
  1781. if serviceMap[cid] == nil {
  1782. serviceMap[cid] = make([]*fms.ContractServiceWithParentTitle, 0)
  1783. }
  1784. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  1785. // 小套餐权限
  1786. if serviceChartPermissionsMap[cid] == nil {
  1787. serviceChartPermissionsMap[cid] = make([]int, 0)
  1788. }
  1789. if serviceList[i].ChartPermissionIds != "" {
  1790. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  1791. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  1792. }
  1793. }
  1794. // 获取合同的套餐金额信息
  1795. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(registerIds)
  1796. if e != nil {
  1797. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1798. return
  1799. }
  1800. for _, v := range serviceAmountList {
  1801. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1802. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1803. }
  1804. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1805. }
  1806. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  1807. ci := new(fms.ContractInvoice)
  1808. csCond = `contract_register_id IN ?`
  1809. csPars = make([]interface{}, 0)
  1810. csPars = append(csPars, registerIds)
  1811. invoiceList, e := ci.List(csCond, csPars, "")
  1812. if e != nil {
  1813. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1814. return
  1815. }
  1816. for k := range invoiceList {
  1817. cid := invoiceList[k].ContractRegisterId
  1818. if invoiceMap[cid] == nil {
  1819. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  1820. }
  1821. if paymentMap[cid] == nil {
  1822. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  1823. }
  1824. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  1825. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  1826. continue
  1827. }
  1828. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  1829. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  1830. continue
  1831. }
  1832. }
  1833. // 取最大开票/到款数
  1834. for j := range invoiceMap {
  1835. if len(invoiceMap[j]) > maxInvoice {
  1836. maxInvoice = len(invoiceMap[j])
  1837. }
  1838. }
  1839. for p := range paymentMap {
  1840. if len(paymentMap[p]) > maxPayment {
  1841. maxPayment = len(paymentMap[p])
  1842. }
  1843. }
  1844. }
  1845. serviceProductIdMap := map[int]string{
  1846. 1: "FICC套餐",
  1847. 2: "权益套餐",
  1848. }
  1849. // 生成Excel文件
  1850. xlsxFile := xlsx.NewFile()
  1851. style := xlsx.NewStyle()
  1852. alignment := xlsx.Alignment{
  1853. Horizontal: "center",
  1854. Vertical: "center",
  1855. WrapText: true,
  1856. }
  1857. style.Alignment = alignment
  1858. style.ApplyAlignment = true
  1859. sheetName := "财务列表"
  1860. sheet, err := xlsxFile.AddSheet(sheetName)
  1861. if err != nil {
  1862. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1863. return
  1864. }
  1865. // 1行表头
  1866. hInt := 0
  1867. titleRow := sheet.AddRow()
  1868. titleRow.SetHeight(40)
  1869. // 1行1列-右合并两格, 下合并1行
  1870. cell1 := titleRow.AddCell()
  1871. if req.ListParam == 0 {
  1872. cell1.HMerge = 9
  1873. } else {
  1874. cell1.HMerge = 9
  1875. }
  1876. cell1.VMerge = 1
  1877. cell1.SetString("客户签约表")
  1878. cell1.SetStyle(style)
  1879. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  1880. titleRow.AddCell().SetString("")
  1881. titleRow.AddCell().SetString("")
  1882. titleRow.AddCell().SetString("")
  1883. titleRow.AddCell().SetString("")
  1884. titleRow.AddCell().SetString("")
  1885. titleRow.AddCell().SetString("")
  1886. titleRow.AddCell().SetString("")
  1887. titleRow.AddCell().SetString("")
  1888. hInt += 9
  1889. if req.ListParam == 0 {
  1890. //如果是全部的话要多一格
  1891. titleRow.AddCell().SetString("")
  1892. hInt += 1
  1893. }
  1894. // 1行2列
  1895. if req.ListParam != 2 {
  1896. cell2 := titleRow.AddCell()
  1897. cell2.VMerge = 1
  1898. cell2.SetString("FICC大套餐")
  1899. cell2.SetStyle(style)
  1900. hInt++
  1901. }
  1902. // 1行3列-右合并小套餐数
  1903. if permissionLen >= 1 && req.ListParam != 2 {
  1904. cell3 := titleRow.AddCell()
  1905. hInt++
  1906. cell3.HMerge = permissionLen - 1
  1907. cell3.VMerge = 1
  1908. cell3.SetString("FICC小套餐")
  1909. cell3.SetStyle(style)
  1910. // 同上右增单元格小套餐数-1的空白单元格用于合并
  1911. for i := 0; i < permissionLen-1; i++ {
  1912. titleRow.AddCell().SetString("")
  1913. hInt++
  1914. }
  1915. }
  1916. if req.ListParam != 2 {
  1917. for i := range otherService {
  1918. cellOther := titleRow.AddCell()
  1919. cellOther.VMerge = 1
  1920. hInt++
  1921. cellOther.SetString(otherService[i].Title)
  1922. cellOther.SetStyle(style)
  1923. }
  1924. }
  1925. if req.ListParam != 1 {
  1926. //权益大套餐
  1927. cell4 := titleRow.AddCell()
  1928. cell4.HMerge = 1
  1929. cell4.VMerge = 1
  1930. cell4.SetString("权益大套餐")
  1931. cell4.SetStyle(style)
  1932. titleRow.AddCell().SetString("")
  1933. hInt += 2
  1934. //权益分行业套餐
  1935. cell5 := titleRow.AddCell()
  1936. cell5.HMerge = 8
  1937. cell5.SetString("权益分行业套餐")
  1938. cell5.SetStyle(style)
  1939. titleRow.AddCell().SetString("")
  1940. titleRow.AddCell().SetString("")
  1941. titleRow.AddCell().SetString("")
  1942. titleRow.AddCell().SetString("")
  1943. titleRow.AddCell().SetString("")
  1944. titleRow.AddCell().SetString("")
  1945. titleRow.AddCell().SetString("")
  1946. titleRow.AddCell().SetString("")
  1947. }
  1948. //第二行,前面几个单元格用于第一行的合并
  1949. titleRow2 := sheet.AddRow()
  1950. titleRow2.SetHeight(30)
  1951. for i := 0; i < hInt; i++ {
  1952. titleRow2.AddCell().SetString("")
  1953. }
  1954. if req.ListParam != 1 {
  1955. //权益分行业套餐
  1956. row2Cell1 := titleRow2.AddCell()
  1957. row2Cell1.HMerge = 1
  1958. row2Cell1.SetString("医药")
  1959. row2Cell1.SetStyle(style)
  1960. titleRow2.AddCell().SetString("")
  1961. row2Cell2 := titleRow2.AddCell()
  1962. row2Cell2.HMerge = 1
  1963. row2Cell2.SetString("消费")
  1964. row2Cell2.SetStyle(style)
  1965. titleRow2.AddCell().SetString("")
  1966. row2Cell3 := titleRow2.AddCell()
  1967. row2Cell3.HMerge = 1
  1968. row2Cell3.SetString("科技")
  1969. row2Cell3.SetStyle(style)
  1970. titleRow2.AddCell().SetString("")
  1971. row2Cell4 := titleRow2.AddCell()
  1972. row2Cell4.HMerge = 1
  1973. row2Cell4.SetString("智造")
  1974. row2Cell4.SetStyle(style)
  1975. titleRow2.AddCell().SetString("")
  1976. row2Cell5 := titleRow2.AddCell()
  1977. row2Cell5.SetString("策略")
  1978. row2Cell5.SetStyle(style)
  1979. }
  1980. // 第三行表头
  1981. titleRow3 := sheet.AddRow()
  1982. titleRow3.SetHeight(60)
  1983. row3Title := make([]string, 0)
  1984. row3TitleParent := make([]string, 0)
  1985. row3Title = append(row3Title, "客户名称", "新客户\n0-是\n1-否", "合同类型\n0-自付合同\n1-代付合同",
  1986. "合同子类型\n续约-0\n新签-1\n补充协议-2", "合同所属方", "代付方", "关联主合同(补充协议)", "关联合同(代付合同)")
  1987. if req.ListParam == 0 {
  1988. row3Title = append(row3Title, "FICC销售", "权益销售", "FICC大套餐")
  1989. for i := range permissionList {
  1990. row3Title = append(row3Title, permissionList[i].PermissionName)
  1991. }
  1992. // 其他套餐
  1993. for i := range otherService {
  1994. row3Title = append(row3Title, otherService[i].Title)
  1995. }
  1996. // 定义二级套餐名称
  1997. for i := range row3Title {
  1998. row3TitleParent = append(row3TitleParent, row3Title[i])
  1999. }
  2000. // 权益三级套餐
  2001. for i := range raiOtherService {
  2002. row3Title = append(row3Title, raiOtherService[i].Title)
  2003. if raiOtherService[i].ParentTitle != "" {
  2004. row3TitleParent = append(row3TitleParent, raiOtherService[i].ParentTitle)
  2005. } else {
  2006. row3TitleParent = append(row3TitleParent, raiOtherService[i].Title)
  2007. }
  2008. }
  2009. } else if req.ListParam == 1 {
  2010. row3Title = append(row3Title, "FICC销售", "FICC大套餐")
  2011. for i := range permissionList {
  2012. row3Title = append(row3Title, permissionList[i].PermissionName)
  2013. }
  2014. // 其他套餐
  2015. for i := range otherService {
  2016. row3Title = append(row3Title, otherService[i].Title)
  2017. }
  2018. // 定义二级套餐名称
  2019. for i := range row3Title {
  2020. row3TitleParent = append(row3TitleParent, row3Title[i])
  2021. }
  2022. } else {
  2023. row3Title = append(row3Title, "权益销售")
  2024. // 权益三级套餐
  2025. for i := range raiOtherService {
  2026. row3Title = append(row3Title, raiOtherService[i].Title)
  2027. if raiOtherService[i].ParentTitle != "" {
  2028. row3TitleParent = append(row3TitleParent, raiOtherService[i].ParentTitle)
  2029. } else {
  2030. row3TitleParent = append(row3TitleParent, raiOtherService[i].Title)
  2031. }
  2032. }
  2033. }
  2034. row3Title = append(row3Title, "套餐备注", "开始时间", "到期时间", "合同金额", "金额单位")
  2035. if req.ListParam == 0 {
  2036. row3Title = append(row3Title, "FICC套餐总金额", "权益套餐总金额")
  2037. }
  2038. row3Title = append(row3Title, "约定付款时间", "签订日", "合同状态", "合同编号", "合规备注")
  2039. // 设置表头
  2040. for i := range row3Title {
  2041. v := titleRow3.AddCell()
  2042. v.SetString(row3Title[i])
  2043. v.SetStyle(style)
  2044. }
  2045. // 第二行表头-开票/收款(动态添加)
  2046. invoiceTitle := []string{"开票日", "开票金额", "套餐类型", "销售", "备注"}
  2047. for i := 0; i < maxInvoice; i++ {
  2048. n := i + 1
  2049. for ii := range invoiceTitle {
  2050. c := titleRow3.AddCell()
  2051. t := fmt.Sprintf("%s%d", invoiceTitle[ii], n)
  2052. c.SetString(t)
  2053. c.SetStyle(style)
  2054. row3Title = append(row3Title, t)
  2055. }
  2056. }
  2057. paymentTitle := []string{"到款日", "到款金额", "套餐类型", "销售", "备注"}
  2058. for i := 0; i < maxPayment; i++ {
  2059. n := i + 1
  2060. for ii := range paymentTitle {
  2061. c := titleRow3.AddCell()
  2062. t := fmt.Sprintf("%s%d", paymentTitle[ii], n)
  2063. c.SetString(t)
  2064. c.SetStyle(style)
  2065. row3Title = append(row3Title, t)
  2066. }
  2067. }
  2068. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  2069. row2NameKeyMap := make(map[string]int)
  2070. for i := range row3Title {
  2071. row2NameKeyMap[row3Title[i]] = i
  2072. }
  2073. newCompanyMap := map[int]string{2: "1", 1: "0"}
  2074. contractTMap := map[int]int{
  2075. fms.ContractTypeSelf: 0,
  2076. fms.ContractTypebehalf: 1,
  2077. }
  2078. contractSubTMap := map[int]int{
  2079. fms.NewContractTypeNew: 1,
  2080. fms.NewContractTypeRenew: 0,
  2081. fms.NewContractTypePlus: 2, // 代付合同
  2082. }
  2083. for _, v := range list {
  2084. k := -1 // 套餐匹配用
  2085. dataRow := sheet.AddRow()
  2086. dataRow.SetHeight(20)
  2087. dataRow.AddCell().SetString(v.CompanyName)
  2088. dataRow.AddCell().SetString(newCompanyMap[v.ContractType])
  2089. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.HasPayment]))
  2090. dataRow.AddCell().SetString(fmt.Sprint(contractSubTMap[v.ContractType]))
  2091. if v.HasPayment == 1 {
  2092. if v.HasInvoice == 1 {
  2093. dataRow.AddCell().SetString("1")
  2094. } else {
  2095. dataRow.AddCell().SetString("0")
  2096. }
  2097. } else {
  2098. dataRow.AddCell().SetString("")
  2099. }
  2100. dataRow.AddCell().SetString(v.ActualPayCompanies)
  2101. dataRow.AddCell().SetString(v.RelateContractMainCode)
  2102. dataRow.AddCell().SetString(v.RelateContractCode)
  2103. if req.ListParam == 0 {
  2104. dataRow.AddCell().SetString(v.SellerName)
  2105. dataRow.AddCell().SetString(v.RaiSellerName)
  2106. } else if req.ListParam == 1 {
  2107. dataRow.AddCell().SetString(v.SellerName)
  2108. } else {
  2109. dataRow.AddCell().SetString(v.RaiSellerName)
  2110. }
  2111. if req.ListParam != 0 {
  2112. k += 10
  2113. } else {
  2114. k += 11
  2115. }
  2116. // 大套餐
  2117. col4Name := row3Title[k]
  2118. svList := serviceMap[v.ContractRegisterId]
  2119. col4 := ""
  2120. if svList != nil && len(svList) > 0 {
  2121. for isv := range svList {
  2122. if svList[isv].Title == col4Name {
  2123. col4 = "是"
  2124. break
  2125. }
  2126. }
  2127. }
  2128. dataRow.AddCell().SetString(col4)
  2129. // 小套餐
  2130. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  2131. for i := 0; i < permissionLen; i++ {
  2132. k += 1
  2133. colName := row3Title[k]
  2134. chartPermissionId := permissionNameIdMap[colName]
  2135. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  2136. dataRow.AddCell().SetString("是")
  2137. } else {
  2138. dataRow.AddCell().SetString("")
  2139. }
  2140. }
  2141. // 除大小套餐外的其他套餐(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  2142. for i := 0; i < otherServiceLen; i++ {
  2143. k += 1
  2144. otherColName := row3Title[k]
  2145. otherCol := ""
  2146. if svList != nil && len(svList) > 0 {
  2147. for isv := range svList {
  2148. if svList[isv].Title == otherColName {
  2149. // 判断权益套餐权限时,需要同时判断父级name
  2150. if otherColName == "主观" || otherColName == "客观" {
  2151. if row3TitleParent[k] == svList[isv].ParentTitle {
  2152. otherCol = "是"
  2153. break
  2154. }
  2155. } else {
  2156. otherCol = "是"
  2157. break
  2158. }
  2159. }
  2160. }
  2161. }
  2162. dataRow.AddCell().SetString(otherCol)
  2163. }
  2164. // 其他信息
  2165. ficcAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductFicc]
  2166. raiAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductRai]
  2167. dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
  2168. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  2169. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  2170. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 合同金额
  2171. dataRow.AddCell().SetString(v.CurrencyUnit) // 货币单位
  2172. if ficcAmount != nil {
  2173. dataRow.AddCell().SetString(fmt.Sprint("¥", ficcAmount.ServiceAmount)) // FICC套餐总金额
  2174. if raiAmount == nil {
  2175. dataRow.AddCell().SetString("") // 权益套餐总金额
  2176. }
  2177. }
  2178. if raiAmount != nil {
  2179. if ficcAmount == nil {
  2180. dataRow.AddCell().SetString("") // 权益套餐总金额
  2181. }
  2182. dataRow.AddCell().SetString(fmt.Sprint("¥", raiAmount.ServiceAmount)) // FICC套餐总金额
  2183. }
  2184. if ficcAmount == nil && raiAmount == nil {
  2185. dataRow.AddCell().SetString("") // FICC套餐总金额
  2186. dataRow.AddCell().SetString("") // 权益套餐总金额
  2187. }
  2188. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  2189. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  2190. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  2191. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  2192. dataRow.AddCell().SetString(v.Remark) // 合规备注
  2193. // 开票/到款信息
  2194. ivList := invoiceMap[v.ContractRegisterId]
  2195. ivListLen := len(ivList)
  2196. for ia := 0; ia < maxInvoice; ia++ {
  2197. if ia < ivListLen {
  2198. if ivList != nil && ivList[ia] != nil {
  2199. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  2200. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].OriginAmount)) // 开票金额
  2201. dataRow.AddCell().SetString(serviceProductIdMap[ivList[ia].ServiceProductId]) // 套餐类型
  2202. dataRow.AddCell().SetString(ivList[ia].SellerName) // 销售名称
  2203. dataRow.AddCell().SetString(ivList[ia].Remark) // 开票备注
  2204. continue
  2205. }
  2206. }
  2207. // 这里要把不够的填充为空
  2208. dataRow.AddCell().SetString("")
  2209. dataRow.AddCell().SetString("")
  2210. dataRow.AddCell().SetString("")
  2211. dataRow.AddCell().SetString("")
  2212. dataRow.AddCell().SetString("")
  2213. }
  2214. pyList := paymentMap[v.ContractRegisterId]
  2215. pyListLen := len(pyList)
  2216. for ib := 0; ib < maxPayment; ib++ {
  2217. if ib < pyListLen {
  2218. if pyList != nil && pyList[ib] != nil {
  2219. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  2220. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].OriginAmount)) // 收款金额
  2221. dataRow.AddCell().SetString(serviceProductIdMap[pyList[ib].ServiceProductId]) // 套餐类型
  2222. dataRow.AddCell().SetString(pyList[ib].SellerName) // 销售名称
  2223. dataRow.AddCell().SetString(pyList[ib].Remark) // 收款备注
  2224. continue
  2225. }
  2226. }
  2227. // 这里要把不够的填充为空
  2228. dataRow.AddCell().SetString("")
  2229. dataRow.AddCell().SetString("")
  2230. dataRow.AddCell().SetString("")
  2231. dataRow.AddCell().SetString("")
  2232. }
  2233. }
  2234. // 输出文件
  2235. var buffer bytes.Buffer
  2236. _ = xlsxFile.Write(&buffer)
  2237. content := bytes.NewReader(buffer.Bytes())
  2238. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2239. fileName := sheetName + randStr + ".xlsx"
  2240. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2241. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2242. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2243. }
  2244. // InvoiceList
  2245. // @Title 开票/到款列表
  2246. // @Description 开票/到款列表
  2247. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  2248. // @Param Keyword query string false "查询关键字"
  2249. // @Param StartDate query string false "开始日期"
  2250. // @Param EndDate query string false "结束日期"
  2251. // @Param MinAmount query float64 false "开票金额区间-最小值"
  2252. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  2253. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  2254. // @Success 200 {object} fms.ContractInvoiceItem
  2255. // @router /contract/register/invoice_list [get]
  2256. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  2257. var req fms.ContractInvoiceListReq
  2258. if e := c.BindQuery(&req); e != nil {
  2259. err, ok := e.(validator.ValidationErrors)
  2260. if !ok {
  2261. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  2262. return
  2263. }
  2264. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  2265. return
  2266. }
  2267. pageSize := req.PageSize
  2268. pageIndex := req.Current
  2269. if pageSize <= 0 {
  2270. pageSize = utils.PageSize20
  2271. }
  2272. if pageIndex <= 0 {
  2273. pageIndex = 1
  2274. }
  2275. cond := ``
  2276. if req.InvoiceType == 1 {
  2277. cond = `invoice_type IN (1,3)`
  2278. } else {
  2279. cond = `invoice_type IN (2,4)`
  2280. }
  2281. pars := make([]interface{}, 0)
  2282. // 搜索
  2283. if req.Keyword != "" {
  2284. kw := fmt.Sprint("%", req.Keyword, "%")
  2285. //pars = append(pars, kw)
  2286. cond += ` AND (b.company_name LIKE ? OR a.contract_code LIKE ?)`
  2287. pars = append(pars, kw, kw)
  2288. }
  2289. if req.StartDate != "" && req.EndDate != "" {
  2290. st := fmt.Sprint(req.StartDate, " 00:00:00")
  2291. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  2292. cond += ` AND (a.invoice_time BETWEEN ? AND ?)`
  2293. pars = append(pars, st, ed)
  2294. }
  2295. if req.MinAmount > 0 {
  2296. cond += ` AND a.amount >= ?`
  2297. pars = append(pars, req.MinAmount)
  2298. }
  2299. if req.MaxAmount > 0 {
  2300. cond += ` AND a.amount <= ?`
  2301. pars = append(pars, req.MaxAmount)
  2302. }
  2303. // 套餐类型
  2304. if req.ServiceProductId > 0 {
  2305. cond += ` AND a.service_product_id = ?`
  2306. pars = append(pars, req.ServiceProductId)
  2307. }
  2308. // 销售
  2309. if req.SellerIds != "" {
  2310. sellerIds := strings.Split(req.SellerIds, ",")
  2311. cond += ` AND (a.seller_id in (?))`
  2312. pars = append(pars, sellerIds)
  2313. }
  2314. // 货币列表
  2315. currencyOB := new(fms.CurrencyUnit)
  2316. currencyCond := `enable = 1`
  2317. currencyPars := make([]interface{}, 0)
  2318. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2319. if e != nil {
  2320. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  2321. return
  2322. }
  2323. unitMap := make(map[string]string)
  2324. currencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2325. for i := range currencyList {
  2326. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2327. currencyTotals = append(currencyTotals, &fms.InvoiceListCurrencyTotal{
  2328. Name: currencyList[i].Name,
  2329. UnitName: currencyList[i].UnitName,
  2330. Code: currencyList[i].Code,
  2331. FlagImg: currencyList[i].FlagImg,
  2332. })
  2333. }
  2334. page := new(base.Page)
  2335. page.SetPageSize(pageSize)
  2336. page.SetCurrent(pageIndex)
  2337. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  2338. if req.IsExport == 1 {
  2339. page.SetPageSize(10000)
  2340. page.SetCurrent(1)
  2341. }
  2342. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  2343. if e != nil {
  2344. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  2345. return
  2346. }
  2347. page.SetTotal(total)
  2348. contractRegisterIds := make([]int, 0)
  2349. contractStatusMap := make(map[int]int)
  2350. for i := range list {
  2351. list[i].UnitName = unitMap[list[i].CurrencyUnit]
  2352. contractRegisterIds = append(contractRegisterIds, list[i].ContractRegisterId)
  2353. }
  2354. if len(contractRegisterIds) > 0 {
  2355. contractRegisters, err := fms.GetContractInfoByRegisterIds(contractRegisterIds)
  2356. if err != nil {
  2357. resp.FailMsg("查询合同信息失败", "查询合同信息失败, Err: "+err.Error(), c)
  2358. return
  2359. }
  2360. for _, v := range contractRegisters {
  2361. contractStatusMap[v.ContractRegisterId] = v.ContractStatus
  2362. }
  2363. }
  2364. for i := range list {
  2365. list[i].ContractStatus = contractStatusMap[list[i].ContractRegisterId]
  2366. }
  2367. // 分币种合计金额
  2368. var amountTotal float64
  2369. sumList, e := fms.GetInvoiceListCurrencySum(cond, pars, "currency_unit")
  2370. if e != nil {
  2371. resp.FailMsg("获取失败", "获取开票/到款列表合计金额失败, Err: "+e.Error(), c)
  2372. return
  2373. }
  2374. sumMap := make(map[string]float64)
  2375. for i := range sumList {
  2376. amountTotal += sumList[i].AmountTotal
  2377. sumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  2378. }
  2379. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotal), 64)
  2380. for i := range currencyTotals {
  2381. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", sumMap[currencyTotals[i].Code]), 64)
  2382. currencyTotals[i].Amount = a
  2383. }
  2384. respData := &fms.InvoiceListRespData{
  2385. Page: page,
  2386. List: list,
  2387. AmountTotal: amountTotal,
  2388. CurrencyTotal: currencyTotals,
  2389. }
  2390. // 是否导出
  2391. if req.IsExport == 1 {
  2392. ExportInvoiceList(c, req, respData)
  2393. return
  2394. }
  2395. resp.OkData("获取成功", respData, c)
  2396. }
  2397. // ExportInvoiceList 导出开票/到款列表
  2398. func ExportInvoiceList(c *gin.Context, req fms.ContractInvoiceListReq, results *fms.InvoiceListRespData) {
  2399. list := make([]*fms.ContractInvoiceItem, 0)
  2400. if val, ok := results.List.([]*fms.ContractInvoiceItem); ok {
  2401. list = val
  2402. } else {
  2403. resp.Fail("列表数据有误", c)
  2404. return
  2405. }
  2406. if len(list) == 0 {
  2407. resp.Fail("列表数据为空", c)
  2408. return
  2409. }
  2410. listName := "开票"
  2411. if req.InvoiceType == fms.ContractInvoiceTypePay {
  2412. listName = "到款"
  2413. }
  2414. // 生成Excel文件
  2415. xlsxFile := xlsx.NewFile()
  2416. style := xlsx.NewStyle()
  2417. alignment := xlsx.Alignment{
  2418. Horizontal: "center",
  2419. Vertical: "center",
  2420. WrapText: true,
  2421. }
  2422. style.Alignment = alignment
  2423. style.ApplyAlignment = true
  2424. sheet, err := xlsxFile.AddSheet(fmt.Sprintf("%s列表", listName))
  2425. if err != nil {
  2426. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2427. return
  2428. }
  2429. // 前两行显示合计金额, 第三行空出与列表数据隔一行
  2430. rowA := sheet.AddRow()
  2431. cellAA := rowA.AddCell()
  2432. rowBData := ""
  2433. if req.InvoiceType == 1 {
  2434. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.AmountTotal))
  2435. rowBData = "已开票金额:"
  2436. } else {
  2437. cellAA.SetString(fmt.Sprintf("已到款合计金额(换算后):%.2f(元)", results.AmountTotal))
  2438. rowBData = "已到款金额:"
  2439. }
  2440. for _, v := range results.CurrencyTotal {
  2441. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2442. }
  2443. rowB := sheet.AddRow()
  2444. rowB.AddCell().SetString(rowBData)
  2445. sheet.AddRow()
  2446. // 列表数据表头
  2447. titles := []string{"客户名称", "合同编号", "套餐类型", fmt.Sprintf("%s金额", listName), "金额单位", "换算金额(元)",
  2448. fmt.Sprintf("%s日期", listName), "备注"}
  2449. titleRow := sheet.AddRow()
  2450. titleRow.SetHeight(40)
  2451. for i := range titles {
  2452. c := titleRow.AddCell()
  2453. c.SetString(titles[i])
  2454. c.SetStyle(style)
  2455. }
  2456. ServiceTemplateStrMap := map[int]string{
  2457. crm.CompanyProductFicc: "FICC套餐",
  2458. crm.CompanyProductRai: "权益套餐",
  2459. }
  2460. // 单元格赋值
  2461. for _, v := range list {
  2462. dataRow := sheet.AddRow()
  2463. dataRow.SetHeight(20)
  2464. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  2465. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  2466. dataRow.AddCell().SetString(ServiceTemplateStrMap[v.ServiceProductId]) // 套餐类型
  2467. dataRow.AddCell().SetString(fmt.Sprint(v.OriginAmount)) // 开票金额
  2468. dataRow.AddCell().SetString(v.UnitName) // 金额单位
  2469. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 换算金额(元)
  2470. dataRow.AddCell().SetString(v.InvoiceDate) // 开票日
  2471. dataRow.AddCell().SetString(v.Remark) // 备注
  2472. }
  2473. // 输出文件
  2474. var buffer bytes.Buffer
  2475. _ = xlsxFile.Write(&buffer)
  2476. content := bytes.NewReader(buffer.Bytes())
  2477. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2478. fileName := fmt.Sprintf("%s列表_%s.xlsx", listName, randStr)
  2479. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2480. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2481. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2482. }
  2483. // Import
  2484. // @Title 合同登记-导入
  2485. // @Description 合同登记-导入
  2486. // @Success 200 string "操作成功"
  2487. // @router /contract/register/import [post]
  2488. func (rg *RegisterController) Import(c *gin.Context) {
  2489. h, err := c.FormFile("File")
  2490. if err != nil {
  2491. resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  2492. return
  2493. }
  2494. ext := path.Ext(h.Filename)
  2495. if ext != ".xlsx" && ext != ".xls" {
  2496. resp.Fail("请上传Excel文件", c)
  2497. return
  2498. }
  2499. claims, _ := c.Get("adminInfo")
  2500. adminInfo := claims.(*system.SysAdmin)
  2501. uploadDir := "static/xls"
  2502. err = os.MkdirAll(uploadDir, 766)
  2503. if err != nil {
  2504. resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  2505. return
  2506. }
  2507. uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  2508. err = c.SaveUploadedFile(h, uploadPath)
  2509. if err != nil {
  2510. resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  2511. return
  2512. }
  2513. defer func() {
  2514. _ = os.Remove(uploadPath)
  2515. }()
  2516. xlFile, err := xlsx.OpenFile(uploadPath)
  2517. if err != nil {
  2518. resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  2519. return
  2520. }
  2521. logList := make([]*fms.ContractRegisterLog, 0)
  2522. // 获取所有已登记,根据合同编号去重
  2523. contractCodeArr := make([]string, 0)
  2524. registerOB := new(fms.ContractRegister)
  2525. registerCond := ``
  2526. registerPars := make([]interface{}, 0)
  2527. registerList, e := registerOB.List(registerCond, registerPars)
  2528. if e != nil {
  2529. resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  2530. return
  2531. }
  2532. for i := range registerList {
  2533. contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  2534. }
  2535. // 获取所有销售Map
  2536. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  2537. if e != nil {
  2538. resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  2539. return
  2540. }
  2541. sellerMap := make(map[string]*crm.SellerAdminWithGroupTeam)
  2542. for i := range sellerList {
  2543. sellerMap[sellerList[i].SellerName] = sellerList[i]
  2544. }
  2545. // 获取品种权限Map
  2546. chartPermissionNameIdMap := make(map[string]int)
  2547. cpCond := `product_id = ?`
  2548. cpPars := make([]interface{}, 0)
  2549. cpPars = append(cpPars, crm.CompanyProductFicc)
  2550. cp := new(crm.ChartPermission)
  2551. permissionList, e := cp.List(cpCond, cpPars)
  2552. if e != nil {
  2553. resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  2554. return
  2555. }
  2556. for i := range permissionList {
  2557. chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  2558. }
  2559. // 获取所有套餐模板
  2560. serviceTempCond := ``
  2561. serviceTempPars := make([]interface{}, 0)
  2562. serviceTempOB := new(fms.ContractServiceTemplate)
  2563. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  2564. if e != nil {
  2565. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  2566. return
  2567. }
  2568. serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
  2569. serviceTempFullNameMap := make(map[string]*fms.ContractServiceTemplate)
  2570. serviceTempIdMap := make(map[int]*fms.ContractServiceTemplate)
  2571. for i := range serviceTempList {
  2572. serviceTempIdMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  2573. serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
  2574. }
  2575. for i := range serviceTempList {
  2576. fullName := serviceTempList[i].Title
  2577. if serviceTempList[i].Pid > 0 {
  2578. parentItem := serviceTempIdMap[serviceTempList[i].Pid]
  2579. fullName += "_" + parentItem.Title
  2580. if parentItem.Pid > 0 {
  2581. fullName += "_" + serviceTempIdMap[parentItem.Pid].Title
  2582. }
  2583. }
  2584. serviceTempFullNameMap[fullName] = serviceTempList[i]
  2585. }
  2586. //权益行业套餐名称
  2587. raiIndustryMap := map[int]string{
  2588. 43: "医药",
  2589. 44: "医药",
  2590. 45: "消费",
  2591. 46: "消费",
  2592. 47: "科技",
  2593. 48: "科技",
  2594. 49: "智造",
  2595. 50: "智造",
  2596. 51: "策略",
  2597. }
  2598. // 获取货币列表及汇率(汇率为导入日的汇率)
  2599. rateList, e := fmsService.GetTodayCurrencyRateList()
  2600. if e != nil {
  2601. resp.FailData("获取货币列表及汇率失败", "Err:"+e.Error(), c)
  2602. return
  2603. }
  2604. rateMap := make(map[string]float64)
  2605. for i := range rateList {
  2606. rateMap[rateList[i].Code] = rateList[i].RMBRate
  2607. }
  2608. titleMap := make(map[int]string)
  2609. newIds := make([]int, 0)
  2610. newCompanyArr := []string{"0", "1"}
  2611. newCompanyMap := map[string]int{"0": 1, "1": 0}
  2612. contractTypeArr := []string{"0", "1"}
  2613. contractTMap := map[string]int{
  2614. "0": fms.ContractTypeSelf,
  2615. "1": fms.ContractTypebehalf,
  2616. }
  2617. contractSubTypeArr := []string{"0", "1", "2"}
  2618. contractSubTMap := map[string]int{
  2619. "1": fms.NewContractTypeNew,
  2620. "0": fms.NewContractTypeRenew,
  2621. "2": fms.NewContractTypePlus,
  2622. }
  2623. // 更新登记状态
  2624. defer func() {
  2625. if len(newIds) > 0 {
  2626. go func() {
  2627. for i := range newIds {
  2628. fmsService.CheckContractRegisterAmount(newIds[i])
  2629. fmsService.SummaryInvoicePaymentByContractRegisterId(newIds[i])
  2630. }
  2631. }()
  2632. }
  2633. }()
  2634. invoiceMax := 3
  2635. checkDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local)
  2636. for _, sheet := range xlFile.Sheets {
  2637. // 遍历行读取
  2638. maxRow := sheet.MaxRow
  2639. fmt.Println("maxRow", maxRow)
  2640. var dayDiff float64
  2641. for i := 0; i < maxRow; i++ {
  2642. // 第三行开始读取表头
  2643. if i == 2 {
  2644. row := sheet.Row(i)
  2645. cells := row.Cells
  2646. for k, cell := range cells {
  2647. text := cell.String()
  2648. titleMap[k] = text
  2649. // 只检验前面部分表头, 后面很多动态列
  2650. if k == 0 {
  2651. if text != "客户名称" {
  2652. resp.Fail("【客户名称】列名称有误, 请参考模板导入", c)
  2653. return
  2654. }
  2655. continue
  2656. } else if k == 1 {
  2657. if !strings.Contains(text, "新客户") {
  2658. resp.Fail("【新客户】列名称有误, 请参考模板导入", c)
  2659. return
  2660. }
  2661. continue
  2662. } else if k == 2 {
  2663. if !strings.Contains(text, "合同类型") {
  2664. resp.Fail("【合同类型】列名称有误, 请参考模板导入", c)
  2665. return
  2666. }
  2667. continue
  2668. } else if k == 3 {
  2669. if !strings.Contains(text, "合同子类型") {
  2670. resp.Fail("【合同子类型】列名称有误, 请参考模板导入", c)
  2671. return
  2672. }
  2673. continue
  2674. } else if k == 4 {
  2675. if !strings.Contains(text, "合同所属方") {
  2676. resp.Fail("【合同所属方】列名称有误, 请参考模板导入", c)
  2677. return
  2678. }
  2679. continue
  2680. } else if k == 5 {
  2681. if text != "代付方" {
  2682. resp.Fail("【代付方】列名称有误, 请参考模板导入", c)
  2683. return
  2684. }
  2685. continue
  2686. } else if k == 6 {
  2687. if !strings.Contains(text, "关联主合同(补充协议)") {
  2688. resp.Fail("【关联主合同】列名称有误, 请参考模板导入", c)
  2689. return
  2690. }
  2691. continue
  2692. } else if k == 7 {
  2693. if !strings.Contains(text, "关联合同") {
  2694. resp.Fail("【关联合同】列名称有误, 请参考模板导入", c)
  2695. return
  2696. }
  2697. continue
  2698. } else if k == 8 {
  2699. if text != "FICC销售" {
  2700. resp.Fail("【FICC销售】列名称有误, 请参考模板导入", c)
  2701. return
  2702. }
  2703. continue
  2704. } else if k == 9 {
  2705. if text != "权益销售" {
  2706. resp.Fail("【权益销售】列名称有误, 请参考模板导入", c)
  2707. return
  2708. }
  2709. continue
  2710. } else if k == 10 {
  2711. if text != "FICC大套餐" {
  2712. resp.Fail("【FICC大套餐】列名称有误, 请参考模板导入", c)
  2713. return
  2714. }
  2715. continue
  2716. }
  2717. }
  2718. } else if i >= 3 {
  2719. // 数据行
  2720. row := sheet.Row(i)
  2721. cells := row.Cells
  2722. // 登记信息
  2723. rowRegister := new(fms.ContractRegister)
  2724. // 套餐
  2725. rowServices := make([]*fms.ContractService, 0)
  2726. // 套餐金额
  2727. rowServiceAmount := make([]*fms.ContractServiceAmount, 0)
  2728. // 开票/到款
  2729. rowInvoices := make([]*fms.ContractInvoice, 0)
  2730. for ir := 0; ir < invoiceMax; ir++ {
  2731. rowInvoices = append(rowInvoices, new(fms.ContractInvoice))
  2732. }
  2733. rowPayments := make([]*fms.ContractInvoice, 0)
  2734. for ir := 0; ir < invoiceMax; ir++ {
  2735. rowPayments = append(rowPayments, new(fms.ContractInvoice))
  2736. }
  2737. // 小套餐权限
  2738. rowChartPermissionIdArr := make([]string, 0)
  2739. productIds := make(map[int]struct{})
  2740. isSkip := false
  2741. for k, cell := range cells {
  2742. fmt.Println("k:", k)
  2743. fmt.Println("cell:", cell.Value)
  2744. v := utils.TrimStr(cell.String())
  2745. // 客户名称
  2746. if k == 0 {
  2747. //pool_474 客户名称保留空格
  2748. if cell.String() == "" {
  2749. resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
  2750. return
  2751. }
  2752. rowRegister.CompanyName = cell.String()
  2753. continue
  2754. }
  2755. // 是否新客户
  2756. if k == 1 {
  2757. if !utils.InArrayByStr(newCompanyArr, v) {
  2758. resp.Fail(fmt.Sprintf("第%d行新客户有误, 请按模板导入", i+1), c)
  2759. return
  2760. }
  2761. rowRegister.NewCompany = newCompanyMap[v]
  2762. continue
  2763. }
  2764. // 合同类型
  2765. if k == 2 {
  2766. if !utils.InArrayByStr(contractTypeArr, v) {
  2767. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  2768. return
  2769. }
  2770. rowRegister.HasPayment = contractTMap[v]
  2771. continue
  2772. }
  2773. if k == 3 {
  2774. if !utils.InArrayByStr(contractSubTypeArr, v) {
  2775. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  2776. return
  2777. }
  2778. rowRegister.ContractType = contractSubTMap[v]
  2779. if rowRegister.ContractType == 0 {
  2780. resp.Fail(fmt.Sprintf("第%d行合同子类型匹配有误, 请按模板导入", i+1), c)
  2781. return
  2782. }
  2783. continue
  2784. }
  2785. if k == 4 {
  2786. if rowRegister.HasPayment == 1 {
  2787. if v == "0" {
  2788. //所属方为实际使用方,不走开票到款流程
  2789. rowRegister.HasInvoice = 0
  2790. } else if v == "1" {
  2791. rowRegister.HasInvoice = 1
  2792. }
  2793. } else {
  2794. rowRegister.HasInvoice = 1
  2795. }
  2796. continue
  2797. }
  2798. if k == 5 {
  2799. rowRegister.ActualPayCompanies = v
  2800. continue
  2801. }
  2802. if k == 6 {
  2803. rowRegister.RelateContractMainCode = v
  2804. continue
  2805. }
  2806. if k == 7 {
  2807. rowRegister.RelateContractCode = v
  2808. continue
  2809. }
  2810. // FICC销售
  2811. if k == 8 {
  2812. if v != "" {
  2813. /*resp.Fail(fmt.Sprintf("第%d行销售名称不可为空, 请按模板导入", i+1), c)
  2814. return*/
  2815. sellerItem := sellerMap[v]
  2816. if sellerItem == nil {
  2817. resp.Fail(fmt.Sprintf("第%d行销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2818. return
  2819. }
  2820. rowRegister.SellerId = sellerItem.SellerId
  2821. rowRegister.SellerName = sellerItem.SellerName
  2822. }
  2823. continue
  2824. }
  2825. // 权益销售
  2826. if k == 9 {
  2827. if v == "" && rowRegister.SellerName == "" {
  2828. resp.Fail(fmt.Sprintf("第FICC销售名称和权益销售名称不可都为空, 请按模板导入", i+1), c)
  2829. return
  2830. }
  2831. sellerItem := sellerMap[v]
  2832. if sellerItem == nil {
  2833. resp.Fail(fmt.Sprintf("第%d行权益销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2834. return
  2835. }
  2836. rowRegister.RaiSellerId = sellerItem.SellerId
  2837. rowRegister.RaiSellerName = sellerItem.SellerName
  2838. continue
  2839. }
  2840. // FICC大套餐
  2841. if k == 10 {
  2842. if v == "是" {
  2843. tempItem := serviceTempNameMap[titleMap[k]]
  2844. if tempItem == nil {
  2845. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2846. return
  2847. }
  2848. cs := &fms.ContractService{
  2849. ProductId: crm.CompanyProductFicc,
  2850. ServiceTemplateId: tempItem.ServiceTemplateId,
  2851. Title: tempItem.Title,
  2852. Value: tempItem.Value,
  2853. TableValue: tempItem.TableValue,
  2854. ChartPermissionId: tempItem.ChartPermissionId,
  2855. }
  2856. cs.Set()
  2857. rowServices = append(rowServices, cs)
  2858. productIds[crm.CompanyProductFicc] = struct{}{}
  2859. }
  2860. continue
  2861. }
  2862. // FICC小套餐
  2863. if k >= 11 && k <= 31 {
  2864. // 小套餐权限
  2865. if v == "是" {
  2866. rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
  2867. productIds[crm.CompanyProductFicc] = struct{}{}
  2868. }
  2869. continue
  2870. }
  2871. // 其他类型套餐
  2872. if k >= 32 && k <= 38 {
  2873. if v == "是" {
  2874. tempItem := serviceTempNameMap[titleMap[k]]
  2875. if tempItem == nil {
  2876. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2877. return
  2878. }
  2879. cs := &fms.ContractService{
  2880. ProductId: crm.CompanyProductFicc,
  2881. ServiceTemplateId: tempItem.ServiceTemplateId,
  2882. Title: tempItem.Title,
  2883. Value: tempItem.Value,
  2884. TableValue: tempItem.TableValue,
  2885. ChartPermissionId: tempItem.ChartPermissionId,
  2886. }
  2887. cs.Set()
  2888. rowServices = append(rowServices, cs)
  2889. productIds[crm.CompanyProductFicc] = struct{}{}
  2890. }
  2891. continue
  2892. }
  2893. if k >= 39 && k <= 49 {
  2894. if v == "是" {
  2895. // 权益大套餐
  2896. if k <= 42 {
  2897. //新增
  2898. parentName := "权益大套餐"
  2899. tempItem := serviceTempNameMap[titleMap[k]]
  2900. if tempItem == nil {
  2901. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2902. return
  2903. }
  2904. cs := &fms.ContractService{
  2905. ProductId: crm.CompanyProductRai,
  2906. ServiceTemplateId: tempItem.ServiceTemplateId,
  2907. Title: tempItem.Title,
  2908. Value: tempItem.Value,
  2909. TableValue: tempItem.TableValue,
  2910. ChartPermissionId: tempItem.ChartPermissionId,
  2911. }
  2912. rowServices = append(rowServices, cs)
  2913. tempItem = serviceTempNameMap[parentName]
  2914. if tempItem == nil {
  2915. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2916. return
  2917. }
  2918. cs = &fms.ContractService{
  2919. ProductId: crm.CompanyProductRai,
  2920. ServiceTemplateId: tempItem.ServiceTemplateId,
  2921. Title: tempItem.Title,
  2922. Value: tempItem.Value,
  2923. TableValue: tempItem.TableValue,
  2924. ChartPermissionId: tempItem.ChartPermissionId,
  2925. }
  2926. rowServices = append(rowServices, cs)
  2927. } else {
  2928. rootName := "行业套餐"
  2929. // 新增三条套餐信息
  2930. parentName, _ := raiIndustryMap[k]
  2931. fmt.Println("raiIndustryMap:", raiIndustryMap)
  2932. fmt.Println("titleMap:", titleMap)
  2933. childName := titleMap[k]
  2934. fullName := childName + "_" + parentName + "_" + rootName
  2935. if fullName != "" {
  2936. //增加三级权限
  2937. tempItem := serviceTempFullNameMap[fullName]
  2938. fmt.Println("fullName:", fullName)
  2939. fmt.Println("serviceTempFullNameMap:", serviceTempFullNameMap)
  2940. if tempItem == nil {
  2941. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2942. return
  2943. }
  2944. cs := &fms.ContractService{
  2945. ProductId: crm.CompanyProductRai,
  2946. ServiceTemplateId: tempItem.ServiceTemplateId,
  2947. Title: tempItem.Title,
  2948. Value: tempItem.Value,
  2949. TableValue: tempItem.TableValue,
  2950. ChartPermissionId: tempItem.ChartPermissionId,
  2951. }
  2952. rowServices = append(rowServices, cs)
  2953. //增加二级权限
  2954. tempItem = serviceTempFullNameMap[parentName+"_"+rootName]
  2955. if tempItem == nil {
  2956. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2957. return
  2958. }
  2959. cs = &fms.ContractService{
  2960. ProductId: crm.CompanyProductRai,
  2961. ServiceTemplateId: tempItem.ServiceTemplateId,
  2962. Title: tempItem.Title,
  2963. Value: tempItem.Value,
  2964. TableValue: tempItem.TableValue,
  2965. ChartPermissionId: tempItem.ChartPermissionId,
  2966. }
  2967. rowServices = append(rowServices, cs)
  2968. //增加一级权限
  2969. tempItem = serviceTempFullNameMap[rootName]
  2970. if tempItem == nil {
  2971. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2972. return
  2973. }
  2974. cs = &fms.ContractService{
  2975. ProductId: crm.CompanyProductRai,
  2976. ServiceTemplateId: tempItem.ServiceTemplateId,
  2977. Title: tempItem.Title,
  2978. Value: tempItem.Value,
  2979. TableValue: tempItem.TableValue,
  2980. ChartPermissionId: tempItem.ChartPermissionId,
  2981. }
  2982. rowServices = append(rowServices, cs)
  2983. }
  2984. }
  2985. productIds[crm.CompanyProductRai] = struct{}{}
  2986. }
  2987. continue
  2988. }
  2989. // 权益研选等套餐
  2990. if k >= 50 && k <= 54 {
  2991. if v == "是" {
  2992. tempItem := serviceTempNameMap[titleMap[k]]
  2993. if tempItem == nil {
  2994. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2995. return
  2996. }
  2997. cs := &fms.ContractService{
  2998. ProductId: crm.CompanyProductRai,
  2999. ServiceTemplateId: tempItem.ServiceTemplateId,
  3000. Title: tempItem.Title,
  3001. Value: tempItem.Value,
  3002. TableValue: tempItem.TableValue,
  3003. ChartPermissionId: tempItem.ChartPermissionId,
  3004. }
  3005. cs.Set()
  3006. rowServices = append(rowServices, cs)
  3007. productIds[crm.CompanyProductRai] = struct{}{}
  3008. }
  3009. continue
  3010. }
  3011. // 套餐备注
  3012. if k == 55 {
  3013. rowRegister.ServiceRemark = v
  3014. continue
  3015. }
  3016. // 开始时间/到期时间
  3017. if k == 58 {
  3018. // 转换失败可能是因为格式为Excel日期格式, 读取出来会是一串数字, 将其转换成日期字符串再处理
  3019. va := cell.Value
  3020. if va == "" {
  3021. resp.Fail(fmt.Sprintf("第%d行%d列开始时间不可为空, 请按模板导入", i+1, k+1), c)
  3022. return
  3023. }
  3024. startDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3025. if e != nil {
  3026. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3027. startDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3028. if e != nil {
  3029. resp.Fail(fmt.Sprintf("第%d行开始时间格式转换有误, 请按模板导入", i+1), c)
  3030. return
  3031. }
  3032. }
  3033. // 转换后的日期小于1900-01-01表示当前生成的日期是有问题的
  3034. if startDate.Before(checkDate) {
  3035. resp.Fail(fmt.Sprintf("第%d行开始时间格式有误, 请按模板导入", i+1), c)
  3036. return
  3037. }
  3038. rowRegister.StartDate = startDate
  3039. continue
  3040. }
  3041. if k == 59 {
  3042. va := cell.Value
  3043. if va == "" {
  3044. resp.Fail(fmt.Sprintf("第%d行到期时间不可为空, 请按模板导入", i+1), c)
  3045. return
  3046. }
  3047. endDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3048. if e != nil {
  3049. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3050. endDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3051. if e != nil {
  3052. resp.Fail(fmt.Sprintf("第%d行到期时间格式转换有误, 请按模板导入", i+1), c)
  3053. return
  3054. }
  3055. }
  3056. if endDate.Before(checkDate) {
  3057. resp.Fail(fmt.Sprintf("第%d行到期时间格式有误, 请按模板导入", i+1), c)
  3058. return
  3059. }
  3060. rowRegister.EndDate = endDate
  3061. continue
  3062. }
  3063. // 合同金额
  3064. if k == 60 {
  3065. amountStr := v
  3066. amount, e := strconv.ParseFloat(amountStr, 64)
  3067. if e != nil {
  3068. resp.Fail(fmt.Sprintf("第%d行合同金额有误, 请按模板导入", i+1), c)
  3069. return
  3070. }
  3071. rowRegister.ContractAmount = amount
  3072. continue
  3073. }
  3074. // 金额单位
  3075. if k == 61 {
  3076. rate := rateMap[v]
  3077. if rate <= 0 {
  3078. resp.Fail(fmt.Sprintf("第%d行金额单位有误, 请按模板导入", i+1), c)
  3079. return
  3080. }
  3081. rowRegister.CurrencyUnit = v
  3082. rowRegister.RMBRate = rate
  3083. continue
  3084. }
  3085. // FICC 套餐总金额
  3086. if k == 62 {
  3087. amountStr := v
  3088. amount, _ := strconv.ParseFloat(amountStr, 64)
  3089. if amount > 0 {
  3090. tmp := &fms.ContractServiceAmount{
  3091. ProductId: crm.CompanyProductFicc,
  3092. ServiceAmount: amount,
  3093. CurrencyUnit: rowRegister.CurrencyUnit,
  3094. TimeBase: base.TimeBase{},
  3095. }
  3096. rowServiceAmount = append(rowServiceAmount, tmp)
  3097. }
  3098. continue
  3099. }
  3100. // 权益套餐总金额
  3101. if k == 63 {
  3102. amountStr := v
  3103. amount, _ := strconv.ParseFloat(amountStr, 64)
  3104. if amount > 0 {
  3105. tmp := &fms.ContractServiceAmount{
  3106. ProductId: crm.CompanyProductRai,
  3107. ServiceAmount: amount,
  3108. CurrencyUnit: rowRegister.CurrencyUnit,
  3109. TimeBase: base.TimeBase{},
  3110. }
  3111. rowServiceAmount = append(rowServiceAmount, tmp)
  3112. }
  3113. continue
  3114. }
  3115. // 约定付款日期
  3116. if k == 64 {
  3117. rowRegister.AgreedPayTime = v
  3118. continue
  3119. }
  3120. // 签订日
  3121. if k == 65 {
  3122. va := cell.Value
  3123. if va == "" {
  3124. continue
  3125. }
  3126. signDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3127. if e != nil {
  3128. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3129. signDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3130. if e != nil {
  3131. resp.Fail(fmt.Sprintf("第%d行签订日格式转换有误, 请按模板导入", i+1), c)
  3132. return
  3133. }
  3134. }
  3135. if signDate.Before(checkDate) {
  3136. resp.Fail(fmt.Sprintf("第%d行签订日格式有误, 请按模板导入", i+1), c)
  3137. return
  3138. }
  3139. rowRegister.SignDate = signDate
  3140. continue
  3141. }
  3142. // 合同状态
  3143. if k == 66 {
  3144. rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
  3145. if rowRegister.ContractStatus == 0 {
  3146. resp.Fail(fmt.Sprintf("第%d行合同状态不匹配, 请按模板导入", i+1), c)
  3147. return
  3148. }
  3149. continue
  3150. }
  3151. // 合同编号
  3152. if k == 67 {
  3153. rowContractCode := v
  3154. if rowContractCode == "" {
  3155. resp.Fail(fmt.Sprintf("第%d行合同编号不可为空, 请按模板导入", i+1), c)
  3156. return
  3157. }
  3158. if utils.InArrayByStr(contractCodeArr, rowContractCode) {
  3159. // 此合同已登记, 跳过本行的读取
  3160. isSkip = true
  3161. break
  3162. }
  3163. rowRegister.ContractCode = rowContractCode
  3164. continue
  3165. }
  3166. // 合规备注
  3167. if k == 68 {
  3168. rowRegister.Remark = v
  3169. continue
  3170. }
  3171. // 开票列表
  3172. k2 := 68
  3173. for ir := 0; ir < invoiceMax; ir++ {
  3174. n := ir + 1
  3175. // 开票日
  3176. k2 += 1
  3177. if k == k2 {
  3178. if v != "" {
  3179. va := cell.Value
  3180. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3181. if e != nil {
  3182. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3183. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3184. if e != nil {
  3185. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式转换有误, 请按模板导入", i+1, n), c)
  3186. return
  3187. }
  3188. }
  3189. if invoiceDate.Before(checkDate) {
  3190. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式有误, 请按模板导入", i+1, n), c)
  3191. return
  3192. }
  3193. rowInvoices[ir].InvoiceDate = invoiceDate
  3194. rowInvoices[ir].ContractCode = rowRegister.ContractCode
  3195. rowInvoices[ir].InvoiceType = fms.ContractInvoiceTypeMake
  3196. }
  3197. continue
  3198. }
  3199. // 开票金额
  3200. k2 += 1
  3201. if k == k2 {
  3202. if v != "" {
  3203. amountStr := v
  3204. amount, e := strconv.ParseFloat(amountStr, 64)
  3205. if e != nil {
  3206. resp.Fail(fmt.Sprintf("第%d行开票金额%d有误, 请按模板导入", i+1, n), c)
  3207. return
  3208. }
  3209. if rowRegister.RMBRate <= 0 {
  3210. resp.Fail(fmt.Sprintf("第%d行开票金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  3211. return
  3212. }
  3213. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  3214. rowInvoices[ir].OriginAmount = amount
  3215. rowInvoices[ir].Amount = a
  3216. }
  3217. continue
  3218. }
  3219. // 开票套餐类型
  3220. k2 += 1
  3221. if k == k2 {
  3222. if v != "" {
  3223. if v == "FICC套餐" {
  3224. rowInvoices[ir].ServiceProductId = crm.CompanyProductFicc
  3225. } else if v == "权益套餐" {
  3226. rowInvoices[ir].ServiceProductId = crm.CompanyProductRai
  3227. } else {
  3228. resp.Fail(fmt.Sprintf("第%d行开票套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  3229. return
  3230. }
  3231. }
  3232. continue
  3233. }
  3234. // 开票销售
  3235. k2 += 1
  3236. if k == k2 {
  3237. if v != "" {
  3238. sellerItem := sellerMap[v]
  3239. if sellerItem == nil {
  3240. resp.Fail(fmt.Sprintf("第%d行开票销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  3241. return
  3242. }
  3243. rowInvoices[ir].SellerId = sellerItem.SellerId
  3244. rowInvoices[ir].SellerName = sellerItem.SellerName
  3245. rowInvoices[ir].SellerGroupId = sellerItem.GroupId
  3246. rowInvoices[ir].SellerGroupName = sellerItem.GroupName
  3247. rowInvoices[ir].SellerTeamId = sellerItem.TeamId
  3248. rowInvoices[ir].SellerTeamName = sellerItem.TeamName
  3249. }
  3250. continue
  3251. }
  3252. // 备注
  3253. k2 += 1
  3254. if k == k2 {
  3255. if v != "" {
  3256. rowInvoices[ir].Remark = v
  3257. }
  3258. continue
  3259. }
  3260. }
  3261. // 到款列表
  3262. for ir := 0; ir < invoiceMax; ir++ {
  3263. n := ir + 1
  3264. // 到款日
  3265. k2 += 1
  3266. if k == k2 {
  3267. if v != "" {
  3268. va := cell.Value
  3269. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3270. if e != nil {
  3271. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3272. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3273. if e != nil {
  3274. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式转换有误, 请按模板导入", i+1, n), c)
  3275. return
  3276. }
  3277. }
  3278. if invoiceDate.Before(checkDate) {
  3279. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式有误, 请按模板导入", i+1, n), c)
  3280. return
  3281. }
  3282. rowPayments[ir].InvoiceDate = invoiceDate
  3283. rowPayments[ir].ContractCode = rowRegister.ContractCode
  3284. rowPayments[ir].InvoiceType = fms.ContractInvoiceTypePay
  3285. }
  3286. continue
  3287. }
  3288. // 到款金额
  3289. k2 += 1
  3290. if k == k2 {
  3291. if v != "" {
  3292. amountStr := v
  3293. amount, e := strconv.ParseFloat(amountStr, 64)
  3294. if e != nil {
  3295. resp.Fail(fmt.Sprintf("第%d行到款金额%d有误, 请按模板导入", i+1, n), c)
  3296. return
  3297. }
  3298. if rowRegister.RMBRate <= 0 {
  3299. resp.Fail(fmt.Sprintf("第%d行到款金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  3300. return
  3301. }
  3302. // 付款方式
  3303. dayDiff = rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
  3304. contractAmount := rowRegister.ContractAmount
  3305. payType := fmsService.CalculateContractPaymentType(amount, contractAmount, dayDiff)
  3306. rowPayments[ir].PayType = payType
  3307. rowPayments[ir].OriginAmount = amount
  3308. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  3309. rowPayments[ir].Amount = a
  3310. }
  3311. continue
  3312. }
  3313. // 到款套餐类型
  3314. k2 += 1
  3315. if k == k2 {
  3316. if v != "" {
  3317. if v == "FICC套餐" {
  3318. rowPayments[ir].ServiceProductId = crm.CompanyProductFicc
  3319. } else if v == "权益套餐" {
  3320. rowPayments[ir].ServiceProductId = crm.CompanyProductRai
  3321. } else {
  3322. resp.Fail(fmt.Sprintf("第%d行到款套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  3323. return
  3324. }
  3325. }
  3326. continue
  3327. }
  3328. // 到款销售
  3329. k2 += 1
  3330. if k == k2 {
  3331. if v != "" {
  3332. sellerItem := sellerMap[v]
  3333. if sellerItem == nil {
  3334. resp.Fail(fmt.Sprintf("第%d行到款销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  3335. return
  3336. }
  3337. rowPayments[ir].SellerId = sellerItem.SellerId
  3338. rowPayments[ir].SellerName = sellerItem.SellerName
  3339. rowPayments[ir].SellerGroupId = sellerItem.GroupId
  3340. rowPayments[ir].SellerGroupName = sellerItem.GroupName
  3341. rowPayments[ir].SellerTeamId = sellerItem.TeamId
  3342. rowPayments[ir].SellerTeamName = sellerItem.TeamName
  3343. }
  3344. continue
  3345. }
  3346. // 备注
  3347. k2 += 1
  3348. if k == k2 {
  3349. if v != "" {
  3350. rowPayments[ir].Remark = v
  3351. }
  3352. continue
  3353. }
  3354. }
  3355. }
  3356. if isSkip {
  3357. continue
  3358. }
  3359. // 小套餐
  3360. if len(rowChartPermissionIdArr) > 0 {
  3361. // 说明有小套餐
  3362. tempItem := serviceTempNameMap["FICC小套餐"]
  3363. if tempItem == nil {
  3364. resp.Fail(fmt.Sprintf("第%d行小套餐名称不匹配, 请按模板导入", i+1), c)
  3365. return
  3366. }
  3367. rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
  3368. cs := &fms.ContractService{
  3369. ProductId: crm.CompanyProductFicc,
  3370. ServiceTemplateId: tempItem.ServiceTemplateId,
  3371. Title: tempItem.Title,
  3372. Value: tempItem.Value,
  3373. TableValue: tempItem.TableValue,
  3374. ChartPermissionId: tempItem.ChartPermissionId,
  3375. ChartPermissionIds: rowChartPermissionIds,
  3376. }
  3377. cs.Set()
  3378. rowServices = append(rowServices, cs)
  3379. }
  3380. // 如果导入的最后一条合同编号为空并且合同编号之后的字段均为空
  3381. // excel这个包读行的时候不会再往后面没数据的地方读取, 所以此处需要重新判断一次
  3382. if rowRegister.ContractCode == "" {
  3383. resp.Fail(fmt.Sprintf("第%d行合同编号为空", i+1), c)
  3384. return
  3385. }
  3386. rowRegister.RegisterStatus = fms.ContractRegisterStatusIng
  3387. rowInvoiceList := make([]*fms.ContractInvoice, 0)
  3388. // 过滤信息不完整的开票到款
  3389. for l := range rowInvoices {
  3390. if rowInvoices[l].ContractCode != "" {
  3391. if rowInvoices[l].OriginAmount <= 0 || rowInvoices[l].SellerId == 0 {
  3392. resp.Fail(fmt.Sprintf("第%d行开票信息必填项不完整", i+1), c)
  3393. return
  3394. }
  3395. rowRegister.InvoicedAmount += rowInvoices[l].Amount
  3396. rowInvoiceList = append(rowInvoiceList, rowInvoices[l])
  3397. }
  3398. }
  3399. for l := range rowPayments {
  3400. if rowPayments[l].ContractCode != "" {
  3401. if rowPayments[l].OriginAmount <= 0 {
  3402. resp.Fail(fmt.Sprintf("第%d行到款信息必填项不完整", i+1), c)
  3403. return
  3404. }
  3405. rowRegister.PaymentAmount += rowPayments[l].Amount
  3406. rowInvoiceList = append(rowInvoiceList, rowPayments[l])
  3407. }
  3408. }
  3409. // 新增登记、套餐、开票到款信息
  3410. for proId, _ := range productIds {
  3411. rowRegister.ProductIds += strconv.Itoa(proId) + ","
  3412. }
  3413. rowRegister.ProductIds = strings.Trim(rowRegister.ProductIds, ",")
  3414. newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, rowInvoiceList, rowServiceAmount)
  3415. if e != nil {
  3416. resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
  3417. return
  3418. }
  3419. //处理重复公司名日期等重复的开票到款记录
  3420. sellerItemMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  3421. dupList, e := fms.GetDuplicateContractInvoiceDetailItemList(rowRegister.CompanyName, rowRegister.StartDate.Format(utils.FormatDate), rowRegister.EndDate.Format(utils.FormatDate))
  3422. if e != nil {
  3423. err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
  3424. return
  3425. }
  3426. templateIds := make([]int, 0)
  3427. for _, detail := range rowServices {
  3428. templateIds = append(templateIds, detail.ServiceTemplateId)
  3429. }
  3430. sort.Ints(templateIds)
  3431. ids := make([]string, 0)
  3432. for _, id := range templateIds {
  3433. ids = append(ids, strconv.Itoa(id))
  3434. }
  3435. templateIdStr := strings.Join(ids, ",")
  3436. nDupList := make([]*fms.DupInvoice, 0)
  3437. for _, dup := range dupList {
  3438. if templateIdStr == dup.TemplateIds {
  3439. nDupList = append(nDupList, dup)
  3440. }
  3441. }
  3442. //先遍历一遍拿到开票销售信息
  3443. for _, ppItem := range dupList {
  3444. j := 0
  3445. if ppItem.ContractRegisterId != newId {
  3446. if ppItem.InvoiceType == 3 {
  3447. sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
  3448. SellerId: ppItem.SellerId,
  3449. SellerName: ppItem.SellerName,
  3450. GroupId: ppItem.SellerGroupId,
  3451. GroupName: ppItem.SellerGroupName,
  3452. TeamId: ppItem.SellerTeamId,
  3453. TeamName: ppItem.SellerTeamName,
  3454. }
  3455. }
  3456. j++
  3457. }
  3458. }
  3459. for _, ppItem := range dupList {
  3460. j := 0
  3461. if ppItem.ContractRegisterId != newId {
  3462. v := &fms.ContractInvoice{
  3463. ContractRegisterId: newId,
  3464. ContractCode: rowRegister.ContractCode,
  3465. Amount: ppItem.Amount,
  3466. OriginAmount: ppItem.OriginAmount,
  3467. CurrencyUnit: ppItem.CurrencyUnit,
  3468. InvoiceDate: ppItem.InvoiceDate,
  3469. SellerId: ppItem.SellerId,
  3470. SellerName: ppItem.SellerName,
  3471. SellerGroupId: ppItem.SellerGroupId,
  3472. SellerGroupName: ppItem.SellerGroupName,
  3473. SellerTeamId: ppItem.SellerTeamId,
  3474. SellerTeamName: ppItem.SellerTeamName,
  3475. AdminId: int(adminInfo.AdminId),
  3476. AdminName: adminInfo.RealName,
  3477. Remark: ppItem.Remark,
  3478. ServiceProductId: ppItem.ServiceProductId,
  3479. IsPrePay: 1,
  3480. StartDate: ppItem.StartDate,
  3481. EndDate: ppItem.EndDate,
  3482. }
  3483. if ppItem.InvoiceType == 3 {
  3484. v.InvoiceType = 1
  3485. rowRegister.InvoicedAmount += ppItem.Amount
  3486. } else if ppItem.InvoiceType == 4 {
  3487. v.InvoiceType = 2
  3488. if sellerItem, ok := sellerItemMap[j]; ok {
  3489. v.SellerId = sellerItem.SellerId
  3490. v.SellerName = sellerItem.SellerName
  3491. v.SellerGroupId = sellerItem.GroupId
  3492. v.SellerGroupName = sellerItem.GroupName
  3493. v.SellerTeamId = sellerItem.TeamId
  3494. v.SellerTeamName = sellerItem.TeamName
  3495. j++
  3496. }
  3497. rowRegister.PaymentAmount += ppItem.Amount
  3498. }
  3499. v.Set()
  3500. // 到款登记-付款方式
  3501. v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, rowRegister.ContractAmount, dayDiff)
  3502. // 新增的记录
  3503. opData := ""
  3504. //opDataByte, e := json.Marshal(req)
  3505. if e != nil {
  3506. return
  3507. }
  3508. //opData = string(opDataByte)
  3509. opType := fms.ContractRegisterOpTypePrePay
  3510. if ppItem.InvoiceType == 3 {
  3511. opType = fms.ContractRegisterOpTypePreInvoice
  3512. }
  3513. newAmount := decimal.NewFromFloat(0).Round(2)
  3514. a := decimal.NewFromFloat(v.Amount).Round(2)
  3515. newAmount = newAmount.Add(a)
  3516. ia, _ := newAmount.Round(2).Float64()
  3517. logList = append(logList, &fms.ContractRegisterLog{
  3518. ContractRegisterId: newId,
  3519. AdminId: int(adminInfo.AdminId),
  3520. AdminName: adminInfo.RealName,
  3521. OpData: opData,
  3522. OpType: opType,
  3523. CreateTime: time.Now().Local(),
  3524. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  3525. })
  3526. if e := v.Create(); e != nil {
  3527. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  3528. return
  3529. }
  3530. updateCols := []string{"PaymentAmount", "InvoicedAmount"}
  3531. if e = rowRegister.Update(updateCols); e != nil {
  3532. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  3533. return
  3534. }
  3535. //最后删除预到款记录
  3536. e = ppItem.Delete()
  3537. if e != nil {
  3538. resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
  3539. return
  3540. }
  3541. ppOB := new(fms.ContractPreRegister)
  3542. items, e := ppOB.FetchByRegisterId(ppItem.ContractRegisterId)
  3543. if e != nil {
  3544. if e == utils.ErrNoRow {
  3545. resp.Fail("预登记记录不存在或已被删除", c)
  3546. return
  3547. }
  3548. resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
  3549. return
  3550. }
  3551. for _, item := range items {
  3552. e = item.Delete()
  3553. if e != nil {
  3554. resp.FailMsg("删除预登记失败", "Err:"+e.Error(), c)
  3555. return
  3556. }
  3557. }
  3558. }
  3559. }
  3560. // 自动分配套餐金额
  3561. go fmsService.CalculatePaymentServiceAmount(newId)
  3562. newIds = append(newIds, newId)
  3563. }
  3564. }
  3565. }
  3566. // 操作日志
  3567. go func() {
  3568. logOB := new(fms.ContractRegisterLog)
  3569. if e := logOB.AddInBatches(logList); e != nil {
  3570. return
  3571. }
  3572. }()
  3573. resp.Ok("操作成功", c)
  3574. }
  3575. // CurrencyList
  3576. // @Title 货币单位列表
  3577. // @Description 货币单位列表
  3578. // @Success 200 {object} fms.CurrencyUnitItem
  3579. // @router /contract/register/currency_list [get]
  3580. func (rg *RegisterController) CurrencyList(c *gin.Context) {
  3581. list, e := fmsService.GetTodayCurrencyRateList()
  3582. if e != nil {
  3583. resp.FailData("获取失败", "获取今日货币汇率列表失败, Err: "+e.Error(), c)
  3584. return
  3585. }
  3586. resp.OkData("获取成功", list, c)
  3587. }
  3588. // CheckContractName
  3589. // @Title 货币单位列表
  3590. // @Description 货币单位列表
  3591. // @Success 200 {object} fms.CheckContractNameResp
  3592. // @router /contract/register/check_contract_code [get]
  3593. func (rg *RegisterController) CheckContractName(c *gin.Context) {
  3594. var req fms.CheckContractNameReq
  3595. if e := c.BindQuery(&req); e != nil {
  3596. err, ok := e.(validator.ValidationErrors)
  3597. if !ok {
  3598. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  3599. return
  3600. }
  3601. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  3602. return
  3603. }
  3604. existCond := ""
  3605. existPars := make([]interface{}, 0)
  3606. if req.CompanyName != "" {
  3607. // 是否存在相同的合同名称的登记
  3608. existCond = ` company_name = ?`
  3609. existPars = append(existPars, req.CompanyName)
  3610. }
  3611. if req.StartDate != "" && req.EndDate != "" {
  3612. // 日期校验
  3613. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  3614. if e != nil {
  3615. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  3616. return
  3617. }
  3618. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  3619. if e != nil {
  3620. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  3621. return
  3622. }
  3623. if existCond != "" {
  3624. existCond += ` AND (start_date =? and end_date=?)`
  3625. } else {
  3626. existCond = ` start_date = ? and end_date=?`
  3627. }
  3628. existPars = append(existPars, startDate, endDate)
  3629. }
  3630. if req.SellerIds != "" {
  3631. admin := new(crm.Admin)
  3632. sellerIds := strings.Split(req.SellerIds, ",")
  3633. if len(sellerIds) > 2 {
  3634. resp.Fail("最多只能选择两个销售", c)
  3635. return
  3636. }
  3637. var pars []interface{}
  3638. cond := ` admin_id in (?) `
  3639. pars = append(pars, sellerIds)
  3640. sellers, e := admin.List(cond, pars)
  3641. if e != nil {
  3642. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  3643. return
  3644. }
  3645. var sellerId, raiSellerId int
  3646. for _, v := range sellers {
  3647. if v.DepartmentId == crm.SellerDepartmentId {
  3648. sellerId = v.AdminId
  3649. } else if v.DepartmentId == crm.RaiSellerDepartmentId {
  3650. raiSellerId = v.AdminId
  3651. }
  3652. }
  3653. existCond += ` AND (seller_id =? and rai_seller_id=?)`
  3654. existPars = append(existPars, sellerId, raiSellerId)
  3655. }
  3656. if existCond == "" {
  3657. resp.Fail("请输入合同名称或者合同有效期", c)
  3658. return
  3659. }
  3660. // 是否存在相同合同名称的登记
  3661. ob := new(fms.ContractRegister)
  3662. data := fms.CheckContractNameResp{
  3663. Exist: 0,
  3664. }
  3665. _, e := ob.FetchByCondition(existCond, existPars)
  3666. if e != nil {
  3667. if e == utils.ErrNoRow {
  3668. resp.OkData("查询成功", data, c)
  3669. return
  3670. }
  3671. resp.FailMsg("查询失败", "查询相同登记号失败, Err: "+e.Error(), c)
  3672. return
  3673. }
  3674. data.Exist = 1
  3675. resp.OkData("查询成功", data, c)
  3676. return
  3677. }
  3678. // CheckContract
  3679. // @Title 货币单位列表
  3680. // @Description 货币单位列表
  3681. // @Success 200 {object} fms.CheckContractNameResp
  3682. // @router /contract/register/check_contract_duplicate [post]
  3683. func (rg *RegisterController) CheckContractDuplicate(c *gin.Context) {
  3684. var req fms.CheckContractDuplicateReq
  3685. if e := c.ShouldBind(&req); e != nil {
  3686. err, ok := e.(validator.ValidationErrors)
  3687. if !ok {
  3688. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  3689. return
  3690. }
  3691. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  3692. return
  3693. }
  3694. existCond := ""
  3695. existPars := make([]interface{}, 0)
  3696. if req.CompanyName != "" {
  3697. // 是否存在相同的合同名称的登记
  3698. existCond = ` company_name = ?`
  3699. existPars = append(existPars, req.CompanyName)
  3700. }
  3701. if req.StartDate != "" && req.EndDate != "" {
  3702. // 日期校验
  3703. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  3704. if e != nil {
  3705. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  3706. return
  3707. }
  3708. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  3709. if e != nil {
  3710. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  3711. return
  3712. }
  3713. if existCond != "" {
  3714. existCond += ` AND (start_date =? and end_date=?)`
  3715. } else {
  3716. existCond = ` start_date = ? and end_date=?`
  3717. }
  3718. existPars = append(existPars, startDate, endDate)
  3719. }
  3720. if existCond == "" {
  3721. resp.Fail("请输入合同名称或者合同有效期", c)
  3722. return
  3723. }
  3724. data := fms.CheckContractDuplicateResp{
  3725. Exist: 0,
  3726. }
  3727. // 是否存在相同合同名称的登记
  3728. list, e := fms.CheckContractDuplicate(existCond, existPars)
  3729. if e != nil {
  3730. resp.FailMsg("操作失败", "查询重复合同失败, Err: "+e.Error(), c)
  3731. return
  3732. }
  3733. registerIds := make([]int, 0)
  3734. for i := range list {
  3735. registerIds = append(registerIds, list[i].ContractRegisterId)
  3736. }
  3737. idlist, e := fms.CheckContractServiceDuplicate(registerIds)
  3738. if e != nil {
  3739. resp.FailMsg("操作失败", "查询重复合同套餐失败, Err: "+e.Error(), c)
  3740. return
  3741. }
  3742. //校验套餐
  3743. if len(req.Services) > 0 {
  3744. serviceAmountMap := make(map[int]float64)
  3745. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  3746. if e != nil {
  3747. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  3748. return
  3749. }
  3750. templateIds := make([]int, 0)
  3751. for _, detail := range serviceList {
  3752. templateIds = append(templateIds, detail.ServiceTemplateId)
  3753. }
  3754. sort.Ints(templateIds)
  3755. ids := make([]string, 0)
  3756. for _, id := range templateIds {
  3757. ids = append(ids, strconv.Itoa(id))
  3758. }
  3759. templateIdStr := strings.Join(ids, ",")
  3760. for _, s := range idlist {
  3761. if templateIdStr == *s {
  3762. data.Exist = 1
  3763. }
  3764. }
  3765. }
  3766. resp.OkData("查询成功", data, c)
  3767. return
  3768. }