unit.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //go:generate reform --gofmt=false .
  2. package asuModels
  3. import (
  4. "database/sql"
  5. "fmt"
  6. "github.com/xaionaro-go/extime"
  7. "html/template"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. //reform:unit
  14. type Unit struct {
  15. Id int `reform:"id" view:"readonly"`
  16. OrgInn string `reform:"OrgInn" view:"readonly"`
  17. Name *string `reform:"Name" view:"readonly"`
  18. ParentId *int `reform:"ParentId" view:"readonly"`
  19. LevelIdx int `reform:"LevelIdx" view:"readonly"`
  20. IsHidden int `reform:"IsHidden" view:"readonly"`
  21. OKVED *string `reform:"OKVED" view:"readonly"`
  22. BriefName *string `reform:"BriefName" view:"readonly"`
  23. CreateOrderNo *string `reform:"CreateOrderNo" view:"readonly"`
  24. CreateOrderDate *extime.Time `reform:"CreateOrderDate" view:"readonly"`
  25. CloseOrderNo *string `reform:"CloseOrderNo" view:"readonly"`
  26. CloseOrderDate *extime.Time `reform:"CloseOrderDate" view:"readonly"`
  27. ChiefName *string `reform:"ChiefName" view:"readonly"`
  28. PersNumber *int `reform:"PersNumber" view:"readonly"`
  29. Code string `reform:"Code" view:"readonly"`
  30. SortNumber *int `reform:"SortNumber" view:"readonly"`
  31. ChiefTabN *string `reform:"ChiefTabN" view:"readonly"`
  32. children []*Unit `reform:"-"`
  33. childrenReady bool `reform:"-"`
  34. formulars Formulars `reform:"-"`
  35. formularsReady bool `reform:"-"`
  36. isActive bool `reform:"-"`
  37. isActiveReady bool `reform:"-"`
  38. }
  39. func (u *Unit) AfterFind() error {
  40. if u.Name != nil {
  41. *u.Name = strings.Trim(*u.Name, " ")
  42. }
  43. if u.BriefName != nil {
  44. *u.BriefName = strings.Trim(*u.BriefName, " ")
  45. }
  46. return nil
  47. }
  48. func (sql Unit) ActiveOnly() *UnitScope {
  49. return sql.Scope().ActiveOnly()
  50. }
  51. func (sql *UnitScope) ActiveOnly() *UnitScope {
  52. return sql.LatestOnly(time.Duration(0))
  53. }
  54. func (sql Unit) LatestOnly(howLong time.Duration) *UnitScope {
  55. return sql.Scope().LatestOnly(howLong)
  56. }
  57. func (sql *UnitScope) LatestOnly(howLong time.Duration) *UnitScope {
  58. ts := time.Now().Add(howLong)
  59. cond := fmt.Sprintf("((CreateOrderDate IS NULL OR CreateOrderDate < NOW()) AND (CloseOrderDate IS NULL OR DATE_ADD(CloseOrderDate, INTERVAL 1 DAY) > '%v'))", extime.Time(ts))
  60. return sql.Where(cond + " OR (Id IN (SELECT ParentId FROM unit WHERE " + cond + "))")
  61. }
  62. func (sql Unit) ConsiderPersNumbers() *UnitScope {
  63. return sql.Scope().ConsiderPersNumbers()
  64. }
  65. func (sql *UnitScope) ConsiderPersNumbers() *UnitScope {
  66. return sql.Group("PersNumber").Order("CreateOrderDate", "DESC")
  67. }
  68. func (sql Unit) ConsiderUniqueCodes() *UnitScope {
  69. return sql.Scope().ConsiderUniqueCodes()
  70. }
  71. func (sql *UnitScope) ConsiderUniqueCodes() *UnitScope {
  72. return sql.Group("Code").Order("id", "DESC")
  73. }
  74. func (sql Unit) RealOnly() *UnitScope {
  75. return sql.Scope().RealOnly()
  76. }
  77. func (sql *UnitScope) RealOnly() *UnitScope {
  78. return sql.Where("LENGTH(Code) = 6")
  79. }
  80. func (sql Unit) UnhiddenOnly() *UnitScope {
  81. return sql.Scope().UnhiddenOnly()
  82. }
  83. func (sql *UnitScope) UnhiddenOnly() *UnitScope {
  84. return sql.Where("IsHidden=1")
  85. }
  86. func (sql Unit) NonEmptyOnly() *UnitScope {
  87. return sql.Scope().UnhiddenOnly()
  88. }
  89. func (sql *UnitScope) NonEmptyOnly() *UnitScope {
  90. return sql.Where("Id IN (SELECT * FROM formular WHERE (StartDate IS NULL OR StartDate < NOW()) AND (EndDate IS NULL OR EndDate+24*3600 > NOW()))")
  91. }
  92. // TODO: Remove this "VIEW" from this model
  93. func (u Unit) View_readTag(fieldName string, parent interface{}, args []interface{}) template.HTML {
  94. if u.Id == 0 {
  95. return template.HTML(fmt.Sprintf(`Не назначено`))
  96. }
  97. name := ""
  98. if u.BriefName != nil {
  99. name = *u.BriefName
  100. }
  101. if u.Name != nil {
  102. name += " (" + *u.Name + ")"
  103. }
  104. return template.HTML(fmt.Sprintf(`<a href="/asu/unitsByID/%v?fullscreen=true">%v — %v</a>`, u.Id, u.Code, name))
  105. }
  106. func (unit Unit) IsChildrenReady() bool {
  107. return unit.childrenReady
  108. }
  109. type Units []Unit
  110. type UnitPtrs []*Unit
  111. func (units Units) ToPersNumberMap() map[int]*Unit {
  112. unitMap := map[int]*Unit{}
  113. for idx, unit := range units {
  114. if unit.PersNumber == nil {
  115. continue
  116. }
  117. unitMap[*unit.PersNumber] = &units[idx]
  118. }
  119. return unitMap
  120. }
  121. func (units Units) ToMap() map[int]*Unit {
  122. unitMap := map[int]*Unit{}
  123. for idx, unit := range units {
  124. unitMap[unit.Id] = &units[idx]
  125. }
  126. return unitMap
  127. }
  128. func (units Units) calculateTree(strict bool) {
  129. unitMap := units.ToMap()
  130. for idx := range units {
  131. unit := &units[idx]
  132. if unit.ParentId == nil {
  133. continue
  134. }
  135. parent := unitMap[*unit.ParentId]
  136. if parent == nil {
  137. if strict {
  138. panic(fmt.Sprintf("Not full units list. len(units) == %v; *unit.ParentId == %v", units, *unit.ParentId))
  139. }
  140. continue
  141. }
  142. parent.children = append(parent.children, unit)
  143. }
  144. for idx := range units {
  145. units[idx].childrenReady = true
  146. }
  147. }
  148. func (units Units) CalculateTree() Units {
  149. units.calculateTree(true)
  150. return units
  151. }
  152. func (unit *Unit) DoRecursive(f func(*Unit, interface{}) bool, arg interface{}) bool {
  153. if !f(unit, arg) {
  154. return false
  155. }
  156. for _, child := range unit.GetChildrenPtrs() {
  157. if !child.DoRecursive(f, arg) {
  158. return false
  159. }
  160. }
  161. return true
  162. }
  163. func (units Units) DoRecursive(f func(*Unit, interface{}) bool, arg interface{}) bool {
  164. return units.ToPtrSlice().DoRecursive(f, arg)
  165. }
  166. func (units UnitPtrs) DoRecursive(f func(*Unit, interface{}) bool, arg interface{}) bool {
  167. for _, unit := range units {
  168. unit.DoRecursive(f, arg)
  169. }
  170. return true
  171. }
  172. func (units Units) ToPtrSlice() (result UnitPtrs) {
  173. for idx := range units {
  174. result = append(result, &units[idx])
  175. }
  176. return
  177. }
  178. func (units Units) GetRecursive() (result UnitPtrs) {
  179. units.DoRecursive(func(unit *Unit, arg interface{}) bool {
  180. result = append(result, unit)
  181. return true
  182. }, nil)
  183. return
  184. }
  185. func (unit Unit) GetRecursive() (result UnitPtrs) {
  186. unit.DoRecursive(func(unit *Unit, arg interface{}) bool {
  187. result = append(result, unit)
  188. return true
  189. }, nil)
  190. return
  191. }
  192. func (u Unit) GetChildrenPtrs() []*Unit {
  193. if !u.childrenReady {
  194. panic("unit is not ready for method GetChildrenPtrs: it's required to call CalculateTree method, first")
  195. }
  196. return u.children
  197. }
  198. func (u *Unit) PrepareFormulars() *Unit {
  199. var err error
  200. if u.PersNumber == nil {
  201. u.formulars, err = FormularSQL.Select(Formular{UnitId: u.Id})
  202. } else {
  203. u.formulars, err = FormularSQL.Select(Formular{PersNumber: u.PersNumber})
  204. for idx := range u.formulars {
  205. u.formulars[idx].UnitId = u.Id
  206. }
  207. }
  208. if err != nil && err != sql.ErrNoRows {
  209. panic(err)
  210. }
  211. u.formularsReady = true
  212. return u
  213. }
  214. func (u Unit) GetFormularsPtr() *Formulars {
  215. return &u.formulars
  216. }
  217. func (u Unit) IsFormularsReady() bool {
  218. return u.formularsReady
  219. }
  220. func (u Unit) GetFormulars() Formulars {
  221. if !u.formularsReady {
  222. panic("unit is not ready for method GetFormulars: it's required to call PrepareFormulars method, first")
  223. }
  224. return u.formulars
  225. }
  226. func (units Units) PrepareFormulars(activeOnly, ppsOnly bool, additionalCondition ...interface{}) Units {
  227. if len(units) == 0 {
  228. return units
  229. }
  230. ids := units.GetUnitIds()
  231. nums := units.GetPersNumbers()
  232. scope := FormularSQL.Scope()
  233. if activeOnly {
  234. scope = scope.ActiveOnly()
  235. }
  236. if ppsOnly {
  237. scope = scope.PPSOnly()
  238. }
  239. if len(nums) == 0 && len(ids) == 0 {
  240. return units
  241. }
  242. if len(nums) > 0 {
  243. scope = scope.Where("PersNumber IN (?) OR OrgDiv IN (?)", nums, ids)
  244. } else {
  245. scope = scope.Where("OrgDiv IN (?)", ids)
  246. }
  247. if len(additionalCondition) > 0 {
  248. scope = scope.Where(additionalCondition[0].(string), additionalCondition[1:]...)
  249. }
  250. formulars, err := scope.Select()
  251. if err != nil && err != sql.ErrNoRows {
  252. panic(err)
  253. }
  254. unitsMap := units.ToMap()
  255. unitsPMap := units.ToPersNumberMap()
  256. for _, formular := range formulars {
  257. if formular.PersNumber == nil {
  258. (*unitsMap[formular.UnitId]).formulars = append((*unitsMap[formular.UnitId]).formulars, formular)
  259. continue
  260. }
  261. unitPtr := unitsPMap[*formular.PersNumber]
  262. formular.UnitId = (*unitPtr).Id
  263. (*unitPtr).formulars = append((*unitPtr).formulars, formular)
  264. }
  265. for idx := range units {
  266. units[idx].formularsReady = true
  267. }
  268. return units
  269. }
  270. func (units Units) GetFormulars() (formulars Formulars) {
  271. for _, unit := range units {
  272. formulars = append(formulars, unit.GetFormulars()...)
  273. }
  274. return
  275. }
  276. func (u *Unit) PrepareIsActive() *Unit {
  277. now := extime.Now()
  278. startIsGood := false
  279. endIsGood := false
  280. if u.CreateOrderDate != nil {
  281. startIsGood = u.CreateOrderDate.UnixNano() <= now.UnixNano()
  282. }
  283. if u.CloseOrderDate == nil {
  284. endIsGood = true
  285. } else {
  286. endIsGood = u.CloseOrderDate.UnixNano()+24*3600*1000*1000*1000 >= now.UnixNano()
  287. }
  288. u.isActive = startIsGood && endIsGood
  289. return u
  290. }
  291. func (u Unit) IsActive() bool {
  292. if !u.isActiveReady {
  293. panic("unit is not ready for method IsActive: it's required to call PrepareIsActive method, first")
  294. }
  295. return u.isActive
  296. }
  297. func (u *Unit) prepareChildrenTree(recursive bool) *Unit {
  298. if u.childrenReady {
  299. return u
  300. }
  301. children, err := UnitSQL.Select(Unit{ParentId: &u.Id})
  302. if err == sql.ErrNoRows {
  303. u.childrenReady = true
  304. return u
  305. }
  306. if err != nil {
  307. panic(err)
  308. }
  309. for idx := range children {
  310. child := &children[idx]
  311. if recursive {
  312. child.PrepareChildrenTree()
  313. }
  314. u.children = append(u.children, child)
  315. }
  316. u.childrenReady = true
  317. return u
  318. }
  319. func (u *Unit) PrepareChildrenTree() *Unit {
  320. return u.prepareChildrenTree(true)
  321. }
  322. func (u *Unit) PrepareChildren() *Unit {
  323. return u.prepareChildrenTree(false)
  324. }
  325. func (units Units) PrepareChildrenTree() Units {
  326. for idx := range units {
  327. units[idx].PrepareChildrenTree()
  328. }
  329. return units
  330. }
  331. func (units Units) PrepareChildren() Units {
  332. for idx := range units {
  333. units[idx].PrepareChildren()
  334. }
  335. return units
  336. }
  337. func GetUnitsHeadedBy(empGUID int) (units Units) {
  338. var formulars Formulars
  339. trueValue := true
  340. formulars, err := FormularSQL.ActiveOnly().Select(Formular{EmpGUID: empGUID, IsHead: &trueValue})
  341. if err != nil {
  342. panic(err)
  343. }
  344. for _, formular := range formulars {
  345. if !formular.PrepareIsActive().IsActive() {
  346. continue
  347. }
  348. formular.PrepareUnit()
  349. unit := formular.GetUnit()
  350. unit.PrepareChildrenTree()
  351. units = append(units, unit)
  352. }
  353. return
  354. }
  355. func (units Units) GetPersNumbers() (persNumbers []int) {
  356. for _, unit := range units {
  357. if unit.PersNumber == nil {
  358. continue
  359. }
  360. persNumbers = append(persNumbers, *unit.PersNumber)
  361. }
  362. return
  363. }
  364. func (units Units) GetUnitIds() []int {
  365. return units.ToPtrSlice().GetUnitIds()
  366. }
  367. func (units UnitPtrs) GetUnitIds() (unitIds []int) {
  368. for _, unit := range units {
  369. unitIds = append(unitIds, unit.Id)
  370. }
  371. return
  372. }
  373. func (unit Unit) Flush() {
  374. unit.children = []*Unit{}
  375. unit.childrenReady = false
  376. unit.formulars = Formulars{}
  377. unit.formularsReady = false
  378. unit.isActive = false
  379. unit.isActiveReady = false
  380. }
  381. func (unit Unit) IsEqualsTo(compareTo Unit) bool {
  382. unit.Flush()
  383. compareTo.Flush()
  384. return reflect.DeepEqual(unit, compareTo)
  385. }
  386. func (unit Unit) GetVoipCodeString() string {
  387. codeInt, err := strconv.Atoi(unit.Code)
  388. if err != nil {
  389. panic(err)
  390. }
  391. return fmt.Sprintf("%02v %03v %02v", codeInt/100000, codeInt/100%1000, codeInt%100)
  392. }