NewProduct.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #
  2. # Copyright (c) Daniel Sheffield 2021
  3. #
  4. # All rights reserved
  5. #
  6. # THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
  7. import urwid
  8. from app.db_utils import NON_IDENTIFIER_COLUMNS
  9. from ..widgets import (
  10. AutoCompleteEdit,
  11. AutoCompletePopUp,
  12. )
  13. from collections import OrderedDict
  14. class NewProduct(urwid.Overlay):
  15. def __init__(self, query_manager, under, name, data, autocomplete_cb, change_cb, apply_cb, esc_cb, apply_choice_cb):
  16. self.esc_cb = esc_cb
  17. self.under = under
  18. self._data = data
  19. self.query_manager = query_manager
  20. self.name = name
  21. title = urwid.Text('Enter Product Info', align='center')
  22. self.fields = OrderedDict()
  23. for f in ('product', 'category', 'group'):
  24. w = AutoCompleteEdit(('bg', f))
  25. self.fields[f] = w
  26. w.set_edit_text(data[f])
  27. urwid.connect_signal(w, 'change', change_cb(f))
  28. ok = urwid.Button('Done', on_press=lambda w: apply_cb(**self.data))
  29. body = urwid.AttrMap(urwid.ListBox(urwid.SimpleListWalker([
  30. urwid.Pile([
  31. urwid.AttrMap(title, 'banner'),
  32. urwid.Divider(),
  33. *[
  34. urwid.AttrMap(
  35. urwid.LineBox(urwid.AttrMap(
  36. AutoCompletePopUp(
  37. v,
  38. apply_change_func=lambda name, pop_up_cb: autocomplete_cb(name, pop_up_cb),
  39. apply_choice_cb=apply_choice_cb,
  40. ),'streak'), title=k.title(), title_align='left'), 'banner'
  41. ) for k,v in self.fields.items()
  42. ],
  43. urwid.AttrMap(ok, 'banner'),
  44. ], focus_item=2)
  45. ])
  46. ), 'banner')
  47. super().__init__(urwid.AttrMap(body, 'bg'), under,
  48. align='center', width=('relative', 40),
  49. valign='middle', height=('relative', 40),
  50. min_width=20, min_height=12)
  51. @property
  52. def data(self):
  53. return dict([(k,v) for k,v in self._data.items() if k in ('product', 'category', 'group')])
  54. def _apply_choice(self, name, value):
  55. self._data.update({
  56. name: value
  57. })
  58. for k,v in self.data.items():
  59. if k == name or v:
  60. continue
  61. options = self.query_manager.unique_suggestions(k, exclude=[self.name, *NON_IDENTIFIER_COLUMNS], **self.data)
  62. if len(options) == 1 and k != 'ts':
  63. self._data.update({
  64. k: list(options)[0]
  65. })
  66. def apply_choice(self, name):
  67. return lambda w,x: self._apply_choice(name, x)
  68. def update(self):
  69. for k, v in self.data.items():
  70. self.fields[k].set_edit_text(v)
  71. return self
  72. def keypress(self, size, key):
  73. if key == 'esc':
  74. self.esc_cb()
  75. return
  76. if key == 'tab':
  77. return
  78. return super().keypress(size, key)