widget_os.py 30.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
from iso8601.iso8601 import ISO8601_REGEX
from deform.widget import string_types
import json
import logging

from colander import SchemaNode, null, Mapping, Invalid  # , string_types
# from colander import compat # tidak ada di colander 2.0
from deform import widget
from deform.compat import sequence_types, text_type, text_
from deform.form import Button
from deform.i18n import _
from deform.widget import (
    Widget, _StrippedString, Select2Widget,  _normalize_choices, OptGroup,
    DateInputWidget as WidgetDateInputWidget, AutocompleteInputWidget)
from tangsel.tools.captcha import img_captcha

_logging = logging.getLogger(__name__)


class DokumenWidget(Widget):
    template = "tangsel.base:/widgets/templates/dokumen.pt"
    readonly_template = "tangsel.base:/widgets/templates/readonly/dokumen.pt"
    assume_y2k = True

    _pstruct_schema = SchemaNode(
        Mapping(),
        SchemaNode(_StrippedString(), name="jenis"),
        SchemaNode(_StrippedString(), name="year"),
        SchemaNode(_StrippedString(), name="bundle"),
        SchemaNode(_StrippedString(), name="seq"),
    )

    def serialize(self, field, cstruct, **kw):
        if cstruct is null:
            jenis = ""
            year = ""
            bundle = ""
            seq = ""
        else:
            jenis, year, bundle, seq = cstruct.split(".", 3)

        kw.setdefault("jenis", jenis)
        kw.setdefault("year", year)
        kw.setdefault("bundle", bundle)
        kw.setdefault("seq", seq)

        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        else:
            try:
                validated = self._pstruct_schema.deserialize(pstruct)
            except Invalid as exc:
                raise Invalid(field.schema, f"Invalid pstruct: {exc}")
            jenis = validated["jenis"]
            year = validated["year"]
            bundle = validated["bundle"]
            seq = validated["seq"]

            if not year and not bundle and not seq:
                return null

            if self.assume_y2k and len(year) == 2:
                year = "20" + year
            result = ".".join([jenis, year, bundle, seq])

            if not year or not bundle or not seq:
                raise Invalid(field.schema, "No Dokumen tidak lengkap", result)

            return result


class FormulirWidget(Widget):
    template = "tangsel.base:/views/widgets/formulir.pt"
    readonly_template = "tangsel.base:/views/widgets/readonly/formulir.pt"
    assume_y2k = True

    _pstruct_schema = SchemaNode(
        Mapping(),
        SchemaNode(_StrippedString(), name="year"),
        SchemaNode(_StrippedString(), name="bundle"),
        SchemaNode(_StrippedString(), name="seq"),
    )

    def serialize(self, field, cstruct, **kw):
        if cstruct is null:
            year = ""
            bundle = ""
            seq = ""
        else:
            year, bundle, seq = cstruct.split(".", 3)

        kw.setdefault("year", year)
        kw.setdefault("bundle", bundle)
        kw.setdefault("seq", seq)

        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        else:
            try:
                validated = self._pstruct_schema.deserialize(pstruct)
            except Invalid as exc:
                raise Invalid(field.schema, f"Invalid pstruct: {exc}")
            year = validated["year"]
            bundle = validated["bundle"]
            seq = validated["seq"]

            if not year and not bundle and not seq:
                return null

            if self.assume_y2k and len(year) == 2:
                year = "20" + year
            result = ".".join([year, bundle, seq])

            if not year or not bundle or not seq:
                raise Invalid(field.schema, "No Dokumen tidak lengkap", result)

            return result


class BlokKavNoWidget(Widget):
    template = "tangsel.base:./widgets/templates/blok_kav_no.pt"
    readonly_template = "tangsel.base:./widgets/templates/readonly/blok_kav_no.pt"

    _pstruct_schema = SchemaNode(
        Mapping(),
        SchemaNode(_StrippedString(), name="blok_kav_no"),
        SchemaNode(_StrippedString(), name="rt"),
        SchemaNode(_StrippedString(), name="rw")
    )

    def serialize(self, field, cstruct, **kw):
        if cstruct is null:
            blok_kav_no = ""
            rt = "000"
            rw = "00"
        else:
            blok_kav_no, rt, rw = cstruct.split("|", 3)

        kw.setdefault("blok_kav_no", blok_kav_no)
        kw.setdefault("rt", rt)
        kw.setdefault("rw", rw)

        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        else:
            try:
                validated = self._pstruct_schema.deserialize(pstruct)
            except Invalid as exc:
                raise Invalid(field.schema, f"Invalid pstruct: {exc}")
            blok_kav_no = validated["blok_kav_no"]
            rt = validated["rt"]
            rw = validated["rw"]

            if not blok_kav_no and not rt and not rw:
                return null

            result = "|".join([blok_kav_no, rt, rw])

            if not rt:
                raise Invalid(
                    field.schema, "RT harus diisi. Minimal 000", result)

            if not rw:
                raise Invalid(
                    field.schema, "RW harus diisi. Minimal 00", result)

            # if not blok_kav_no or not rt or not rw:
            #     raise Invalid(field.schema, "Blok Kav No RT/RW tidak lengkap",
            #                   result)

            return result


class Select2MsWidget(Select2Widget):
    """
    Renders ``<select>`` field based on a predefined set of values using
    `select2 <https://select2.org/>`_ library.

    **Attributes/Arguments**

    Same as :func:`~deform.widget.Select2Widget`, with some extra options
    listed here.
    url: url for slave select
    slave: id of slave  select
    widget = widget_os.Select2MsWidget(url="https://slave_item_url?item_key=selected_value,
                                        slave="slave_id")

    """

    url = ""
    slave = ""
    template = "select2_ms.pt"


class AutocompleteMsInputWidget(AutocompleteInputWidget):
    """
    Renders ``<select>`` field based on a predefined set of values using
    `select2 <https://select2.org/>`_ library.

    **Attributes/Arguments**

    Same as :func:`~deform.widget.Select2Widget`, with some extra options
    listed here.
    url: url for slave select
    slave: id of slave  select
    widget = widget_os.AutocompleteMsInputWidget(url="https://slave_item_url?item_key=selected_value,
                                        slave="slave_id")

    Saat ini untuk slave baru bisa ke select2ms atau select2 atau select

    """

    url = ""
    slave = ""
    template = "autocomplete_input_ms"

    _pstruct_schema = SchemaNode(
        Mapping(),
        SchemaNode(_StrippedString(), name="auto_id"),
        SchemaNode(_StrippedString(), name="auto_value"),
    )

    def serialize(self, field, cstruct, **kw):
        if "delay" in kw or getattr(self, "delay", None):
            raise ValueError(
                "AutocompleteWidget does not support *delay* parameter "
                "any longer."
            )

        if cstruct is null:
            auto_id = ""
            auto_value = ""
        else:
            auto_id, auto_value = cstruct.split("|", 2)

        kw.setdefault("auto_id", auto_id)
        kw.setdefault("auto_value", auto_value)
        self.values = self.values or []
        readonly = kw.get("readonly", self.readonly)

        options = {}
        if isinstance(self.values, string_types):
            options["remote"] = "%s?term=%%QUERY" % self.values
        else:
            # vals = []
            # for v in self.values:
            #     if not isinstance(v, string_types):
            #         vals.append(v[1])
            # if not vals:
            # vals = self.values

            options["local"] = self.values

        options["minLength"] = kw.pop("min_length", self.min_length)
        options["limit"] = kw.pop("items", self.items)
        kw["options"] = json.dumps(options)
        kw["data"] = self.values

        template = readonly and self.readonly_template or self.template
        tmpl_values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **tmpl_values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        else:
            try:
                validated = self._pstruct_schema.deserialize(pstruct)
            except Invalid as exc:
                raise Invalid(field.schema, text_("Invalid pstruct: %s" % exc))
            auto_id = validated["auto_id"]
            auto_value = validated["auto_value"]

            if not auto_id and not auto_value:
                return null

            result = "|".join([auto_id, auto_value])
            if not auto_id or not auto_value:
                raise Invalid(field.schema, _("Incomplete Data"), result)

            return result


class QtyWidget(Widget):
    template = "tangsel.base:/widgets/templates/qty.pt"
    readonly_template = "tangsel.base:/viewswidgets/templates/readonly/qty.pt"

    _pstruct_schema = SchemaNode(
        Mapping(),
        SchemaNode(_StrippedString(), name="qty"),
        SchemaNode(_StrippedString(), name="measure"),
    )

    def serialize(self, field, cstruct, **kw):
        if cstruct is null:
            qty = 0
            measure = 0
        else:
            qty, measure = cstruct.split("|", 3)

        kw.setdefault("qty", qty)
        kw.setdefault("measure", measure)
        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        else:
            try:
                validated = self._pstruct_schema.deserialize(pstruct)
            except Invalid as exc:
                raise Invalid(field.schema, f"Invalid pstruct: {exc}")
            qty = validated["qty"]
            measure = validated["measure"]

            if not qty and not measure:
                return null

            result = "|".join([str(qty), str(measure)])

            if not qty or not measure:
                raise Invalid(field.schema, "Data tidak lengkap", result)

            return result


class CaptchaWidget(Widget):
    """
    Renders an ``<input type="text"/>`` widget.

    **Attributes/Arguments**

    template
       The template name used to render the widget.  Default:
        ``textinput``.

    readonly_template
        The template name used to render the widget in read-only mode.
        Default: ``readonly/textinput``.

    strip
        If true, during deserialization, strip the value of leading
        and trailing whitespace (default ``True``).

    """

    template = "tangsel.base:widgets/templates/captcha.pt"
    readonly_template = "textinput"
    strip = True
    requirements = ()
    request = None
    
    def __init__(self, **kw):
        super(CaptchaWidget, self).__init__(**kw)

    def serialize(self, field, cstruct, **kw):
        kode_captcha, file_name = img_captcha(self.request)
        self.request.session["captcha"] = kode_captcha
        cstruct = self.url+file_name
        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        elif not isinstance(pstruct, string_types):
            raise Invalid(field.schema, "Pstruct is not a string")
        if self.strip:
            pstruct = pstruct.strip()
        if not pstruct:
            return null
        if pstruct != self.request.session["captcha"]:
            raise Invalid(field.schema, "Captcha tidak sesuai")
        return pstruct


class ImageWidget(Widget):
    """
    Renders an ``<img src="src"/>`` widget.

    **Attributes/Arguments**

    template
       The template name used to render the widget.  Default:
        ``image``.

    readonly_template
        The template name used to render the widget in read-only mode.
        Default: ``readonly/image``.

    strip
        If true, during deserialization, strip the value of leading
        and trailing whitespace (default ``True``).

    """

    template = "tangsel.base:views/widgets/image.pt"
    readonly_template = "image"
    strip = True
    requirements = ()
    height = "30px"

    def __init__(self, **kw):
        super().__init__(**kw)

    def serialize(self, field, cstruct, **kw):
        if cstruct in (null, None):
            cstruct = ""
        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        elif not isinstance(pstruct, string_types):
            raise Invalid(field.schema, "Pstruct is not a string")
        if self.strip:
            pstruct = pstruct.strip()
        if not pstruct:
            return null
        return pstruct


class MapWidget(Widget):
    """
    Renders an ``<div id="map"/>`` widget.

    **Attributes/Arguments**

    template
       The template name used to render the widget.  Default:
        ``textinput``.

    readonly_template
        The template name used to render the widget in read-only mode.
        Default: ``readonly/textinput``.

    strip
        If true, during deserialization, strip the value of leading
        and trailing whitespace (default ``True``).

    """

    template = "tangsel.base:views/widgets/gmap.pt"
    readonly_template = "tangsel.base:views/widgets/readonly/gmap.pt"
    map_center = [0, 0]
    map_zoom = 12
    gmap_key = None
    gmap_control = ['Point', 'Polygon', 'LineString']
    gmap_height = "400px"
    gmap_width = "100%"
    strip = True
    html_info = {}
    gmap_data_style = {
        "editable": True,
        "draggable": True,
        "clickable": True,
        "removable": True,
    }
    gmap_edit_url = ""
    show_options = False
    requirements = (('deform', None),
                    {
                        "js": "tangsel.base:static/js/gmap.js",
                        "css": "deform:static/select2/select2.css",
    },)

    def __init__(self, **kw):
        super().__init__(**kw)
        _logging.debug(self.gmap_data_style)
        self.gmap_data_style = json.dumps(self.gmap_data_style)

    def serialize(self, field, cstruct, **kw):
        if cstruct in (null, None):
            cstruct = ""
        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        _logging.debug(self.gmap_data_style)
        # if readonly:
        gmap_data_style = {
            "editable": not readonly,
            "draggable": not readonly,
            "clickable": True,
            "removable": not readonly,
        }
        self.gmap_data_style = json.dumps(gmap_data_style)
        _logging.debug(self.gmap_data_style)

        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        elif not isinstance(pstruct, string_types):
            raise Invalid(field.schema, "Pstruct is not a string")
        if self.strip:
            pstruct = pstruct.strip()
        if not pstruct:
            return null
        return pstruct


class LeafMapWidget(Widget):
    """
    Renders an ``<div id="map"/>`` widget.

    **Attributes/Arguments**

    template
       The template name used to render the widget.  Default:
        ``textinput``.

    readonly_template
        The template name used to render the widget in read-only mode.
        Default: ``readonly/textinput``.

    strip
        If true, during deserialization, strip the value of leading
        and trailing whitespace (default ``True``).

    """

    template = "tangsel.base:views/widgets/leafmap.pt"
    readonly_template = "tangsel.base:views/widgets/readonly/leafmap.pt"
    map_center = [0, 0]
    map_zoom = 12
    # gmap_control = ['Point', 'Polygon', 'LineString']
    map_height = "400px"
    map_width = "100%"
    strip = True
    html_info = {}
    # gmap_data_style = {
    #     "editable": True,
    #     "draggable": True,
    #     "clickable": True,
    #     "removable": True,
    # }
    # gmap_edit_url = ""
    show_options = True
    requirements = (
        ('deform', None),
        {
            "js": ["tangsel.base:static/v3/map/leaflet/leaflet.js",
                   "https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.js"],
            "css": ["tangsel.base:static/v3/map/leaflet/leaflet.css",
                    "https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.css"],
        })

    def __init__(self, **kw):
        super().__init__(**kw)
        # _logging.info(self.gmap_data_style)
        # self.gmap_data_style = json.dumps(self.gmap_data_style)

    def serialize(self, field, cstruct, **kw):
        if cstruct in (null, None):
            cstruct = ""
        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        # _logging.debug(self.gmap_data_style)
        # if readonly:
        gmap_data_style = {
            "editable": not readonly,
            "draggable": not readonly,
            "clickable": True,
            "removable": not readonly,
        }
        # self.gmap_data_style = json.dumps(gmap_data_style)
        # _logging.info(self.gmap_data_style)

        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        elif not isinstance(pstruct, string_types):
            raise Invalid(field.schema, "Pstruct is not a string")
        if self.strip:
            pstruct = pstruct.strip()
        if not pstruct:
            return null
        return pstruct


class BootStrapDateInputWidget(Widget):
    """
    Renders a date picker widget.

    The default rendering is as a native HTML5 date input widget,
    falling back to pickadate (https://github.com/amsul/pickadate.js.)

    Most useful when the schema node is a ``colander.Date`` object.

    **Attributes/Arguments**

    options
        Dictionary of options for configuring the widget (eg: date format)

    template
        The template name used to render the widget.  Default:
        ``dateinput``.

    readonly_template
        The template name used to render the widget in read-only mode.
        Default: ``readonly/textinput``.
    """
    template = "bootstrapdateinput"
    readonly_template = "readonly/textinput"
    type_name = "text"
    req_path = "tangsel.base:static/v3/js/plugin"
    requirements = (
        ('deform', None),
        {
            "js": (
                f"{req_path}/bootstrap-datepicker/js/bootstrap-datepicker.min.js",
                f"{req_path}/bootstrap-timepicker/bootstrap-timepicker.min.js",
                f"{req_path}/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js",
            ),
            "css": (
                f"{req_path}/bootstrap-datepicker/css/bootstrap-datepicker.min.css",
                # f"{req_path}/bootstrap-timepicker/css/bootstrap-timepicker.min.css",
                f"{req_path}/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css",
            ),
        }
    )
    default_options = (
        ("format", "yyyy-mm-dd"),
        ("zIndexOffset", "910"),

    )
    # ("selectMonths", True),
    # ("selectYears", True),
    options = None

    _pstruct_schema = SchemaNode(
        Mapping(),
        SchemaNode(_StrippedString(), name="date"),
        SchemaNode(_StrippedString(), name="date_submit", missing=""),
    )

    def serialize(self, field, cstruct, **kw):
        if cstruct in (null, None):
            cstruct = ""
        readonly = kw.get("readonly", self.readonly)
        template = readonly and self.readonly_template or self.template
        options = dict(
            kw.get("options") or self.options or self.default_options
        )
        options["formatSubmit"] = "yyyy-mm-dd"
        kw.setdefault("options_json", json.dumps(options))
        values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct in ("", null):
            return null
        try:
            _logging.debug(f"Date:{self._pstruct_schema}")
            validated = self._pstruct_schema.deserialize(pstruct)
        except Invalid as exc:
            raise Invalid(field.schema, "Invalid pstruct: %s" % exc)
        return validated["date_submit"] or validated["date"]


class BootStrapDateTimeInputWidget(Widget):
    """
    Renders a datetime picker widget.

    The default rendering is as a pair of inputs (a date and a time) using
    pickadate.js (https://github.com/amsul/pickadate.js).

    Used for ``colander.DateTime`` schema nodes.

    **Attributes/Arguments**

    date_options
        A dictionary of date options passed to pickadate.

    time_options
        A dictionary of time options passed to pickadate.

    template
        The template name used to render the widget.  Default:
        ``dateinput``.

    readonly_template
        The template name used to render the widget in read-only mode.
        Default: ``readonly/textinput``.
    """

    template = "datetimeinput"
    readonly_template = "readonly/datetimeinput"
    type_name = "datetime"
    requirements = (("modernizr", None), ("pickadate", None))
    default_date_options = (
        ("format", "yyyy-mm-dd"),
        ("selectMonths", True),
        ("selectYears", True),
    )
    date_options = None
    default_time_options = (("format", "h:i A"), ("interval", 30))
    time_options = None

    _pstruct_schema = SchemaNode(
        Mapping(),
        SchemaNode(_StrippedString(), name="date"),
        SchemaNode(_StrippedString(), name="time"),
        SchemaNode(_StrippedString(), name="date_submit", missing=""),
        SchemaNode(_StrippedString(), name="time_submit", missing=""),
    )

    def serialize(self, field, cstruct, **kw):
        if cstruct in (null, None):
            cstruct = ""
        readonly = kw.get("readonly", self.readonly)
        if cstruct:
            parsed = ISO8601_REGEX.match(cstruct)
            if parsed:  # strip timezone if it's there
                timezone = parsed.groupdict()["timezone"]
                if timezone and cstruct.endswith(timezone):
                    cstruct = cstruct[: -len(timezone)]

        try:
            date, time = cstruct.split("T", 1)
            try:
                # get rid of milliseconds
                time, _ = time.split(".", 1)
            except ValueError:
                pass
            kw["date"], kw["time"] = date, time
        except ValueError:  # need more than one item to unpack
            kw["date"] = kw["time"] = ""

        date_options = dict(
            kw.get("date_options")
            or self.date_options
            or self.default_date_options
        )
        date_options["formatSubmit"] = "yyyy-mm-dd"
        kw["date_options_json"] = json.dumps(date_options)

        time_options = dict(
            kw.get("time_options")
            or self.time_options
            or self.default_time_options
        )
        time_options["formatSubmit"] = "HH:i"
        kw["time_options_json"] = json.dumps(time_options)

        values = self.get_template_values(field, cstruct, kw)
        template = readonly and self.readonly_template or self.template
        return field.renderer(template, **values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        else:
            try:
                validated = self._pstruct_schema.deserialize(pstruct)
            except Invalid as exc:
                raise Invalid(field.schema, "Invalid pstruct: %s" % exc)
            # seriously pickadate?  oh.  right.  i forgot.  you're javascript.
            date = validated["date_submit"] or validated["date"]
            time = validated["time_submit"] or validated["time"]

            if not time and not date:
                return null

            result = "T".join([date, time])

            if not date:
                raise Invalid(field.schema, _("Incomplete date"), result)

            if not time:
                raise Invalid(field.schema, _("Incomplete time"), result)

            return result


class TextInputWidget(widget.TextInputWidget):
    template = "textinput_btn"
    button = None
    js = None

    def __init__(self, **kw):
        super(TextInputWidget, self).__init__(**kw)

        # if isinstance(self.button, compat.string_types):
        if self.button:
            if isinstance(self.button, str):
                self.button = Button(self.button, type="button")


class DateInputWidget(WidgetDateInputWidget):
    type_name = "text"


class MoneyInputWidget(widget.MoneyInputWidget):
    readonly_template = "readonly/textinput"

    def get_template_values(self, field, cstruct, kw):
        options = json.loads(kw.get("mask_options", "{}"))
        if options:
            decimal = options.get("decimal", '.')
            precision = options.get("precision", 2)
            thousands = options.get("thousands", ',')
            cstr = cstruct and float(cstruct) or 0
            cstruct = f"{cstr:,.{precision}f}"\
                .replace(".", "%")\
                .replace(",", thousands)\
                .replace("%", decimal)

        values = {"cstruct": cstruct, "field": field}
        values.update(kw)
        values.pop("template", None)
        return values


class FilterWidget(Widget):
    template = "tangsel.base:/views/widgets/filters.pt"
    readonly_template = "tangsel.base:/views/widgets/readonly/filters.pt"
    null_value = ""
    values = ()
    size = None
    multiple = False
    optgroup_class = OptGroup
    long_label_generator = None
    selectize_options = None
    default_selectize_options = (("allowEmptyOption", True),)

    _pstruct_schema = SchemaNode(
        Mapping(),
        SchemaNode(_StrippedString(), name="fields"),
        SchemaNode(_StrippedString(), name="equality"),
        SchemaNode(_StrippedString(), name="nilai"),
        SchemaNode(_StrippedString(), name="condition"),
    )

    def get_select_value(self, cstruct, value):
        """Choose whether <opt> is selected or not.

        Incoming value is always string, as it has been passed through HTML.
        However, our values might be given as integer, UUID.
        """

        if self.multiple:
            if value in map(text_type, cstruct):
                return "selected"
        else:
            if value == text_type(cstruct):
                return "selected"
        return None

    def serialize(self, field, cstruct, **kw):
        if cstruct in (null, None):
            condition = ""
            fields = ""
            equality = ""
            nilai = ""
        else:
            fields, equality, nilai, condition = cstruct.split(".", 4)
        # if cstruct in (null, None):
        #     cstruct = self.null_value
        kw.setdefault("condition", condition)
        kw.setdefault("fields", fields)
        kw.setdefault("equality", equality)
        kw.setdefault("nilai", nilai)

        readonly = kw.get("readonly", self.readonly)
        values = kw.get("values", self.values)
        if not isinstance(values, sequence_types):
            e = "Values must be a sequence type (list, tuple, or range)."
            raise TypeError(e)

        template = readonly and self.readonly_template or self.template
        kw["values"] = _normalize_choices(values)
        selectize_options = dict(
            kw.get("selectize_options")
            or self.selectize_options
            or self.default_selectize_options
        )
        kw["selectize_options_json"] = json.dumps(selectize_options)
        tmpl_values = self.get_template_values(field, cstruct, kw)
        return field.renderer(template, **tmpl_values)

    def deserialize(self, field, pstruct):
        if pstruct is null:
            return null
        else:
            try:
                validated = self._pstruct_schema.deserialize(pstruct)
            except Invalid as exc:
                raise Invalid(field.schema, f"Invalid pstruct: {exc}")
            condition = validated["condition"]
            fields = validated["fields"]
            equality = validated["equality"]
            nilai = validated["nilai"]

            # if not year and not bundle and not seq:
            #     return null
            #
            # if self.assume_y2k and len(year) == 2:
            #     year = "20" + year
            result = ".".join([fields, equality, nilai, condition])
            #
            # if not year or not bundle or not seq:
            #     raise Invalid(field.schema, "No Dokumen tidak lengkap", result)

            return result

# class AutocompleteInputWidget(widget.AutocompleteInputWidget):
#     targets = None
# def serialize(self, field, cstruct, **kw):
#     item_id = kw.get("item_id", None)
#     super().serialize(field, cstruct, **kw)
#     if "delay" in kw or getattr(self, "delay", None):
#         raise ValueError(
#             "AutocompleteWidget does not support *delay* parameter "
#             "any longer."
#         )
#     if cstruct in (null, None):
#         cstruct = ""
#     self.values = self.values or []
#     readonly = kw.get("readonly", self.readonly)
#
#     options = {}
#     if isinstance(self.values, string_types):
#         options["remote"] = "%s?term=%%QUERY" % self.values
#     else:
#         options["local"] = self.values
#
#     options["minLength"] = kw.pop("min_length", self.min_length)
#     options["limit"] = kw.pop("items", self.items)
#     kw["options"] = json.dumps(options)
#     tmpl_values = self.get_template_values(field, cstruct, kw)
#     template = readonly and self.readonly_template or self.template
#     return field.renderer(template, **tmpl_values)
#