widget_os.py 22.1 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
import json
import logging

from colander import SchemaNode, null, Mapping, Invalid, string_types
from deform.widget import Widget, _StrippedString, Select2Widget, default_resources, \
    ResourceRegistry, default_resource_registry
from deform.form import Button
from iso8601.iso8601 import ISO8601_REGEX
from deform.i18n import _
from  colander import compat
_logging = logging.getLogger(__name__)


class DokumenWidget(Widget):
    template = "opensipkd.base:/views/widgets/dokumen.pt"
    readonly_template = "opensipkd.base:/views/widgets/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 = "opensipkd.base:/views/widgets/formulir.pt"
    readonly_template = "opensipkd.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 = "opensipkd.base:/views/widgets/blok_kav_no.pt"
    readonly_template = "opensipkd.base:/views/widgets/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 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 QtyWidget(Widget):
    template = "opensipkd.base:/views/widgets/qty.pt"
    readonly_template = "opensipkd.base:/views/widgets/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 = "opensipkd.base:views/widgets/captcha.pt"
    readonly_template = "textinput"
    strip = True
    requirements = ()

    def __init__(self, **kw):
        super(CaptchaWidget, self).__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 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 = "opensipkd.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 = "opensipkd.base:views/widgets/gmap.pt"
    readonly_template = "opensipkd.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": "opensipkd.base:static/js/gmap.js",
                        "css": "deform:static/select2/select2.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 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 = "opensipkd.base:views/widgets/leafmap.pt"
    readonly_template = "opensipkd.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": ["opensipkd.base:static/v3/map/leaflet/leaflet.js",
                   "https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.js"],
            "css": ["opensipkd.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 = "opensipkd.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"),
    )
    # ("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:
            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
from deform import widget

class MoneyInputWidget(widget.MoneyInputWidget):
    requirements = ({"js":"opensipkd.base:static/jquery/jquery.maskMoney.min.js"},)
    
class TextInputWidget(widget.TextInputWidget):
    template = "textinput_btn"
    button=None
    def __init__(self, **kw):
        super(TextInputWidget, self).__init__(**kw)
    
        if isinstance(self.button, compat.string_types):
                self.button = Button(self.button, type="button")