register.go 127 KB

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