material.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  1. package final
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. "sync/atomic"
  7. "time"
  8. "zhiyuan/models/budget"
  9. "zhiyuan/models/final"
  10. "zhiyuan/pkg/app"
  11. "zhiyuan/pkg/config"
  12. "zhiyuan/pkg/db"
  13. "zhiyuan/pkg/logger"
  14. "zhiyuan/pkg/utils"
  15. "zhiyuan/services/admin"
  16. budgetService "zhiyuan/services/budget"
  17. "github.com/w3liu/go-common/constant/timeformat"
  18. "github.com/xuri/excelize/v2"
  19. "github.com/gin-gonic/gin"
  20. )
  21. type MaterialCartAddFrom struct {
  22. MatId int64 `form:"mat_id" json:"mat_id" label:"材料ID" binding:"required"`
  23. Num float64 `form:"num" json:"num" label:"数量"`
  24. ItemId int64 `form:"item_id" json:"item_id" label:"项目类型"`
  25. }
  26. func MaterialCartAdd(c *gin.Context) {
  27. var form MaterialCartAddFrom
  28. if app.Bind(c, &form) != nil {
  29. return
  30. }
  31. adminId := c.GetInt("adminID")
  32. if form.Num <= 0 {
  33. form.Num = 1
  34. }
  35. var mat final.FinalMat
  36. db.GetModel(map[string]interface{}{
  37. "id": form.MatId,
  38. "deleted_at": 0,
  39. }, &mat)
  40. if mat.ID == 0 {
  41. app.ErrorMsg(c, "材料错误", nil)
  42. return
  43. }
  44. if form.ItemId == 0 {
  45. items := make([]final.FinalMatItem, 0)
  46. s := db.ModelQuery(db.Type(items), map[string]interface{}{}, true)
  47. db.WhereParse(&s, map[string]interface{}{
  48. "deleted_at": 0,
  49. })
  50. var mattype final.FinalMatType
  51. db.GetModel(map[string]interface{}{
  52. "id": mat.TypeId,
  53. }, &mattype)
  54. where := "1=2"
  55. where += fmt.Sprintf(" OR find_in_set(%s, `%s`.`mattype_ids`)", s.Param(mattype.ID), final.FinalMatItem{}.TableName())
  56. for _, v := range strings.Split(mattype.Path, ",") {
  57. if v != "" {
  58. i, _ := db.ToInt64(v)
  59. where += fmt.Sprintf(" OR find_in_set(%s, `%s`.`mattype_ids`)", s.Param(i), final.FinalMatItem{}.TableName())
  60. }
  61. }
  62. s.Where = append(s.Where, where)
  63. query, params := s.Query()
  64. db.Query(query, params, &items, final.FinalMatItem{}.DB())
  65. if len(items) == 1 {
  66. form.ItemId = items[0].ID
  67. }
  68. }
  69. var model final.FinalMaterialCart
  70. db.GetModel(map[string]interface{}{
  71. "item_id": form.ItemId,
  72. "admin_id": adminId,
  73. "process_id": 0,
  74. "mat_id": form.MatId,
  75. "deleted_at": 0,
  76. }, &model)
  77. total := utils.FloatMul(mat.Price, form.Num, 2)
  78. if model.ID == 0 {
  79. _, err := db.InsertModel(db.Type(model), map[string]interface{}{
  80. "item_id": form.ItemId,
  81. "admin_id": adminId,
  82. "process_id": 0,
  83. "mat_id": form.MatId,
  84. "price": mat.Price,
  85. "num": form.Num,
  86. "total": total,
  87. })
  88. if err != nil {
  89. app.Error(c, err.Error())
  90. return
  91. }
  92. } else {
  93. err := db.UpdateModel(db.Type(model), model.ID, map[string]interface{}{
  94. "num": utils.FloatAdd(model.Num, form.Num, 2),
  95. "total": total,
  96. })
  97. if err != nil {
  98. app.Error(c, err.Error())
  99. return
  100. }
  101. }
  102. app.Success(c, nil)
  103. }
  104. var num int64
  105. func Generate(t time.Time) string {
  106. s := t.Format(timeformat.Continuity)
  107. m := t.UnixNano()/1e6 - t.UnixNano()/1e9*1e3
  108. ms := sup(m, 3)
  109. p := os.Getpid() % 1000
  110. ps := sup(int64(p), 3)
  111. i := atomic.AddInt64(&num, 1)
  112. r := i % 10000
  113. rs := sup(r, 4)
  114. n := fmt.Sprintf("%s%s%s%s", s, ms, ps, rs)
  115. return n
  116. }
  117. // 对长度不足n的数字前面补0
  118. func sup(i int64, n int) string {
  119. m := fmt.Sprintf("%d", i)
  120. for len(m) < n {
  121. m = fmt.Sprintf("0%s", m)
  122. }
  123. return m
  124. }
  125. type MaterialOrderCreateFrom struct {
  126. Carts []int `form:"carts" json:"carts" label:"购物车" binding:"required"`
  127. SiteId int `form:"site_id" json:"site_id" label:"工地" binding:"required"`
  128. Attachments map[int64]string `form:"attachments" json:"attachments" label:"附件"`
  129. Material int `form:"material" json:"material" label:"项目"`
  130. }
  131. func MaterialOrderCreate(c *gin.Context) {
  132. var form MaterialOrderCreateFrom
  133. if app.Bind(c, &form) != nil {
  134. return
  135. }
  136. adminId := c.GetInt("adminID")
  137. if len(form.Carts) == 0 {
  138. app.ErrorMsg(c, "购物车错误", nil)
  139. return
  140. }
  141. carts, err := db.GetModelMap(db.Type(final.FinalMaterialCartMobile{}), map[string]interface{}{
  142. "admin_id": adminId,
  143. "id in": form.Carts,
  144. "finalmat.state": 1,
  145. "deleted_at": 0,
  146. }, nil)
  147. if err != nil {
  148. app.ErrorMsg(c, err.Error(), nil)
  149. return
  150. }
  151. if len(carts) != len(form.Carts) {
  152. app.ErrorMsg(c, "购物车错误", nil)
  153. return
  154. }
  155. var site final.FinalSite
  156. db.GetModel(map[string]interface{}{
  157. "id": form.SiteId,
  158. "deleted_at": 0,
  159. }, &site)
  160. if site.ID == 0 {
  161. app.ErrorMsg(c, "工地不存在", nil)
  162. return
  163. }
  164. var settle final.FinalSettle
  165. db.GetModel(map[string]interface{}{
  166. "site_id": site.ID,
  167. "deleted_at": 0,
  168. }, &settle)
  169. if settle.ID != 0 {
  170. app.ErrorMsg(c, "已结算,无法下单", nil)
  171. return
  172. }
  173. address := site.Address
  174. if site.Village != " " {
  175. address += " " + site.Village
  176. }
  177. if site.RoomNo != " " {
  178. address += " " + site.RoomNo
  179. }
  180. type FinalMaterialMobile struct {
  181. ID int64 `json:"id" prop:"add:false"`
  182. Residue float64 `json:"residue" label:"金额" prop:"select:budget-ifnull(sum(order.total),0)"`
  183. final.FinalMaterialMobile
  184. }
  185. var material FinalMaterialMobile
  186. if form.Material != 0 {
  187. db.GetModel(map[string]interface{}{
  188. "id": form.Material,
  189. "deleted_at": 0,
  190. }, &material)
  191. if material.ID == 0 {
  192. app.ErrorMsg(c, "下单状态错误", nil)
  193. return
  194. }
  195. }
  196. cTotal := float64(0)
  197. ctyp := int64(0)
  198. itemMap := make(map[int64][]final.FinalMaterialOrderItem, 0)
  199. citemMap := make(map[int64][]final.FinalMaterialOrderItem, 0)
  200. supplierAdminMap := make(map[int64]int64)
  201. supplierTotalMap := make(map[int64]float64)
  202. supplierReduceMap := make(map[int64]int64)
  203. for i, v := range carts {
  204. supplier_id, _ := db.ToInt64(v["supplier_id"])
  205. supplier_admin_id, _ := db.ToInt64(v["supplier_admin_id"])
  206. supplierAdminMap[supplier_id] = supplier_admin_id
  207. supplier_reduce, _ := db.ToInt64(v["supplier_reduce"])
  208. supplierReduceMap[supplier_id] = supplier_reduce
  209. id, _ := db.ToInt64(v["id"])
  210. typ, _ := db.ToInt64(v["type"])
  211. mat_id, _ := db.ToInt64(v["mat_id"])
  212. num, _ := db.ToFloat64(v["num"])
  213. remark := db.ToString(v["remark"])
  214. price, _ := db.ToFloat64(v["mat_price"])
  215. total := utils.FloatMul(price, num, 2)
  216. //total, _ := db.ToFloat64(v["total"])
  217. item_id, _ := db.ToInt64(v["item_id"])
  218. is_custom, _ := db.ToInt64(v["is_custom"])
  219. if num <= 0 {
  220. continue
  221. }
  222. if is_custom == 0 {
  223. is := make([]final.FinalMaterialOrderItem, 0)
  224. if s, ok := itemMap[supplier_id]; ok {
  225. is = s
  226. }
  227. is = append(is, final.FinalMaterialOrderItem{
  228. ID: id,
  229. ItemId: item_id,
  230. MatId: mat_id,
  231. Price: price,
  232. Num: num,
  233. Remark: remark,
  234. Total: total,
  235. })
  236. itemMap[supplier_id] = is
  237. } else {
  238. cs := make([]final.FinalMaterialOrderItem, 0)
  239. if s, ok := citemMap[supplier_id]; ok {
  240. cs = s
  241. }
  242. cs = append(cs, final.FinalMaterialOrderItem{
  243. ID: id,
  244. ItemId: item_id,
  245. MatId: mat_id,
  246. Price: price,
  247. Num: num,
  248. Remark: remark,
  249. Total: total,
  250. })
  251. citemMap[supplier_id] = cs
  252. }
  253. if i == 0 {
  254. ctyp = typ
  255. } else {
  256. if ctyp != typ {
  257. app.ErrorMsg(c, "下单类型错误", nil)
  258. return
  259. }
  260. }
  261. if _, ok := supplierTotalMap[supplier_id]; !ok {
  262. supplierTotalMap[supplier_id] = 0
  263. }
  264. supplierTotalMap[supplier_id] = utils.FloatAdd(supplierTotalMap[supplier_id], total, 2)
  265. cTotal = utils.FloatAdd(cTotal, total, 2)
  266. }
  267. if material.ID != 0 && cTotal > material.Residue {
  268. app.ErrorMsg(c, "下单金额大于控量", nil)
  269. return
  270. }
  271. supplierids := make([]int64, 0)
  272. for id, _ := range supplierAdminMap {
  273. supplierids = append(supplierids, id)
  274. }
  275. suppliers, err := db.GetModelMap(db.Type(final.FinalSupplierPrepaymentStatist{}), map[string]interface{}{
  276. "id in": supplierids,
  277. "prepayment": 1,
  278. "deleted_at": 0,
  279. }, nil)
  280. if err != nil {
  281. app.ErrorMsg(c, err.Error(), nil)
  282. return
  283. }
  284. for _, v := range suppliers {
  285. id, _ := db.ToInt64(v["id"])
  286. name := db.ToString(v["name"])
  287. warning_amount, _ := db.ToFloat64(v["warning_amount"])
  288. notice_ids := db.ToString(v["notice_ids"])
  289. total, _ := db.ToFloat64(v["total"])
  290. noticeIds := make([]int64, 0)
  291. for _, i := range strings.Split(notice_ids, ",") {
  292. if i != "" {
  293. if n, ok := db.ToInt64(i); ok {
  294. noticeIds = append(noticeIds, n)
  295. }
  296. }
  297. }
  298. if supplierTotalMap[id] > total {
  299. for _, i := range noticeIds {
  300. err := final.SendMaterialMessage(int(i), "", 0, address, "材料商"+name+"预付款金额不足,下单失败")
  301. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  302. }
  303. app.ErrorMsg(c, "材料商"+name+"预付款金额不足,下单失败", nil)
  304. return
  305. }
  306. if total-supplierTotalMap[id] <= warning_amount {
  307. for _, i := range noticeIds {
  308. err := final.SendMaterialMessage(int(i), "", 0, address, "材料商"+name+"预付款金额仅剩"+db.ToString(total-supplierTotalMap[id]))
  309. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  310. }
  311. }
  312. }
  313. orderNo := Generate(time.Now())
  314. n := 0
  315. supplierOrderMap := make(map[int64]final.FinalMaterialOrder)
  316. customOrdersMap := make(map[int64]final.FinalMaterialOrder)
  317. for is_custom, itemmap := range []map[int64][]final.FinalMaterialOrderItem{itemMap, citemMap} {
  318. for supplier_id, items := range itemmap {
  319. n++
  320. order_no := orderNo
  321. if len(itemMap)+len(citemMap) > 1 {
  322. order_no = order_no + "-" + db.ToString(n)
  323. }
  324. total := float64(0)
  325. cartids := make([]int64, 0)
  326. for _, v := range items {
  327. cartids = append(cartids, v.ID)
  328. total = utils.FloatAdd(total, v.Total, 2)
  329. }
  330. xs := total - float64(int64(total))
  331. total = float64(int64(total))
  332. if xs >= 0.6 {
  333. total += 1
  334. }
  335. datas := map[string]interface{}{
  336. "order_no": order_no,
  337. "site_id": form.SiteId,
  338. "type": ctyp,
  339. "is_custom": is_custom,
  340. "type_id": material.ID,
  341. "supplier_id": supplier_id,
  342. "attachment": form.Attachments[supplier_id],
  343. "total": total,
  344. "state": 0,
  345. "take_time": time.Now().Unix(),
  346. "created_id": adminId,
  347. }
  348. if is_custom == 1 {
  349. datas["state"] = 8
  350. if site.PkgId == 7 {
  351. datas["state"] = 9
  352. }
  353. } else {
  354. if supplierReduceMap[supplier_id] == 1 {
  355. datas["state"] = 2
  356. }
  357. }
  358. orderid, err := db.InsertModel(db.Type(final.FinalMaterialOrder{}), datas)
  359. if err != nil {
  360. app.ErrorMsg(c, err.Error(), nil)
  361. return
  362. }
  363. if is_custom == 0 {
  364. supplierOrderMap[supplier_id] = final.FinalMaterialOrder{
  365. ID: orderid,
  366. OrderNo: order_no,
  367. }
  368. } else {
  369. customOrdersMap[supplier_id] = final.FinalMaterialOrder{
  370. ID: orderid,
  371. OrderNo: order_no,
  372. }
  373. }
  374. for _, v := range items {
  375. _, err := db.InsertModel(db.Type(final.FinalMaterialOrderItem{}), map[string]interface{}{
  376. "item_id": v.ItemId,
  377. "order_id": orderid,
  378. "mat_id": v.MatId,
  379. "price": v.Price,
  380. "num": v.Num,
  381. "total": v.Total,
  382. "remark": v.Remark,
  383. })
  384. if err != nil {
  385. app.ErrorMsg(c, err.Error(), nil)
  386. return
  387. }
  388. }
  389. process_id, err := db.InsertModel(db.Type(final.FinalMaterialOrderProcess{}), map[string]interface{}{
  390. "order_id": orderid,
  391. "type": 0,
  392. "created_id": adminId,
  393. })
  394. if err != nil {
  395. app.ErrorMsg(c, err.Error(), nil)
  396. return
  397. }
  398. if is_custom == 1 && site.PkgId == 7 {
  399. _, err := db.InsertModel(db.Type(final.FinalMaterialOrderProcess{}), map[string]interface{}{
  400. "order_id": orderid,
  401. "type": 11,
  402. "created_id": adminId,
  403. })
  404. if err != nil {
  405. app.ErrorMsg(c, err.Error(), nil)
  406. return
  407. }
  408. }
  409. err = db.UpdateModels(db.Type(final.FinalMaterialCart{}), map[string]interface{}{
  410. "admin_id": adminId,
  411. "id in": cartids,
  412. "deleted_at": 0,
  413. }, map[string]interface{}{
  414. "process_id": process_id,
  415. })
  416. if err != nil {
  417. app.ErrorMsg(c, err.Error(), nil)
  418. return
  419. }
  420. }
  421. }
  422. if material.ID != 0 {
  423. db.UpdateModel(db.Type(material), material.ID, map[string]interface{}{
  424. "state": 1,
  425. })
  426. }
  427. for s, o := range supplierOrderMap {
  428. if supplierReduceMap[s] == 1 {
  429. err := final.SendMaterialMessage(int(supplierAdminMap[s]), o.OrderNo, o.ID, address, "订单已下单,请安排配送")
  430. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  431. } else {
  432. err := final.SendMaterialMessage(int(supplierAdminMap[s]), o.OrderNo, o.ID, address, "订单已下单,请安排备货")
  433. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  434. }
  435. }
  436. for s, o := range customOrdersMap {
  437. if site.PkgId == 7 {
  438. err := final.SendMaterialMessage(int(supplierAdminMap[s]), o.OrderNo, o.ID, address, "已通知测量,请及时安排")
  439. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  440. } else {
  441. err := final.SendMaterialMessage(int(site.ManagerId), o.OrderNo, o.ID, address, "定制品已下单,请通知测量")
  442. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  443. }
  444. }
  445. app.Success(c, nil)
  446. }
  447. type MaterialOrderProcessCheckFrom struct {
  448. ProcessId int64 `form:"process_id" json:"process_id" label:"流程ID" binding:"required"`
  449. Check int `form:"check" json:"check" label:"状态"`
  450. CheckMark string `form:"checkmark" json:"checkmark" label:"留言"`
  451. }
  452. func MaterialOrderProcessCheck(c *gin.Context) {
  453. var form MaterialOrderProcessCheckFrom
  454. if app.Bind(c, &form) != nil {
  455. return
  456. }
  457. adminId := c.GetInt("adminID")
  458. var process final.FinalMaterialOrderProcess
  459. db.GetModel(map[string]interface{}{
  460. "id": form.ProcessId,
  461. "deleted_at": 0,
  462. }, &process)
  463. if process.ID == 0 {
  464. app.ErrorMsg(c, "流程错误", nil)
  465. return
  466. }
  467. var order final.FinalMaterialOrder
  468. db.GetModel(map[string]interface{}{
  469. "id": process.OrderId,
  470. "deleted_at": 0,
  471. }, &order)
  472. if order.ID == 0 || order.ProcessId != process.ID {
  473. app.ErrorMsg(c, "流程错误", nil)
  474. return
  475. }
  476. var site final.FinalSite
  477. db.GetModel(map[string]interface{}{
  478. "id": order.SiteId,
  479. "deleted_at": 0,
  480. }, &site)
  481. if site.ID == 0 {
  482. app.ErrorMsg(c, "工地不存在", nil)
  483. return
  484. }
  485. address := site.Address
  486. if site.Village != " " {
  487. address += " " + site.Village
  488. }
  489. if site.RoomNo != " " {
  490. address += " " + site.RoomNo
  491. }
  492. var supplier final.FinalSupplier
  493. db.GetModel(map[string]interface{}{
  494. "id": order.SupplierId,
  495. "deleted_at": 0,
  496. }, &supplier)
  497. data := map[string]interface{}{
  498. "check": form.Check,
  499. "checkmark": form.CheckMark,
  500. "check_id": adminId,
  501. "check_at": time.Now().Unix(),
  502. }
  503. dataOrder := map[string]interface{}{
  504. "process_id": 0,
  505. }
  506. name := ""
  507. adminInfo, _ := admin.GetInfoByID(int(process.CreatedId), nil, nil)
  508. if adminInfo != nil {
  509. name = adminInfo.Username
  510. }
  511. if process.Type == 6 {
  512. data = map[string]interface{}{}
  513. dataOrder = map[string]interface{}{}
  514. /*if admin.CheckAuth([]string{"final:verify:audit"}, adminId) && process.CheckAt == 0 {
  515. data["check"] = form.Check
  516. data["checkmark"] = form.CheckMark
  517. data["check_id"] = adminId
  518. data["check_at"] = time.Now().Unix()
  519. process.CheckAt = time.Now().Unix()
  520. }*/
  521. if adminId == int(site.ManagerId) && process.CheckAt2 == 0 {
  522. data["check2"] = form.Check
  523. data["checkmark2"] = form.CheckMark
  524. data["check_id2"] = adminId
  525. data["check_at2"] = time.Now().Unix()
  526. process.CheckAt2 = time.Now().Unix()
  527. }
  528. if adminId == int(supplier.AdminId) && process.CheckAt3 == 0 {
  529. data["check3"] = form.Check
  530. data["checkmark3"] = form.CheckMark
  531. data["check_id3"] = adminId
  532. data["check_at3"] = time.Now().Unix()
  533. process.CheckAt3 = time.Now().Unix()
  534. }
  535. if len(data) == 0 {
  536. app.ErrorMsg(c, "没有权限", nil)
  537. return
  538. }
  539. /*if process.CreatedId == supplier.AdminId {
  540. if adminId != int(order.CreatedId) {
  541. app.ErrorMsg(c, "没有权限", nil)
  542. return
  543. }
  544. } else {
  545. if adminId != int(supplier.AdminId) {
  546. app.ErrorMsg(c, "没有权限", nil)
  547. return
  548. }
  549. }*/
  550. if form.Check == 0 {
  551. //if process.CheckAt != 0 && process.CheckAt2 != 0 && process.CheckAt3 != 0 {
  552. if (process.CheckAt2 != 0 || site.ManagerId == process.CreatedId) && process.CheckAt3 != 0 {
  553. dataOrder["state"] = -1
  554. dataOrder["process_id"] = 0
  555. final.SendMaterialMessage(int(process.CreatedId), order.OrderNo, order.ID, address, "订单已取消")
  556. }
  557. } else {
  558. dataOrder["process_id"] = 0
  559. final.SendMaterialMessage(int(process.CreatedId), order.OrderNo, order.ID, address, name+"不同意取消订单")
  560. }
  561. } else if process.Type == 7 {
  562. data = map[string]interface{}{}
  563. dataOrder = map[string]interface{}{}
  564. if admin.CheckAuth([]string{"final:verify:audit"}, adminId) && process.CheckAt == 0 {
  565. data["check"] = form.Check
  566. data["checkmark"] = form.CheckMark
  567. data["check_id"] = adminId
  568. data["check_at"] = time.Now().Unix()
  569. process.CheckAt = time.Now().Unix()
  570. }
  571. if adminId == int(order.CreatedId) && process.CheckAt2 == 0 {
  572. data["check2"] = form.Check
  573. data["checkmark2"] = form.CheckMark
  574. data["check_id2"] = adminId
  575. data["check_at2"] = time.Now().Unix()
  576. process.CheckAt2 = time.Now().Unix()
  577. }
  578. if len(data) == 0 {
  579. app.ErrorMsg(c, "没有权限", nil)
  580. return
  581. }
  582. /*if !admin.CheckAuth([]string{"final:verify:audit"}, adminId) {
  583. app.ErrorMsg(c, "没有权限", nil)
  584. return
  585. }*/
  586. if form.Check == 0 {
  587. if process.CheckAt != 0 && process.CheckAt2 != 0 {
  588. carts := make([]final.FinalMaterialCart, 0)
  589. db.GetModel(map[string]interface{}{
  590. "process_id": process.ID,
  591. "deleted_at": 0,
  592. }, &carts)
  593. _, err := db.BuildUpdate(final.FinalMaterialOrderItem{}.TableName(), map[string]interface{}{
  594. "order_id": order.ID,
  595. "deleted_at": 0,
  596. }, map[string]interface{}{
  597. "deleted_at": time.Now().Unix(),
  598. }, final.FinalMaterialOrderItem{}.DB())
  599. if err != nil {
  600. app.ErrorMsg(c, err.Error(), nil)
  601. return
  602. }
  603. total := float64(0)
  604. for _, v := range carts {
  605. _, err := db.InsertModel(db.Type(final.FinalMaterialOrderItem{}), map[string]interface{}{
  606. "order_id": order.ID,
  607. "mat_id": v.MatId,
  608. "price": v.Price,
  609. "num": v.Num,
  610. "total": v.Total,
  611. "remark": v.Remark,
  612. })
  613. if err != nil {
  614. app.ErrorMsg(c, err.Error(), nil)
  615. return
  616. }
  617. total = utils.FloatAdd(total, v.Total, 2)
  618. }
  619. dataOrder["total"] = total
  620. dataOrder["process_id"] = 0
  621. final.SendMaterialMessage(int(process.CreatedId), order.OrderNo, order.ID, address, "订单已修改")
  622. }
  623. } else {
  624. dataOrder["process_id"] = 0
  625. final.SendMaterialMessage(int(process.CreatedId), order.OrderNo, order.ID, address, name+"不同意修改订单")
  626. }
  627. } else if process.Type == 12 {
  628. data = map[string]interface{}{}
  629. dataOrder = map[string]interface{}{}
  630. if admin.CheckAuth([]string{"final:verify:audit"}, adminId) && process.CheckAt == 0 {
  631. data["check"] = form.Check
  632. data["checkmark"] = form.CheckMark
  633. data["check_id"] = adminId
  634. data["check_at"] = time.Now().Unix()
  635. process.CheckAt = time.Now().Unix()
  636. }
  637. if adminId == int(order.CreatedId) && process.CheckAt2 == 0 {
  638. data["check2"] = form.Check
  639. data["checkmark2"] = form.CheckMark
  640. data["check_id2"] = adminId
  641. data["check_at2"] = time.Now().Unix()
  642. process.CheckAt2 = time.Now().Unix()
  643. }
  644. if len(data) == 0 {
  645. app.ErrorMsg(c, "没有权限", nil)
  646. return
  647. }
  648. /*if !admin.CheckAuth([]string{"final:verify:audit"}, adminId) {
  649. app.ErrorMsg(c, "没有权限", nil)
  650. return
  651. }*/
  652. if form.Check == 0 {
  653. if process.CheckAt != 0 && process.CheckAt2 != 0 {
  654. carts := make([]final.FinalMaterialCart, 0)
  655. db.GetModel(map[string]interface{}{
  656. "process_id": process.ID,
  657. "deleted_at": 0,
  658. }, &carts)
  659. _, err := db.BuildUpdate(final.FinalMaterialOrderItem{}.TableName(), map[string]interface{}{
  660. "order_id": order.ID,
  661. "deleted_at": 0,
  662. }, map[string]interface{}{
  663. "deleted_at": time.Now().Unix(),
  664. }, final.FinalMaterialOrderItem{}.DB())
  665. if err != nil {
  666. app.ErrorMsg(c, err.Error(), nil)
  667. return
  668. }
  669. total := float64(0)
  670. for _, v := range carts {
  671. _, err := db.InsertModel(db.Type(final.FinalMaterialOrderItem{}), map[string]interface{}{
  672. "order_id": order.ID,
  673. "mat_id": v.MatId,
  674. "price": v.Price,
  675. "num": v.Num,
  676. "total": v.Total,
  677. "remark": v.Remark,
  678. })
  679. if err != nil {
  680. app.ErrorMsg(c, err.Error(), nil)
  681. return
  682. }
  683. total = utils.FloatAdd(total, v.Total, 2)
  684. }
  685. dataOrder["total"] = total
  686. dataOrder["state"] = 0
  687. dataOrder["take_time"] = time.Now().Unix()
  688. dataOrder["process_id"] = 0
  689. final.SendMaterialMessage(int(process.CreatedId), order.OrderNo, order.ID, address, "测量订单修改已通过审核,请及时安排备货")
  690. }
  691. } else {
  692. dataOrder["state"] = 9
  693. dataOrder["process_id"] = 0
  694. final.SendMaterialMessage(int(process.CreatedId), order.OrderNo, order.ID, address, "测量订单修改未通过审核")
  695. }
  696. } else if process.Type == 14 {
  697. data = map[string]interface{}{}
  698. dataOrder = map[string]interface{}{}
  699. if adminId == int(site.ManagerId) && process.CheckAt == 0 {
  700. data["check"] = form.Check
  701. data["checkmark"] = form.CheckMark
  702. data["check_id"] = adminId
  703. data["check_at"] = time.Now().Unix()
  704. process.CheckAt = time.Now().Unix()
  705. }
  706. if form.Check == 0 {
  707. //if process.CheckAt != 0 && process.CheckAt2 != 0 && process.CheckAt3 != 0 {
  708. if process.CheckAt != 0 {
  709. if process.CheckAt-process.CreatedAt > 2*24*60*60 {
  710. dataOrder["report_timeout"] = order.ReportTimeout + 1
  711. }
  712. dataOrder["state"] = 8
  713. dataOrder["process_id"] = 0
  714. final.SendMaterialMessage(int(process.CreatedId), order.OrderNo, order.ID, address, "不具备测量条件已通过审核")
  715. }
  716. } else {
  717. dataOrder["process_id"] = 0
  718. final.SendMaterialMessage(int(process.CreatedId), order.OrderNo, order.ID, address, name+"不同意不具备测量条件")
  719. }
  720. } else {
  721. app.ErrorMsg(c, "流程错误", nil)
  722. return
  723. }
  724. if len(dataOrder) != 0 {
  725. err := db.UpdateModel(db.Type(final.FinalMaterialOrder{}), order.ID, dataOrder)
  726. if err != nil {
  727. app.ErrorMsg(c, err.Error(), nil)
  728. return
  729. }
  730. }
  731. err := db.UpdateModel(db.Type(final.FinalMaterialOrderProcess{}), process.ID, data)
  732. if err != nil {
  733. app.ErrorMsg(c, err.Error(), nil)
  734. return
  735. }
  736. app.Success(c, nil)
  737. }
  738. type MaterialOrderCartAddFrom struct {
  739. OrderId int64 `form:"order_id" json:"order_id" label:"订单ID" binding:"required"`
  740. }
  741. func MaterialOrderCartAdd(c *gin.Context) {
  742. var form MaterialOrderCartAddFrom
  743. if app.Bind(c, &form) != nil {
  744. return
  745. }
  746. adminId := c.GetInt("adminID")
  747. items := make([]final.FinalMaterialOrderItem, 0)
  748. db.GetModel(map[string]interface{}{
  749. "order_id": form.OrderId,
  750. "deleted_at": 0,
  751. }, &items)
  752. var model final.FinalMaterialCart
  753. _, err := db.BuildUpdate(model.TableName(), map[string]interface{}{
  754. "admin_id": adminId,
  755. "process_id": 0,
  756. "deleted_at": 0,
  757. }, map[string]interface{}{
  758. "deleted_at": time.Now().Unix(),
  759. }, model.DB())
  760. if err != nil {
  761. app.ErrorMsg(c, err.Error(), nil)
  762. return
  763. }
  764. for _, v := range items {
  765. _, err := db.InsertModel(db.Type(model), map[string]interface{}{
  766. "admin_id": adminId,
  767. "process_id": 0,
  768. "item_id": v.ItemId,
  769. "mat_id": v.MatId,
  770. "price": v.Price,
  771. "num": v.Num,
  772. "remark": v.Remark,
  773. "total": v.Total,
  774. })
  775. if err != nil {
  776. app.Error(c, err.Error())
  777. return
  778. }
  779. }
  780. app.Success(c, nil)
  781. }
  782. type Order struct {
  783. ID int64 `json:"id" prop:"add:false"`
  784. SiteId int64 `json:"site_id" label:"工地" type:"int" prop:"add:false" search:"="`
  785. Total float64 `json:"total" label:"金额" type:"float" prop:"add:false" default:"0"`
  786. SupplierId int64 `json:"supplier_id" label:"材料商ID" type:"int" prop:"add:false" search:"="`
  787. ShopId int64 `json:"shop_id" label:"门店" type:"int" prop:"select:finalsite.shop_id" search:"="`
  788. OverTime int64 `json:"over_time" label:"完成时间" type:"int" prop:"add:false" default:"0" search:"="`
  789. final.FinalMaterialOrderMobile
  790. }
  791. type ContractDeduction struct {
  792. ContractId int64 `json:"contractId"`
  793. Name string `json:"name"`
  794. Amount float64 `json:"amount"`
  795. }
  796. type PunishDeduction struct {
  797. PunishId int64 `json:"punishId"`
  798. Explain string `json:"explain"`
  799. Amount float64 `json:"amount"`
  800. }
  801. type OrderPunishDeduction struct {
  802. PunishId int64 `json:"punishId"`
  803. OrderId int64 `json:"orderId"`
  804. OrderNo string `json:"order_no"`
  805. Explain string `json:"explain"`
  806. Amount float64 `json:"amount"`
  807. }
  808. func materialSettleDeduction(supplierId int64, shopId int64, orders []Order) (amount float64, contractDeductions []ContractDeduction, punishDeductions []PunishDeduction, orderPunishDeduction []OrderPunishDeduction) {
  809. orderAmount := float64(0)
  810. for _, order := range orders {
  811. orderAmount = utils.FloatAdd(orderAmount, order.Total, 2)
  812. }
  813. amount = 0
  814. type FinalSupplierContractStatist struct {
  815. ID int64 `json:"id" prop:"add:false"`
  816. Name string `json:"name" label:"名称" type:"string" prop:"add edit"`
  817. StartDate int64 `json:"startdate" label:"开始日期" type:"int" prop:"add edit"`
  818. EndDate int64 `json:"enddate" label:"截止日期" type:"int" prop:"add edit"`
  819. Info string `json:"info" label:"返点" type:"string" prop:"edit"`
  820. AmountTotal float64 `json:"amount_total" type:"float" prop:"select:ifnull(deduction.amount_total,0)"`
  821. DeductionTotal float64 `json:"deduction_total" type:"float" prop:"select:ifnull(deduction.deduction_total,0)"`
  822. final.FinalSupplierContractStatist
  823. }
  824. contracts := make([]FinalSupplierContractStatist, 0)
  825. db.GetModel(map[string]interface{}{
  826. "supplierId": supplierId,
  827. "state": 1,
  828. "deleted_at": 0,
  829. }, &contracts)
  830. contractDeductions = make([]ContractDeduction, 0)
  831. for _, contract := range contracts {
  832. if orderAmount <= 0 {
  833. break
  834. }
  835. //contractOrders := make([]Order, 0)
  836. contractOrderTotal := float64(0)
  837. for _, order := range orders {
  838. if order.OverTime >= contract.StartDate && order.OverTime < contract.EndDate+24*3600 {
  839. //contractOrders = append(contractOrders, order)
  840. contractOrderTotal = utils.FloatAdd(contractOrderTotal, order.Total, 2)
  841. }
  842. }
  843. //if len(contractOrders) == 0 {
  844. // continue
  845. //}
  846. amountTotal := utils.FloatAdd(contract.AmountTotal, contractOrderTotal, 2)
  847. point := float64(0)
  848. points := final.FinalSupplierContractPoints(contract.Info)
  849. for _, v := range points {
  850. if amountTotal >= v.Amount && v.Point > point {
  851. point = v.Point
  852. }
  853. }
  854. pointAmount := utils.FloatSub(utils.FloatDiv(utils.FloatMul(amountTotal, point, 2), 100, 2), contract.DeductionTotal, 2)
  855. if pointAmount <= 0 {
  856. continue
  857. }
  858. if pointAmount > orderAmount {
  859. pointAmount = orderAmount
  860. }
  861. orderAmount = utils.FloatSub(orderAmount, pointAmount, 2)
  862. contractDeductions = append(contractDeductions, ContractDeduction{
  863. ContractId: contract.ID,
  864. Name: contract.Name,
  865. Amount: pointAmount,
  866. })
  867. amount = utils.FloatAdd(amount, pointAmount, 2)
  868. }
  869. type FinalSupplierPunishStatist struct {
  870. ID int64 `json:"id" prop:"add:false"`
  871. Amount float64 `json:"amount" label:"金额" type:"float" prop:"add edit" default:"0" search:"="`
  872. Explain string `json:"explain" label:"说明" type:"string" prop:"edit" search:"like"`
  873. Punished float64 `json:"punished" label:"已罚金额" type:"float" prop:"select:ifnull(deduction.deduction_total,0)"`
  874. final.FinalSupplierPunishStatist
  875. }
  876. punishs := make([]FinalSupplierPunishStatist, 0)
  877. s := db.ModelQuery(db.Type(punishs), map[string]interface{}{}, true)
  878. db.WhereParse(&s, map[string]interface{}{
  879. "supplierId": supplierId,
  880. "deleted_at": 0,
  881. })
  882. s.Where = append(s.Where, "`zy_final_supplier_punish`.`amount` > ifnull(`deduction`.`deduction_total`,0)")
  883. query, params := s.Query()
  884. db.Query(query, params, &punishs, FinalSupplierPunishStatist{}.DB())
  885. punishDeductions = make([]PunishDeduction, 0)
  886. for _, punish := range punishs {
  887. if orderAmount <= 0 {
  888. break
  889. }
  890. punishAmount := utils.FloatSub(punish.Amount, punish.Punished, 2)
  891. if punishAmount <= 0 {
  892. continue
  893. }
  894. if punishAmount > orderAmount {
  895. punishAmount = orderAmount
  896. }
  897. orderAmount = utils.FloatSub(orderAmount, punishAmount, 2)
  898. punishDeductions = append(punishDeductions, PunishDeduction{
  899. PunishId: punish.ID,
  900. Explain: punish.Explain,
  901. Amount: punishAmount,
  902. })
  903. amount = utils.FloatAdd(amount, punishAmount, 2)
  904. }
  905. type FinalOrderPunishStatist struct {
  906. ID int64 `json:"id" prop:"add:false"`
  907. OrderNo string `json:"order_no" label:"订单号" type:"string" prop:"select:order.order_no"`
  908. OrderId int64 `json:"orderId" label:"订单ID" type:"int" prop:"add" search:"="`
  909. Amount float64 `json:"amount" label:"金额" type:"float" prop:"add edit" default:"0" search:"="`
  910. Explain string `json:"explain" label:"说明" type:"string" prop:"edit" search:"like"`
  911. Punished float64 `json:"punished" label:"已罚金额" type:"float" prop:"select:ifnull(deduction.deduction_total,0)"`
  912. final.FinalOrderPunishStatist
  913. }
  914. orderpunishs := make([]FinalOrderPunishStatist, 0)
  915. s = db.ModelQuery(db.Type(orderpunishs), map[string]interface{}{}, true)
  916. db.WhereParse(&s, map[string]interface{}{
  917. "order.supplier_id": supplierId,
  918. "finalsite.shop_id": shopId,
  919. "deleted_at": 0,
  920. })
  921. s.Where = append(s.Where, "`zy_final_order_punish`.`amount` > ifnull(`deduction`.`deduction_total`,0)")
  922. query, params = s.Query()
  923. db.Query(query, params, &orderpunishs, FinalSupplierPunishStatist{}.DB())
  924. orderPunishDeduction = make([]OrderPunishDeduction, 0)
  925. for _, punish := range orderpunishs {
  926. if orderAmount <= 0 {
  927. break
  928. }
  929. punishAmount := utils.FloatSub(punish.Amount, punish.Punished, 2)
  930. if punishAmount <= 0 {
  931. continue
  932. }
  933. if punishAmount > orderAmount {
  934. punishAmount = orderAmount
  935. }
  936. orderAmount = utils.FloatSub(orderAmount, punishAmount, 2)
  937. orderPunishDeduction = append(orderPunishDeduction, OrderPunishDeduction{
  938. PunishId: punish.ID,
  939. OrderId: punish.OrderId,
  940. OrderNo: punish.OrderNo,
  941. Explain: punish.Explain,
  942. Amount: punishAmount,
  943. })
  944. amount = utils.FloatAdd(amount, punishAmount, 2)
  945. }
  946. return
  947. }
  948. type MaterialSettleDeductionFrom struct {
  949. Orders []int `form:"orders" json:"orders" label:"订单" binding:"required"`
  950. }
  951. func MaterialSettleDeduction(c *gin.Context) {
  952. var form MaterialSettleDeductionFrom
  953. if app.Bind(c, &form) != nil {
  954. return
  955. }
  956. if len(form.Orders) == 0 {
  957. app.ErrorMsg(c, "没有权限", nil)
  958. return
  959. }
  960. adminid := c.GetInt("adminID")
  961. suppliers := make([]final.FinalSupplier, 0)
  962. db.GetModel(map[string]interface{}{
  963. "adminId": adminid,
  964. "deleted_at": 0,
  965. }, &suppliers)
  966. supplierids := make([]int64, 0)
  967. for _, v := range suppliers {
  968. supplierids = append(supplierids, v.ID)
  969. }
  970. orders := make([]Order, 0)
  971. db.GetModel(map[string]interface{}{
  972. "id in": form.Orders,
  973. "supplier_id in": supplierids,
  974. "state": 11,
  975. "process_id": 0,
  976. "settle_id": 0,
  977. "deleted_at": 0,
  978. }, &orders)
  979. if len(orders) != len(form.Orders) {
  980. app.ErrorMsg(c, "订单错误", nil)
  981. return
  982. }
  983. amount := float64(0)
  984. shop_id := orders[0].ShopId
  985. supplier_id := orders[0].SupplierId
  986. orderMap := make(map[int64][]Order)
  987. for _, order := range orders {
  988. //amount = utils.FloatAdd(amount, order.Total, 2)
  989. if order.ShopId != shop_id {
  990. app.ErrorMsg(c, "没有权限", nil)
  991. return
  992. }
  993. if order.SupplierId != supplier_id {
  994. app.ErrorMsg(c, "没有权限", nil)
  995. return
  996. }
  997. if _, ok := orderMap[order.SiteId]; !ok {
  998. orderMap[order.SiteId] = make([]Order, 0)
  999. }
  1000. orderMap[order.SiteId] = append(orderMap[order.SiteId], order)
  1001. }
  1002. for _, os := range orderMap {
  1003. total := float64(0)
  1004. for _, order := range os {
  1005. total = utils.FloatAdd(total, order.Total, 2)
  1006. }
  1007. xs := total - float64(int64(total))
  1008. total = float64(int64(total))
  1009. if xs >= 0.6 {
  1010. total += 1
  1011. }
  1012. amount = utils.FloatAdd(amount, total, 2)
  1013. }
  1014. deduction, contracts, punishs, orderPunishs := materialSettleDeduction(supplier_id, shop_id, orders)
  1015. total := utils.FloatSub(amount, deduction, 2)
  1016. app.Success(c, map[string]interface{}{
  1017. "deduction": deduction,
  1018. "contracts": contracts,
  1019. "amount": amount,
  1020. "punishs": punishs,
  1021. "orderPunishs": orderPunishs,
  1022. "total": total,
  1023. })
  1024. }
  1025. type MaterialSettleAddFrom struct {
  1026. Orders []int `form:"orders" json:"orders" label:"订单" binding:"required"`
  1027. AccountId int `form:"account_id" json:"account_id" label:"账户" binding:"required"`
  1028. Explain string `form:"explain" json:"explain" label:"说明"`
  1029. Pictures string `form:"pictures" json:"pictures" label:"图片"`
  1030. }
  1031. func MaterialSettleAdd(c *gin.Context) {
  1032. var form MaterialSettleAddFrom
  1033. if app.Bind(c, &form) != nil {
  1034. return
  1035. }
  1036. if len(form.Orders) == 0 {
  1037. app.ErrorMsg(c, "没有权限", nil)
  1038. return
  1039. }
  1040. adminid := c.GetInt("adminID")
  1041. suppliers := make([]final.FinalSupplier, 0)
  1042. db.GetModel(map[string]interface{}{
  1043. "adminId": adminid,
  1044. "deleted_at": 0,
  1045. }, &suppliers)
  1046. supplierids := make([]int64, 0)
  1047. for _, v := range suppliers {
  1048. supplierids = append(supplierids, v.ID)
  1049. }
  1050. orders := make([]Order, 0)
  1051. db.GetModel(map[string]interface{}{
  1052. "id in": form.Orders,
  1053. "supplier_id in": supplierids,
  1054. "state": 11,
  1055. "process_id": 0,
  1056. "settle_id": 0,
  1057. "deleted_at": 0,
  1058. }, &orders)
  1059. if len(orders) != len(form.Orders) {
  1060. app.ErrorMsg(c, "订单错误", nil)
  1061. return
  1062. }
  1063. amount := float64(0)
  1064. ids := make([]string, 0)
  1065. shop_id := orders[0].ShopId
  1066. supplier_id := orders[0].SupplierId
  1067. orderMap := make(map[int64][]Order)
  1068. for _, order := range orders {
  1069. //amount = utils.FloatAdd(amount, order.Total, 2)
  1070. ids = append(ids, db.ToString(order.ID))
  1071. if order.ShopId != shop_id {
  1072. app.ErrorMsg(c, "没有权限", nil)
  1073. return
  1074. }
  1075. if order.SupplierId != supplier_id {
  1076. app.ErrorMsg(c, "没有权限", nil)
  1077. return
  1078. }
  1079. if _, ok := orderMap[order.SiteId]; !ok {
  1080. orderMap[order.SiteId] = make([]Order, 0)
  1081. }
  1082. orderMap[order.SiteId] = append(orderMap[order.SiteId], order)
  1083. }
  1084. for _, os := range orderMap {
  1085. total := float64(0)
  1086. for _, order := range os {
  1087. total = utils.FloatAdd(total, order.Total, 2)
  1088. }
  1089. xs := total - float64(int64(total))
  1090. total = float64(int64(total))
  1091. if xs >= 0.6 {
  1092. total += 1
  1093. }
  1094. amount = utils.FloatAdd(amount, total, 2)
  1095. }
  1096. deduction, contractDeductions, punishDeductions, orderPunishDeductions := materialSettleDeduction(supplier_id, shop_id, orders)
  1097. total := utils.FloatSub(amount, deduction, 2)
  1098. id, err := db.InsertModel(db.Type(final.FinalMaterialSettle{}), map[string]interface{}{
  1099. "supplier_id": supplier_id,
  1100. "account_id": form.AccountId,
  1101. "amount": amount,
  1102. "deduction": deduction,
  1103. "total": total,
  1104. "shop_id": shop_id,
  1105. "orders": strings.Join(ids, ","),
  1106. "state": 2,
  1107. "created_id": c.GetInt("adminID"),
  1108. })
  1109. if err != nil {
  1110. app.ErrorMsg(c, err.Error(), nil)
  1111. return
  1112. }
  1113. err = db.UpdateModels(db.Type(final.FinalMaterialOrder{}), map[string]interface{}{
  1114. "id in": form.Orders,
  1115. "supplier_id": supplier_id,
  1116. "state": 11,
  1117. "process_id": 0,
  1118. "settle_id": 0,
  1119. "deleted_at": 0,
  1120. }, map[string]interface{}{
  1121. "state": 12,
  1122. "settle_id": id,
  1123. })
  1124. if err != nil {
  1125. app.ErrorMsg(c, err.Error(), nil)
  1126. return
  1127. }
  1128. _, err = db.InsertModel(db.Type(final.FinalMaterialSettleProcess{}), map[string]interface{}{
  1129. "settle_id": id,
  1130. "explain": form.Explain,
  1131. "pictures": form.Pictures,
  1132. "type": 0,
  1133. "state": 0,
  1134. "created_id": c.GetInt("adminID"),
  1135. })
  1136. if err != nil {
  1137. app.ErrorMsg(c, err.Error(), nil)
  1138. return
  1139. }
  1140. for _, deduction := range contractDeductions {
  1141. _, err = db.InsertModel(db.Type(final.FinalSupplierContractDeduction{}), map[string]interface{}{
  1142. "supplierId": supplier_id,
  1143. "contractId": deduction.ContractId,
  1144. "settleId": id,
  1145. "amount": deduction.Amount,
  1146. })
  1147. if err != nil {
  1148. app.ErrorMsg(c, err.Error(), nil)
  1149. return
  1150. }
  1151. }
  1152. for _, deduction := range punishDeductions {
  1153. _, err = db.InsertModel(db.Type(final.FinalSupplierPunishDeduction{}), map[string]interface{}{
  1154. "supplierId": supplier_id,
  1155. "punishId": deduction.PunishId,
  1156. "settleId": id,
  1157. "amount": deduction.Amount,
  1158. })
  1159. if err != nil {
  1160. app.ErrorMsg(c, err.Error(), nil)
  1161. return
  1162. }
  1163. }
  1164. for _, deduction := range orderPunishDeductions {
  1165. _, err = db.InsertModel(db.Type(final.FinalOrderPunishDeduction{}), map[string]interface{}{
  1166. "supplierId": supplier_id,
  1167. "orderId": deduction.OrderId,
  1168. "punishId": deduction.PunishId,
  1169. "settleId": id,
  1170. "amount": deduction.Amount,
  1171. })
  1172. if err != nil {
  1173. app.ErrorMsg(c, err.Error(), nil)
  1174. return
  1175. }
  1176. }
  1177. app.Success(c, nil)
  1178. }
  1179. type MaterialCartSelectItemFrom struct {
  1180. Id int64 `form:"id" json:"id" label:"ID" binding:"required"`
  1181. ItemId int64 `form:"item_id" json:"item_id" label:"项目类型"`
  1182. }
  1183. func MaterialCartSelectItem(c *gin.Context) {
  1184. var form MaterialCartSelectItemFrom
  1185. if app.Bind(c, &form) != nil {
  1186. return
  1187. }
  1188. adminId := c.GetInt("adminID")
  1189. var model final.FinalMaterialCart
  1190. db.GetModel(map[string]interface{}{
  1191. "id": form.Id,
  1192. "admin_id": adminId,
  1193. "process_id": 0,
  1194. "deleted_at": 0,
  1195. }, &model)
  1196. if model.ID == 0 {
  1197. app.ErrorMsg(c, "没有权限", nil)
  1198. return
  1199. }
  1200. var models final.FinalMaterialCart
  1201. db.GetModel(map[string]interface{}{
  1202. "id !=": model.ID,
  1203. "item_id": form.ItemId,
  1204. "admin_id": adminId,
  1205. "process_id": 0,
  1206. "mat_id": model.MatId,
  1207. "deleted_at": 0,
  1208. }, &models)
  1209. if models.ID == 0 {
  1210. err := db.UpdateModel(db.Type(model), model.ID, map[string]interface{}{
  1211. "item_id": form.ItemId,
  1212. })
  1213. if err != nil {
  1214. app.Error(c, err.Error())
  1215. return
  1216. }
  1217. } else {
  1218. err := db.UpdateModel(db.Type(model), models.ID, map[string]interface{}{
  1219. "num": utils.FloatAdd(model.Num, models.Num, 2),
  1220. "total": utils.FloatAdd(model.Total, models.Total, 2),
  1221. })
  1222. if err != nil {
  1223. app.Error(c, err.Error())
  1224. return
  1225. }
  1226. err = db.UpdateModel(db.Type(model), model.ID, map[string]interface{}{
  1227. "deleted_at": time.Now().Unix(),
  1228. })
  1229. if err != nil {
  1230. app.Error(c, err.Error())
  1231. return
  1232. }
  1233. }
  1234. app.Success(c, nil)
  1235. }
  1236. type MaterialBrandCartAddFrom struct {
  1237. BrandId int64 `form:"brandId" json:"brandId" label:"品牌" binding:"required"`
  1238. PresetsId int64 `form:"presetsId" json:"presetsId" label:"预设"`
  1239. }
  1240. func MaterialBrandCartAdd(c *gin.Context) {
  1241. var form MaterialBrandCartAddFrom
  1242. if app.Bind(c, &form) != nil {
  1243. return
  1244. }
  1245. adminId := c.GetInt("adminID")
  1246. items := make([]final.FinalMatAuxiliaryItem, 0)
  1247. db.GetModel(map[string]interface{}{
  1248. "brandId": form.BrandId,
  1249. "deleted_at": 0,
  1250. }, &items)
  1251. pitems := make([]final.FinalMatAuxiliaryPresetsItem, 0)
  1252. db.GetModel(map[string]interface{}{
  1253. "presetsId": form.PresetsId,
  1254. "deleted_at": 0,
  1255. }, &pitems)
  1256. pitemMap := make(map[int64]final.FinalMatAuxiliaryPresetsItem)
  1257. for _, v := range pitems {
  1258. pitemMap[v.ItemId] = v
  1259. }
  1260. matitemids := make([]int64, 0)
  1261. matitemMap := make(map[int64]final.FinalMatAuxiliaryItem)
  1262. for _, v := range items {
  1263. matitemids = append(matitemids, v.ItemId)
  1264. matitemMap[v.ItemId] = v
  1265. }
  1266. matitems := make([]final.FinalMatItem, 0)
  1267. db.GetModel(map[string]interface{}{
  1268. "id in": matitemids,
  1269. "deleted_at": 0,
  1270. }, &matitems)
  1271. itemss := make([]final.FinalMatAuxiliaryItem, 0)
  1272. for _, v := range matitems {
  1273. if item, ok := matitemMap[v.ID]; ok {
  1274. itemss = append([]final.FinalMatAuxiliaryItem{item}, itemss...)
  1275. }
  1276. }
  1277. var model final.FinalMaterialCart
  1278. _, err := db.BuildUpdate(model.TableName(), map[string]interface{}{
  1279. "admin_id": adminId,
  1280. "process_id": 0,
  1281. "deleted_at": 0,
  1282. }, map[string]interface{}{
  1283. "deleted_at": time.Now().Unix(),
  1284. }, model.DB())
  1285. if err != nil {
  1286. app.ErrorMsg(c, err.Error(), nil)
  1287. return
  1288. }
  1289. matids := make([]int64, 0)
  1290. for _, v := range itemss {
  1291. matids = append(matids, v.MatId)
  1292. }
  1293. mats := make([]final.FinalMat, 0)
  1294. matMap := make(map[int64]final.FinalMat)
  1295. db.GetModel(map[string]interface{}{
  1296. "id in": matids,
  1297. "deleted_at": 0,
  1298. }, &mats)
  1299. for _, v := range mats {
  1300. matMap[v.ID] = v
  1301. }
  1302. for _, v := range itemss {
  1303. num := int64(0)
  1304. if i, ok := pitemMap[v.ItemId]; ok && i.Num > 0 {
  1305. num = i.Num
  1306. }
  1307. total := utils.FloatMul(float64(num), matMap[v.MatId].Price, 2)
  1308. _, err := db.InsertModel(db.Type(model), map[string]interface{}{
  1309. "admin_id": adminId,
  1310. "process_id": 0,
  1311. "item_id": v.ItemId,
  1312. "mat_id": v.MatId,
  1313. "num": num,
  1314. "price": matMap[v.MatId].Price,
  1315. "total": total,
  1316. })
  1317. if err != nil {
  1318. app.Error(c, err.Error())
  1319. return
  1320. }
  1321. }
  1322. app.Success(c, nil)
  1323. }
  1324. type MaterialCartBatchAddFrom struct {
  1325. Carts []MaterialCartAddFrom `form:"carts" json:"carts" binding:"required"`
  1326. }
  1327. func MaterialCartBatchAdd(c *gin.Context) {
  1328. var form MaterialCartBatchAddFrom
  1329. if app.Bind(c, &form) != nil {
  1330. return
  1331. }
  1332. adminId := c.GetInt("adminID")
  1333. var model final.FinalMaterialCart
  1334. _, err := db.BuildUpdate(model.TableName(), map[string]interface{}{
  1335. "admin_id": adminId,
  1336. "process_id": 0,
  1337. "deleted_at": 0,
  1338. }, map[string]interface{}{
  1339. "deleted_at": time.Now().Unix(),
  1340. }, model.DB())
  1341. if err != nil {
  1342. app.ErrorMsg(c, err.Error(), nil)
  1343. return
  1344. }
  1345. matids := make([]int64, 0)
  1346. for _, v := range form.Carts {
  1347. matids = append(matids, v.MatId)
  1348. }
  1349. mats := make([]final.FinalMat, 0)
  1350. matMap := make(map[int64]final.FinalMat)
  1351. db.GetModel(map[string]interface{}{
  1352. "id in": matids,
  1353. "deleted_at": 0,
  1354. }, &mats)
  1355. for _, v := range mats {
  1356. matMap[v.ID] = v
  1357. }
  1358. for _, v := range form.Carts {
  1359. if v.Num <= 0 {
  1360. v.Num = 1
  1361. }
  1362. _, err := db.InsertModel(db.Type(model), map[string]interface{}{
  1363. "admin_id": adminId,
  1364. "process_id": 0,
  1365. "item_id": v.ItemId,
  1366. "mat_id": v.MatId,
  1367. "num": v.Num,
  1368. "total": utils.FloatMul(v.Num, matMap[v.MatId].Price, 2),
  1369. })
  1370. if err != nil {
  1371. app.Error(c, err.Error())
  1372. return
  1373. }
  1374. }
  1375. app.Success(c, nil)
  1376. }
  1377. type SelectMaterialAddFrom struct {
  1378. Carts []MaterialCartAddFrom `form:"carts" json:"carts" binding:"required"`
  1379. SiteId int64 `form:"site_id" json:"site_id" label:"ID" binding:"required"`
  1380. }
  1381. func SelectMaterialAdd(c *gin.Context) {
  1382. var form SelectMaterialAddFrom
  1383. if app.Bind(c, &form) != nil {
  1384. return
  1385. }
  1386. adminId := c.GetInt("adminID")
  1387. matids := make([]int64, 0)
  1388. for _, v := range form.Carts {
  1389. matids = append(matids, v.MatId)
  1390. }
  1391. mats := make([]final.FinalMat, 0)
  1392. matMap := make(map[int64]final.FinalMat)
  1393. db.GetModel(map[string]interface{}{
  1394. "id in": matids,
  1395. "deleted_at": 0,
  1396. }, &mats)
  1397. for _, v := range mats {
  1398. matMap[v.ID] = v
  1399. }
  1400. id, err := db.InsertModel(db.Type(final.FinalSelectMaterial{}), map[string]interface{}{
  1401. "site_id": form.SiteId,
  1402. "state": 0,
  1403. "created_id": adminId,
  1404. })
  1405. if err != nil {
  1406. app.Error(c, err.Error())
  1407. return
  1408. }
  1409. for _, v := range form.Carts {
  1410. if v.Num <= 0 {
  1411. v.Num = 1
  1412. }
  1413. _, err := db.InsertModel(db.Type(final.FinalSelectMaterialItem{}), map[string]interface{}{
  1414. "select_id": id,
  1415. "item_id": v.ItemId,
  1416. "mat_id": v.MatId,
  1417. })
  1418. if err != nil {
  1419. app.Error(c, err.Error())
  1420. return
  1421. }
  1422. }
  1423. app.Success(c, nil)
  1424. }
  1425. type SelectMaterialOrderCreateFrom struct {
  1426. SelectId int `form:"select_id" json:"select_id" binding:"required"`
  1427. }
  1428. func SelectMaterialOrderCreate(c *gin.Context) {
  1429. var form SelectMaterialOrderCreateFrom
  1430. if app.Bind(c, &form) != nil {
  1431. return
  1432. }
  1433. var selectMaterial final.FinalSelectMaterial
  1434. db.GetModel(map[string]interface{}{
  1435. "id": form.SelectId,
  1436. "deleted_at": 0,
  1437. }, &selectMaterial)
  1438. if selectMaterial.ID == 0 {
  1439. app.ErrorMsg(c, "选材单不存在", nil)
  1440. return
  1441. }
  1442. if selectMaterial.State != 0 {
  1443. app.ErrorMsg(c, "选材单状态错误", nil)
  1444. return
  1445. }
  1446. adminId := c.GetInt("adminID")
  1447. items, err := db.GetModelMap(db.Type(final.FinalSelectMaterialItemMobile{}), map[string]interface{}{
  1448. "select_id": selectMaterial.ID,
  1449. "deleted_at": 0,
  1450. }, nil)
  1451. if err != nil {
  1452. app.ErrorMsg(c, err.Error(), nil)
  1453. return
  1454. }
  1455. var site final.FinalSite
  1456. db.GetModel(map[string]interface{}{
  1457. "id": selectMaterial.SiteId,
  1458. "deleted_at": 0,
  1459. }, &site)
  1460. if site.ID == 0 {
  1461. app.ErrorMsg(c, "工地不存在", nil)
  1462. return
  1463. }
  1464. var settle final.FinalSettle
  1465. db.GetModel(map[string]interface{}{
  1466. "site_id": site.ID,
  1467. "deleted_at": 0,
  1468. }, &settle)
  1469. if settle.ID != 0 {
  1470. app.ErrorMsg(c, "已结算,无法下单", nil)
  1471. return
  1472. }
  1473. address := site.Address
  1474. if site.Village != " " {
  1475. address += " " + site.Village
  1476. }
  1477. if site.RoomNo != " " {
  1478. address += " " + site.RoomNo
  1479. }
  1480. cTotal := float64(0)
  1481. ctyp := int64(0)
  1482. itemMap := make(map[int64][]final.FinalMaterialOrderItem, 0)
  1483. citemMap := make(map[int64][]final.FinalMaterialOrderItem, 0)
  1484. supplierAdminMap := make(map[int64]int64)
  1485. supplierTotalMap := make(map[int64]float64)
  1486. for i, v := range items {
  1487. supplier_id, _ := db.ToInt64(v["supplier_id"])
  1488. supplier_admin_id, _ := db.ToInt64(v["supplier_admin_id"])
  1489. supplierAdminMap[supplier_id] = supplier_admin_id
  1490. id, _ := db.ToInt64(v["id"])
  1491. typ, _ := db.ToInt64(v["type"])
  1492. mat_id, _ := db.ToInt64(v["mat_id"])
  1493. num, _ := db.ToFloat64(v["num"])
  1494. remark := db.ToString(v["remark"])
  1495. price, _ := db.ToFloat64(v["mat_price"])
  1496. total := utils.FloatMul(price, num, 2)
  1497. item_id, _ := db.ToInt64(v["item_id"])
  1498. is_custom, _ := db.ToInt64(v["is_custom"])
  1499. if num <= 0 {
  1500. continue
  1501. }
  1502. if is_custom == 0 {
  1503. is := make([]final.FinalMaterialOrderItem, 0)
  1504. if s, ok := itemMap[supplier_id]; ok {
  1505. is = s
  1506. }
  1507. is = append(is, final.FinalMaterialOrderItem{
  1508. ID: id,
  1509. ItemId: item_id,
  1510. MatId: mat_id,
  1511. Price: price,
  1512. Num: num,
  1513. Remark: remark,
  1514. Total: total,
  1515. })
  1516. itemMap[supplier_id] = is
  1517. } else {
  1518. cs := make([]final.FinalMaterialOrderItem, 0)
  1519. if s, ok := citemMap[supplier_id]; ok {
  1520. cs = s
  1521. }
  1522. cs = append(cs, final.FinalMaterialOrderItem{
  1523. ID: id,
  1524. ItemId: item_id,
  1525. MatId: mat_id,
  1526. Price: price,
  1527. Num: num,
  1528. Remark: remark,
  1529. Total: total,
  1530. })
  1531. citemMap[supplier_id] = cs
  1532. }
  1533. if i == 0 {
  1534. ctyp = typ
  1535. } else {
  1536. if ctyp != typ {
  1537. app.ErrorMsg(c, "下单类型错误", nil)
  1538. return
  1539. }
  1540. }
  1541. if _, ok := supplierTotalMap[supplier_id]; !ok {
  1542. supplierTotalMap[supplier_id] = 0
  1543. }
  1544. supplierTotalMap[supplier_id] = utils.FloatAdd(supplierTotalMap[supplier_id], total, 2)
  1545. cTotal = utils.FloatAdd(cTotal, total, 2)
  1546. }
  1547. supplierids := make([]int64, 0)
  1548. for id, _ := range supplierAdminMap {
  1549. supplierids = append(supplierids, id)
  1550. }
  1551. suppliers, err := db.GetModelMap(db.Type(final.FinalSupplierPrepaymentStatist{}), map[string]interface{}{
  1552. "id in": supplierids,
  1553. "prepayment": 1,
  1554. "deleted_at": 0,
  1555. }, nil)
  1556. if err != nil {
  1557. app.ErrorMsg(c, err.Error(), nil)
  1558. return
  1559. }
  1560. for _, v := range suppliers {
  1561. id, _ := db.ToInt64(v["id"])
  1562. name := db.ToString(v["name"])
  1563. warning_amount, _ := db.ToFloat64(v["warning_amount"])
  1564. notice_ids := db.ToString(v["notice_ids"])
  1565. total, _ := db.ToFloat64(v["total"])
  1566. noticeIds := make([]int64, 0)
  1567. for _, i := range strings.Split(notice_ids, ",") {
  1568. if i != "" {
  1569. if n, ok := db.ToInt64(i); ok {
  1570. noticeIds = append(noticeIds, n)
  1571. }
  1572. }
  1573. }
  1574. if supplierTotalMap[id] > total {
  1575. for _, i := range noticeIds {
  1576. err := final.SendMaterialMessage(int(i), "", 0, address, "材料商"+name+"预付款金额不足,下单失败")
  1577. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  1578. }
  1579. app.ErrorMsg(c, "材料商"+name+"预付款金额不足,下单失败", nil)
  1580. return
  1581. }
  1582. if total-supplierTotalMap[id] <= warning_amount {
  1583. for _, i := range noticeIds {
  1584. err := final.SendMaterialMessage(int(i), "", 0, address, "材料商"+name+"预付款金额仅剩"+db.ToString(total-supplierTotalMap[id]))
  1585. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  1586. }
  1587. }
  1588. }
  1589. orderNo := Generate(time.Now())
  1590. n := 0
  1591. supplierOrderMap := make(map[int64]final.FinalMaterialOrder)
  1592. customOrders := make([]final.FinalMaterialOrder, 0)
  1593. for is_custom, itemmap := range []map[int64][]final.FinalMaterialOrderItem{itemMap, citemMap} {
  1594. for supplier_id, items := range itemmap {
  1595. n++
  1596. order_no := orderNo
  1597. if len(itemMap)+len(citemMap) > 1 {
  1598. order_no = order_no + "-" + db.ToString(n)
  1599. }
  1600. total := float64(0)
  1601. for _, v := range items {
  1602. total = utils.FloatAdd(total, v.Total, 2)
  1603. }
  1604. xs := total - float64(int64(total))
  1605. total = float64(int64(total))
  1606. if xs >= 0.6 {
  1607. total += 1
  1608. }
  1609. datas := map[string]interface{}{
  1610. "order_no": order_no,
  1611. "site_id": selectMaterial.SiteId,
  1612. "type": ctyp,
  1613. "is_custom": is_custom,
  1614. "type_id": 0,
  1615. "supplier_id": supplier_id,
  1616. "total": total,
  1617. "state": 0,
  1618. "take_time": time.Now().Unix(),
  1619. "created_id": selectMaterial.CreatedId,
  1620. }
  1621. if is_custom == 1 {
  1622. datas["state"] = 8
  1623. }
  1624. orderid, err := db.InsertModel(db.Type(final.FinalMaterialOrder{}), datas)
  1625. if err != nil {
  1626. app.ErrorMsg(c, err.Error(), nil)
  1627. return
  1628. }
  1629. if err != nil {
  1630. app.ErrorMsg(c, err.Error(), nil)
  1631. return
  1632. }
  1633. if is_custom == 0 {
  1634. supplierOrderMap[supplier_id] = final.FinalMaterialOrder{
  1635. ID: orderid,
  1636. OrderNo: order_no,
  1637. }
  1638. } else {
  1639. customOrders = append(customOrders, final.FinalMaterialOrder{
  1640. ID: orderid,
  1641. OrderNo: order_no,
  1642. })
  1643. }
  1644. for _, v := range items {
  1645. _, err := db.InsertModel(db.Type(final.FinalMaterialOrderItem{}), map[string]interface{}{
  1646. "item_id": v.ItemId,
  1647. "order_id": orderid,
  1648. "mat_id": v.MatId,
  1649. "price": v.Price,
  1650. "num": v.Num,
  1651. "total": v.Total,
  1652. "remark": v.Remark,
  1653. })
  1654. if err != nil {
  1655. app.ErrorMsg(c, err.Error(), nil)
  1656. return
  1657. }
  1658. }
  1659. _, err = db.InsertModel(db.Type(final.FinalMaterialOrderProcess{}), map[string]interface{}{
  1660. "order_id": orderid,
  1661. "type": 0,
  1662. "created_id": adminId,
  1663. })
  1664. if err != nil {
  1665. app.ErrorMsg(c, err.Error(), nil)
  1666. return
  1667. }
  1668. }
  1669. }
  1670. err = db.UpdateModel(db.Type(final.FinalSelectMaterial{}), selectMaterial.ID, map[string]interface{}{
  1671. "check_id": adminId,
  1672. "state": 1,
  1673. })
  1674. if err != nil {
  1675. app.ErrorMsg(c, err.Error(), nil)
  1676. return
  1677. }
  1678. for s, o := range supplierOrderMap {
  1679. err := final.SendMaterialMessage(int(supplierAdminMap[s]), o.OrderNo, o.ID, address, "订单已下单,请安排备货")
  1680. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  1681. }
  1682. for _, o := range customOrders {
  1683. err := final.SendMaterialMessage(int(site.ManagerId), o.OrderNo, o.ID, address, "定制品已下单,请通知测量")
  1684. logger.Sugar.Infof("SendMaterialMessage, err: %v", err)
  1685. }
  1686. app.Success(c, nil)
  1687. }
  1688. type MaterialOrderCartBatchAddFrom struct {
  1689. OrderId int64 `form:"orderId" json:"orderId" binding:"required"`
  1690. }
  1691. func MaterialOrderCartBatchAdd(c *gin.Context) {
  1692. var form MaterialOrderCartBatchAddFrom
  1693. if app.Bind(c, &form) != nil {
  1694. return
  1695. }
  1696. adminId := c.GetInt("adminID")
  1697. var model final.FinalMaterialCart
  1698. _, err := db.BuildUpdate(model.TableName(), map[string]interface{}{
  1699. "admin_id": adminId,
  1700. "process_id": 0,
  1701. "deleted_at": 0,
  1702. }, map[string]interface{}{
  1703. "deleted_at": time.Now().Unix(),
  1704. }, model.DB())
  1705. if err != nil {
  1706. app.ErrorMsg(c, err.Error(), nil)
  1707. return
  1708. }
  1709. items := make([]final.FinalMaterialOrderItem, 0)
  1710. db.GetModel(map[string]interface{}{
  1711. "order_id": form.OrderId,
  1712. "deleted_at": 0,
  1713. }, &items)
  1714. matids := make([]int64, 0)
  1715. for _, v := range items {
  1716. matids = append(matids, v.MatId)
  1717. }
  1718. mats := make([]final.FinalMat, 0)
  1719. matMap := make(map[int64]final.FinalMat)
  1720. db.GetModel(map[string]interface{}{
  1721. "id in": matids,
  1722. "deleted_at": 0,
  1723. }, &mats)
  1724. for _, v := range mats {
  1725. matMap[v.ID] = v
  1726. }
  1727. for _, v := range items {
  1728. if v.Num <= 0 {
  1729. v.Num = 1
  1730. }
  1731. _, err := db.InsertModel(db.Type(model), map[string]interface{}{
  1732. "admin_id": adminId,
  1733. "process_id": 0,
  1734. "item_id": v.ItemId,
  1735. "mat_id": v.MatId,
  1736. "price": matMap[v.MatId].Price,
  1737. "num": v.Num,
  1738. "total": utils.FloatMul(v.Num, matMap[v.MatId].Price, 2),
  1739. })
  1740. if err != nil {
  1741. app.Error(c, err.Error())
  1742. return
  1743. }
  1744. }
  1745. app.Success(c, nil)
  1746. }
  1747. func QuoteOrderInfo(c *gin.Context) {
  1748. id := utils.ToInt(c.Param("id"))
  1749. if id <= 0 {
  1750. app.ErrorMsg(c, "id must be a number", nil)
  1751. return
  1752. }
  1753. var model budget.Order
  1754. db.GetModel(map[string]interface{}{"id": id}, &model)
  1755. if model.ID == 0 {
  1756. app.ErrorMsg(c, "订单不存在", nil)
  1757. return
  1758. }
  1759. order, err := budgetService.LoadOrder(model)
  1760. if err != nil {
  1761. app.ErrorMsg(c, err.Error(), nil)
  1762. return
  1763. }
  1764. context := budgetService.NewContext(order, c)
  1765. err = context.Eval()
  1766. logger.Sugar.Infof("err: %v", err)
  1767. if model.State == 0 {
  1768. err = order.Save(context)
  1769. logger.Sugar.Infof("err: %v", err)
  1770. }
  1771. model.Content = make([]byte, 0)
  1772. app.Success(c, gin.H{
  1773. "name": order.Models[budgetService.Quote][order.Form.ID].GetName(),
  1774. "order": model,
  1775. "result": order.ToMap(false),
  1776. })
  1777. }
  1778. type MaterialLeaderCheckFrom struct {
  1779. Orders []int `form:"orders" json:"orders" label:"订单" binding:"required"`
  1780. Signature string `form:"signature" json:"signature" label:"签名" binding:"required"`
  1781. Explain string `form:"explain" json:"explain" label:"说明"`
  1782. Pictures string `form:"pictures" json:"pictures" label:"图片"`
  1783. }
  1784. func MaterialLeaderCheck(c *gin.Context) {
  1785. var form MaterialLeaderCheckFrom
  1786. if app.Bind(c, &form) != nil {
  1787. return
  1788. }
  1789. if len(form.Orders) == 0 {
  1790. app.ErrorMsg(c, "没有权限", nil)
  1791. return
  1792. }
  1793. adminid := c.GetInt("adminID")
  1794. orders := make([]final.FinalMaterialOrder, 0)
  1795. db.GetModel(map[string]interface{}{
  1796. "id in": form.Orders,
  1797. "state": 7,
  1798. "process_id": 0,
  1799. "deleted_at": 0,
  1800. }, &orders)
  1801. if len(orders) != len(form.Orders) {
  1802. app.ErrorMsg(c, "订单错误", nil)
  1803. return
  1804. }
  1805. err := db.UpdateModels(db.Type(final.FinalMaterialOrder{}), map[string]interface{}{
  1806. "id in": form.Orders,
  1807. "state": 7,
  1808. "process_id": 0,
  1809. "deleted_at": 0,
  1810. }, map[string]interface{}{
  1811. "state": 11,
  1812. })
  1813. if err != nil {
  1814. app.ErrorMsg(c, err.Error(), nil)
  1815. return
  1816. }
  1817. for _, order := range orders {
  1818. _, err = db.InsertModel(db.Type(final.FinalMaterialOrderProcess{}), map[string]interface{}{
  1819. "order_id": order.ID,
  1820. "type": 13,
  1821. "explain": form.Explain,
  1822. "pictures": form.Pictures,
  1823. "signature": form.Signature,
  1824. "created_id": adminid,
  1825. })
  1826. if err != nil {
  1827. app.ErrorMsg(c, err.Error(), nil)
  1828. return
  1829. }
  1830. }
  1831. app.Success(c, nil)
  1832. }
  1833. func MaterialOrderSatic(c *gin.Context) {
  1834. adminID := c.GetInt("adminID")
  1835. orderModel := final.FinalMaterialOrderSupplier{}
  1836. orderType := db.Type(orderModel)
  1837. deleted := orderModel.DeletedField()
  1838. s := db.ModelQuery(orderType, map[string]interface{}{}, false)
  1839. if deleted != "" {
  1840. s.Where = append(s.Where, fmt.Sprintf("`%s`.`%s` = 0", orderModel.TableName(), deleted))
  1841. }
  1842. if !orderModel.ListPrivilege(c, map[string]interface{}{}, &s) {
  1843. app.ErrorMsg(c, "没有权限", nil)
  1844. return
  1845. }
  1846. orderCount, err := db.GetCount(s, orderModel.DB())
  1847. if err != nil {
  1848. app.ErrorMsg(c, err.Error(), nil)
  1849. return
  1850. }
  1851. where := s.Where
  1852. adminIDParam := s.Param(adminID)
  1853. s.Where = where
  1854. dclWhere := fmt.Sprintf("(`finalsite`.`manager_id` = %s AND ((`%s`.`state` in (8,1,3,4,6) AND `%s`.`process_id` = 0) OR (`process`.`type` = 6 AND `process`.`check_at2` = 0) OR (`process`.`type` = 14 AND `process`.`check_at` = 0)))", adminIDParam, orderModel.TableName(), orderModel.TableName())
  1855. dclWhere += fmt.Sprintf(" OR (`supplier`.`adminId` = %s AND ((`%s`.`state` in (9,0,2,5,11) AND `%s`.`process_id` = 0) OR (`process`.`type` = 6 AND `process`.`check_at3` = 0)))", adminIDParam, orderModel.TableName(), orderModel.TableName())
  1856. dclWhere += fmt.Sprintf(" OR (`finalsite`.`project_leader_id` = %s AND `%s`.`state` = 7 AND `%s`.`process_id` = 0)", adminIDParam, orderModel.TableName(), orderModel.TableName())
  1857. dclWhere += fmt.Sprintf(" OR (`%s`.`created_id` = %s AND `process`.`type` = 7 AND `process`.`check_at2` = 0)", orderModel.TableName(), adminIDParam)
  1858. if admin.CheckAuth([]string{"final:verify:audit"}, adminID) {
  1859. dclWhere += " OR (`process`.`type` = 7 AND `process`.`check_at` = 0) OR (`process`.`type` = 12 AND `process`.`check_at` = 0)"
  1860. }
  1861. s.Where = append(where, fmt.Sprintf("(%s)", dclWhere))
  1862. dclCount, err := db.GetCount(s, orderModel.DB())
  1863. if err != nil {
  1864. app.ErrorMsg(c, err.Error(), nil)
  1865. return
  1866. }
  1867. s.Where = append(where, fmt.Sprintf("`%s`.`process_id` != %s", orderModel.TableName(), s.Param(0)))
  1868. wheres := fmt.Sprintf("(`finalsite`.`manager_id` = %s AND `process`.`type` = 6 AND `process`.`check_at2` = 0) OR (`supplier`.`adminId` = %s AND `process`.`type` = 6 AND `process`.`check_at3` = 0) OR (`%s`.`created_id` = %s AND `process`.`type` = 7 AND `process`.`check_at2` = 0)", adminIDParam, adminIDParam, orderModel.TableName(), adminIDParam)
  1869. if admin.CheckAuth([]string{"final:verify:audit"}, adminID) {
  1870. wheres += " OR (`process`.`type` = 7 AND `process`.`check_at` = 0) OR (`process`.`type` = 12 AND `process`.`check_at` = 0)"
  1871. }
  1872. s.Where = append(s.Where, "("+wheres+")")
  1873. dshCount, err := db.GetCount(s, orderModel.DB())
  1874. if err != nil {
  1875. app.ErrorMsg(c, err.Error(), nil)
  1876. return
  1877. }
  1878. stateConsts := []int64{}
  1879. for i := 0; i <= 12; i++ {
  1880. s.Where = append(where, fmt.Sprintf("`%s`.`state` = %s", orderModel.TableName(), s.Param(i)))
  1881. count, err := db.GetCount(s, orderModel.DB())
  1882. if err != nil {
  1883. app.ErrorMsg(c, err.Error(), nil)
  1884. return
  1885. }
  1886. stateConsts = append(stateConsts, count)
  1887. }
  1888. app.Success(c, gin.H{
  1889. "orderCount": orderCount,
  1890. "dclCount": dclCount,
  1891. "dshCount": dshCount,
  1892. "stateConsts": stateConsts,
  1893. })
  1894. }
  1895. func FinalMaterialSettlePaymentExport(c *gin.Context) {
  1896. id := utils.ToInt(c.Param("id"))
  1897. if id <= 0 {
  1898. app.ErrorMsg(c, "id must be a number", nil)
  1899. return
  1900. }
  1901. type FinalMaterialSettle struct {
  1902. ID int64 `json:"id" prop:"add:false"`
  1903. ShopName string `json:"shop_name" prop:"select:shop.shop_name"`
  1904. CreatedAt int64 `json:"created_at" prop:"add:false"`
  1905. AccountName string `json:"account_name" prop:"select:account.account_name"`
  1906. AccountBank string `json:"account_bank" prop:"select:account.account_bank"`
  1907. AccountNo string `json:"account_no" prop:"select:account.account_no"`
  1908. SupplierName string `json:"supplier_name" type:"string" prop:"select:supplier.name" search:"like"`
  1909. Total float64 `json:"total" label:"合计金额" type:"float" prop:"add:false" search:"="`
  1910. final.FinalMaterialSettleMobile
  1911. }
  1912. var model FinalMaterialSettle
  1913. db.GetModel(map[string]interface{}{"id": id}, &model)
  1914. if model.ID == 0 {
  1915. app.ErrorMsg(c, "结算不存在", nil)
  1916. return
  1917. }
  1918. template, err := excelize.OpenFile("fkspdTemplate.xlsx")
  1919. //template, err := xlsx.OpenFile("fkspdTemplate.xlsx")
  1920. if err != nil {
  1921. app.ErrorMsg(c, "系统错误", nil)
  1922. return
  1923. }
  1924. for _, sheet := range template.GetSheetList() {
  1925. template.SetCellValue(sheet, "B3", model.ShopName)
  1926. template.SetCellValue(sheet, "F3", time.Unix(model.CreatedAt, 0).Format("2006.01.02"))
  1927. template.SetCellValue(sheet, "B4", model.AccountName)
  1928. template.SetCellValue(sheet, "B5", model.AccountBank)
  1929. template.SetCellValue(sheet, "E5", model.AccountNo)
  1930. template.SetCellValue(sheet, "B6", model.SupplierName+"(材料款)")
  1931. template.SetCellValue(sheet, "B8", model.Total)
  1932. /*cell, err := sheet.Cell(2, 1)
  1933. if err != nil {
  1934. app.ErrorMsg(c, "系统错误", nil)
  1935. return
  1936. }
  1937. cell.SetString(model.ShopName)
  1938. cell, err = sheet.Cell(2, 5)
  1939. if err != nil {
  1940. app.ErrorMsg(c, "系统错误", nil)
  1941. return
  1942. }
  1943. cell.SetString(time.Unix(model.CreatedAt, 0).Format("2006.01.02"))
  1944. cell, err = sheet.Cell(3, 1)
  1945. if err != nil {
  1946. app.ErrorMsg(c, "系统错误", nil)
  1947. return
  1948. }
  1949. cell.SetString(model.AccountName)
  1950. cell, err = sheet.Cell(4, 1)
  1951. if err != nil {
  1952. app.ErrorMsg(c, "系统错误", nil)
  1953. return
  1954. }
  1955. cell.SetString(model.AccountBank)
  1956. cell, err = sheet.Cell(4, 4)
  1957. if err != nil {
  1958. app.ErrorMsg(c, "系统错误", nil)
  1959. return
  1960. }
  1961. cell.SetString(model.AccountNo)
  1962. cell, err = sheet.Cell(5, 1)
  1963. if err != nil {
  1964. app.ErrorMsg(c, "系统错误", nil)
  1965. return
  1966. }
  1967. cell.SetString(model.SupplierName + "(材料款)")
  1968. cell, err = sheet.Cell(7, 1)
  1969. if err != nil {
  1970. app.ErrorMsg(c, "系统错误", nil)
  1971. return
  1972. }
  1973. cell.SetFloat(model.Total)*/
  1974. }
  1975. exportFileName := utils.ToStr(time.Now().UnixNano()) + ".xlsx"
  1976. b, err := template.WriteToBuffer()
  1977. if err != nil {
  1978. app.ErrorMsg(c, "系统错误", nil)
  1979. return
  1980. }
  1981. f, err := os.Create(config.Cfg.App.ExportPath + exportFileName)
  1982. if err != nil {
  1983. app.ErrorMsg(c, "系统错误", nil)
  1984. return
  1985. }
  1986. defer f.Close()
  1987. _, _ = b.WriteTo(f)
  1988. /*if err := template.Save(config.Cfg.App.ExportPath + exportFileName); err != nil {
  1989. app.ErrorMsg(c, "系统错误", nil)
  1990. return
  1991. }*/
  1992. app.Success(c, gin.H{"path": "export/" + exportFileName, "filename": exportFileName})
  1993. }