register.go 128 KB

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