register.go 128 KB

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