filter.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package vuetifyx
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/gob"
  6. "fmt"
  7. "net/url"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/qor5/web"
  13. h "github.com/theplant/htmlgo"
  14. )
  15. type VXFilterBuilder struct {
  16. value FilterData
  17. tag *h.HTMLTagBuilder
  18. onChange interface{}
  19. }
  20. func VXFilter(value FilterData) (r *VXFilterBuilder) {
  21. r = &VXFilterBuilder{
  22. value: value,
  23. tag: h.Tag("vx-filter"),
  24. }
  25. return
  26. }
  27. func (b *VXFilterBuilder) Attr(vs ...interface{}) (r *VXFilterBuilder) {
  28. b.tag.Attr(vs...)
  29. return b
  30. }
  31. func (b *VXFilterBuilder) Value(v FilterData) (r *VXFilterBuilder) {
  32. b.tag.Attr(":value", v)
  33. return b
  34. }
  35. func (b *VXFilterBuilder) Translations(v FilterTranslations) (r *VXFilterBuilder) {
  36. b.tag.Attr(":translations", h.JSONString(v))
  37. return b
  38. }
  39. func (b *VXFilterBuilder) OnChange(v interface{}) (r *VXFilterBuilder) {
  40. b.onChange = v
  41. return b
  42. }
  43. func (b *VXFilterBuilder) MarshalHTML(ctx context.Context) (r []byte, err error) {
  44. var visibleFilterData FilterData
  45. for _, v := range b.value {
  46. if !v.Invisible {
  47. visibleFilterData = append(visibleFilterData, v)
  48. }
  49. }
  50. if b.onChange == nil {
  51. // $plaid().stringLocation(qs).mergeQueryWithoutParams(keysInFilterData).url(window.location.href).pushState(true).go()
  52. b.onChange = web.GET().
  53. StringQuery(web.Var("$event.encodedFilterData")).
  54. ClearMergeQuery(web.Var("$event.filterKeys")).
  55. PushState(true).
  56. Go()
  57. }
  58. b = b.Value(visibleFilterData).Attr("@change", b.onChange)
  59. return b.tag.MarshalHTML(ctx)
  60. }
  61. /*
  62. translations: {
  63. type: Object,
  64. default: () => {
  65. return {
  66. date: {
  67. to: 'to',
  68. },
  69. number: {
  70. equals: 'is equal to',
  71. between: 'between',
  72. greaterThan: 'is greater than',
  73. lessThan: 'is less than',
  74. and: 'and',
  75. },
  76. string: {
  77. equals: 'is equal to',
  78. contains: 'contains',
  79. },
  80. clear: 'Clear',
  81. filters: 'Filters',
  82. filter: 'Filter',
  83. done: 'Done',
  84. };
  85. },
  86. */
  87. type FilterTranslations struct {
  88. Clear string `json:"clear,omitempty"`
  89. Add string `json:"add,omitempty"`
  90. Apply string `json:"apply,omitempty"`
  91. Date struct {
  92. To string `json:"to,omitempty"`
  93. } `json:"date,omitempty"`
  94. Number struct {
  95. Equals string `json:"equals,omitempty"`
  96. Between string `json:"between,omitempty"`
  97. GreaterThan string `json:"greaterThan,omitempty"`
  98. LessThan string `json:"lessThan,omitempty"`
  99. And string `json:"and,omitempty"`
  100. } `json:"number,omitempty"`
  101. String struct {
  102. Equals string `json:"equals,omitempty"`
  103. Contains string `json:"contains,omitempty"`
  104. } `json:"string,omitempty"`
  105. MultipleSelect struct {
  106. In string `json:"in,omitempty"`
  107. NotIn string `json:"notIn,omitempty"`
  108. } `json:"multipleSelect,omitempty"`
  109. }
  110. type FilterIndependentTranslations struct {
  111. FilterBy string `json:"filterBy,omitempty"`
  112. }
  113. type FilterItemType string
  114. const (
  115. ItemTypeDatetimeRange FilterItemType = "DatetimeRangeItem"
  116. ItemTypeDateRange FilterItemType = "DateRangeItem"
  117. ItemTypeDate FilterItemType = "DateItem"
  118. ItemTypeSelect FilterItemType = "SelectItem"
  119. ItemTypeMultipleSelect FilterItemType = "MultipleSelectItem"
  120. ItemTypeLinkageSelect FilterItemType = "LinkageSelectItem"
  121. ItemTypeNumber FilterItemType = "NumberItem"
  122. ItemTypeString FilterItemType = "StringItem"
  123. )
  124. type FilterItemModifier string
  125. const (
  126. ModifierEquals FilterItemModifier = "equals" // String, Number
  127. ModifierBetween FilterItemModifier = "between" // DatetimeRange, Number
  128. ModifierGreaterThan FilterItemModifier = "greaterThan" // Number
  129. ModifierLessThan FilterItemModifier = "lessThan" // Number
  130. ModifierContains FilterItemModifier = "contains" // String
  131. ModifierIn FilterItemModifier = "in" // String
  132. ModifierNotIn FilterItemModifier = "notIn" // String
  133. )
  134. type FilterItemInTheLastUnit string
  135. type FilterData []*FilterItem
  136. type SelectItem struct {
  137. Text string `json:"text,omitempty"`
  138. Value string `json:"value,omitempty"`
  139. SQLCondition string `json:"-"`
  140. }
  141. type FilterLinkageSelectData struct {
  142. Items [][]*LinkageSelectItem `json:"items,omitempty"`
  143. Labels []string `json:"labels,omitempty"`
  144. SelectOutOfOrder bool `json:"selectOutOfOrder,omitempty"`
  145. SQLConditions []string `json:"-"`
  146. }
  147. type FilterItem struct {
  148. Key string `json:"key,omitempty"`
  149. Label string `json:"label,omitempty"`
  150. Folded bool `json:"folded,omitempty"`
  151. ItemType FilterItemType `json:"itemType,omitempty"`
  152. Selected bool `json:"selected,omitempty"`
  153. Modifier FilterItemModifier `json:"modifier,omitempty"`
  154. ValueIs string `json:"valueIs,omitempty"`
  155. ValuesAre []string `json:"valuesAre,omitempty"`
  156. ValueFrom string `json:"valueFrom,omitempty"`
  157. ValueTo string `json:"valueTo,omitempty"`
  158. SQLCondition string `json:"-"`
  159. Options []*SelectItem `json:"options,omitempty"`
  160. LinkageSelectData FilterLinkageSelectData `json:"linkageSelectData,omitempty"`
  161. Invisible bool `json:"invisible,omitempty"`
  162. AutocompleteDataSource *AutocompleteDataSource `json:"autocompleteDataSource,omitempty"`
  163. Translations FilterIndependentTranslations `json:"translations,omitempty"`
  164. }
  165. func (fd FilterData) Clone() (r FilterData) {
  166. buf := bytes.NewBuffer(nil)
  167. enc := gob.NewEncoder(buf)
  168. err := enc.Encode(fd)
  169. if err != nil {
  170. panic(err)
  171. }
  172. dec := gob.NewDecoder(buf)
  173. err = dec.Decode(&r)
  174. if err != nil {
  175. panic(err)
  176. }
  177. return
  178. }
  179. func (fd FilterData) getSQLCondition(key string, val string) string {
  180. it := fd.getFilterItem(key)
  181. if it == nil {
  182. return ""
  183. }
  184. // If item type is ItemTypeSelect and value is not nil, we use option's SQLCondition instead of item SQLCondition if option's SQLCondition present.
  185. if it.ItemType == ItemTypeSelect && val != "" {
  186. for _, option := range it.Options {
  187. if option.Value == val && option.SQLCondition != "" {
  188. return option.SQLCondition
  189. }
  190. }
  191. }
  192. return it.SQLCondition
  193. }
  194. func (fd FilterData) getFilterItem(key string) *FilterItem {
  195. for _, it := range fd {
  196. if it.Key == key {
  197. return it
  198. }
  199. }
  200. return nil
  201. }
  202. var sqlOps = map[string]string{
  203. "": "=",
  204. "gte": ">=",
  205. "lte": "<=",
  206. "gt": ">",
  207. "lt": "<",
  208. "ilike": "ILIKE",
  209. "in": "IN",
  210. "notIn": "NOT IN",
  211. }
  212. const SQLOperatorPlaceholder = "{op}"
  213. func (fd FilterData) SetByQueryString(qs string) (sqlCondition string, sqlArgs []interface{}) {
  214. queryMap, err := url.ParseQuery(qs)
  215. if err != nil {
  216. panic(err)
  217. }
  218. var conds []string
  219. var keys = make([]string, len(queryMap))
  220. i := 0
  221. for k := range queryMap {
  222. keys[i] = k
  223. i++
  224. }
  225. sort.Strings(keys)
  226. var keyModValueMap = map[string]map[string]string{}
  227. for _, k := range keys {
  228. v := queryMap[k]
  229. segs := strings.Split(k, ".")
  230. var mod = ""
  231. key := k
  232. val := v[0]
  233. if len(segs) > 1 {
  234. key = segs[0]
  235. mod = segs[1]
  236. }
  237. it := fd.getFilterItem(key)
  238. if it == nil {
  239. continue
  240. }
  241. if _, ok := keyModValueMap[key]; !ok {
  242. keyModValueMap[key] = map[string]string{}
  243. }
  244. keyModValueMap[key][mod] = v[0]
  245. if it.ItemType == ItemTypeLinkageSelect {
  246. vals := strings.Split(val, ",")
  247. for i, v := range vals {
  248. if v != "" {
  249. conds = append(conds, it.LinkageSelectData.SQLConditions[i])
  250. sqlArgs = append(sqlArgs, v)
  251. }
  252. }
  253. } else {
  254. sqlc := fd.getSQLCondition(key, v[0])
  255. if len(sqlc) > 0 {
  256. var ival interface{} = val
  257. if it.ItemType == ItemTypeDatetimeRange {
  258. var err error
  259. ival, err = time.ParseInLocation("2006-01-02 15:04", val, time.Local)
  260. if err != nil {
  261. continue
  262. }
  263. } else if it.ItemType == ItemTypeDate || it.ItemType == ItemTypeDateRange {
  264. var err error
  265. ival, err = time.ParseInLocation("2006-01-02", val, time.Local)
  266. if err != nil {
  267. continue
  268. }
  269. }
  270. if it.ItemType == ItemTypeDate {
  271. conds = append(conds, sqlcToCond(sqlc, "gte"), sqlcToCond(sqlc, "lt"))
  272. sqlArgs = append(sqlArgs, ival, ival.(time.Time).Add(24*time.Hour))
  273. } else if it.ItemType == ItemTypeDateRange {
  274. if mod == "gte" {
  275. conds = append(conds, sqlcToCond(sqlc, "gte"))
  276. sqlArgs = append(sqlArgs, ival)
  277. }
  278. if mod == "lte" {
  279. conds = append(conds, sqlcToCond(sqlc, "lt"))
  280. sqlArgs = append(sqlArgs, ival.(time.Time).Add(24*time.Hour))
  281. }
  282. } else {
  283. conds = append(conds, sqlcToCond(sqlc, mod))
  284. // Prepare value Args for sql condition.
  285. // e.g. assume value is "1"
  286. // "source_b = ?" ==> []interface{}{"1"}
  287. // "source_b = ? OR source_c = ?" ==> []interface{}{"1", "1"}
  288. // "source_b ilike ? OR source_c ilike ?" ==> []interface{}{"%1%", "%1%"}
  289. valCount := strings.Count(sqlc, "?")
  290. for i := 0; i < valCount; i++ {
  291. switch mod {
  292. case "ilike":
  293. sqlArgs = append(sqlArgs, fmt.Sprintf("%%%s%%", val))
  294. case "in", "notIn":
  295. sqlArgs = append(sqlArgs, strings.Split(val, ","))
  296. default:
  297. sqlArgs = append(sqlArgs, ival)
  298. }
  299. }
  300. }
  301. }
  302. }
  303. }
  304. sqlCondition = strings.Join(conds, " AND ")
  305. for k, mv := range keyModValueMap {
  306. for _, it := range fd {
  307. if it.Key != k {
  308. continue
  309. }
  310. if len(mv) == 2 {
  311. it.Selected = true
  312. it.Modifier = ModifierBetween
  313. if it.ItemType == ItemTypeDatetimeRange {
  314. it.ValueFrom = mv["gte"]
  315. it.ValueTo = mv["lt"]
  316. }
  317. if it.ItemType == ItemTypeNumber || it.ItemType == ItemTypeDateRange {
  318. it.ValueFrom = mv["gte"]
  319. it.ValueTo = mv["lte"]
  320. }
  321. } else if len(mv) == 1 {
  322. it.Selected = true
  323. for mod, v := range mv {
  324. if mod == "" {
  325. it.Modifier = ModifierEquals
  326. }
  327. if it.ItemType == ItemTypeMultipleSelect {
  328. switch mod {
  329. case "in":
  330. it.Modifier = ModifierIn
  331. case "notIn":
  332. it.Modifier = ModifierNotIn
  333. default:
  334. it.Modifier = ModifierIn
  335. }
  336. if v != "" {
  337. it.ValuesAre = strings.Split(v, ",")
  338. }
  339. continue
  340. }
  341. if it.ItemType == ItemTypeLinkageSelect {
  342. if v != "" {
  343. it.ValuesAre = strings.Split(v, ",")
  344. }
  345. continue
  346. }
  347. if it.ItemType == ItemTypeDatetimeRange {
  348. it.ValueIs = v
  349. if mod == "gte" {
  350. it.ValueFrom = mv["gte"]
  351. }
  352. if mod == "lt" {
  353. it.ValueTo = mv["lt"]
  354. }
  355. continue
  356. }
  357. if it.ItemType == ItemTypeDateRange {
  358. it.ValueIs = v
  359. if mod == "gte" {
  360. it.ValueFrom = mv["gte"]
  361. }
  362. if mod == "lte" {
  363. it.ValueTo = mv["lte"]
  364. }
  365. continue
  366. }
  367. it.ValueIs = v
  368. if it.ItemType == ItemTypeNumber {
  369. if mod == "gte" {
  370. it.Modifier = ModifierBetween
  371. it.ValueFrom = v
  372. }
  373. if mod == "lte" {
  374. it.Modifier = ModifierBetween
  375. it.ValueTo = v
  376. }
  377. if mod == "gt" {
  378. it.Modifier = ModifierGreaterThan
  379. it.ValueFrom = v
  380. }
  381. if mod == "lt" {
  382. it.Modifier = ModifierLessThan
  383. it.ValueTo = v
  384. }
  385. continue
  386. }
  387. if it.ItemType == ItemTypeString {
  388. if mod == "ilike" {
  389. it.Modifier = ModifierContains
  390. }
  391. continue
  392. }
  393. }
  394. }
  395. }
  396. }
  397. return
  398. }
  399. func unixToDate(u string) string {
  400. return unixToDatetimeWithFormat(u, "2006-01-02")
  401. }
  402. func unixToDatetime(u string) string {
  403. return unixToDatetimeWithFormat(u, time.RFC3339)
  404. }
  405. func unixToDatetimeWithFormat(u string, format string) string {
  406. return unixToTime(u).Format(format)
  407. }
  408. // We always use local timezone(server timezone) to parse time.
  409. // e.g.
  410. // Server timezone: UTC+8
  411. // Client timezone: UTC+10
  412. // Client send 2022-4-15 12:00:00 UTC+10
  413. // Server would parse it as 2022-4-15 10:00:00 UTC+8
  414. func unixToTime(u string) time.Time {
  415. unix, _ := strconv.ParseInt(u, 10, 64)
  416. d := time.Unix(unix, 0)
  417. return d
  418. }
  419. func sqlcToCond(sqlc string, mod string) string {
  420. // Compose operator into sql condition. If you want to use multiple operators you have to use {op}, '%s' is not supported
  421. // e.g.
  422. // "source_b %s ?" ==> "source_b = ?"
  423. // "source_b {op} ?" ==> "source_b = ?"
  424. // "source_b {op} ? AND source_c {op} ?" ==> "source_b = ? AND source_c = ?"
  425. if strings.Contains(sqlc, "%s") {
  426. // This is for backward compatibility
  427. return fmt.Sprintf(sqlc, sqlOps[mod])
  428. }
  429. return strings.NewReplacer(SQLOperatorPlaceholder, sqlOps[mod]).Replace(sqlc)
  430. }