unit.go 11 KB

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