register.go 127 KB

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