pcpd.py 37.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
# from types import NoneType
import os
from pyramid.view import (
    view_config,
)
from ..views import BaseView
from ..models import *
from ..models.eis import Eis, Chart, ChartItem, Slide
from datatables import ColumnDT, DataTables
from sqlalchemy import func, and_, String, text
from sqlalchemy.sql.expression import cast
from ..models.payment import PaymentPBB, PaymentPAD, PaymentBPHTB, PaymentWEBR, TargetsBangbadil, UploadRealisasiOpsen
from opensipkd.pbb.monitoring.models import PembayaranSppt, Kecamatan, Kelurahan, Sppt
from opensipkd.pjdl.models import Sspd, Pajak, Usaha, PdlDBSession
from datetime import timedelta
from ..models.payment import PCDBSession

log = logging.getLogger(__name__)

PAD_TYP = {
    "hotel": ["1"],
    "resto": ["2"],
    "hiburan": ["3"],
    "ppju": ["7"],
    "minerba": ["9"],
    "parkir": ["5"],
    "walet": ["10"],
    "atd": ["6"],
    "reklame": ["4"],
    "pbb": ["0"],
}


PAD2_TYP = {
    "hotel": "41011903",
    "resto": "41011901",
    "hiburan": "41011905",
    "ppju": "41011902",
    "minerba": "410114",
    "parkir": "41011904",
    "walet": "410113",
    "atd": "410112",
    "reklame": "410109",
    "pbb": "0",
}

jenis_pajak = {
    "opsen_pkb": {
        "kode": "4.1.01.20.01.0001",
        "nama": "Opsen PKB",
        "subs": []
    },
    "opsen_bbnkb": {
        "kode": "4.1.01.20.02.0001",
        "nama": "Opsen BBNKB",
        "subs": []
    },
    "pbb": {
        "kode": "4.1.1.0",
        "nama": "Pajak Bumi & Bangunan",
        "subs": []
    },
    "bphtb": {
        "kode": "4.1.0.0",
        "nama": "Bea Perolehan Hak atas Tanah dan Bangunan",
         "subs": []
    },
    "resto": {
        "kode": "4.1.1.02",
        "nama": "PBJT - Makanan dan Minuman",
         "subs": []
    },
    "ppju": {
        "kode": "4.1.1.05",
        "nama": "PBJT-Tenaga Listrik",
        "subs": []},
    "hotel": {
        "kode": "4.1.1.01",
        "nama": "PBJT Jasa Perhotelan",
        "subs": []
    },
    "parkir": {
        "kode": "4.1.1.07",
        "nama": "Pajak Parkir"},
    "hiburan": {
        "kode": "4.1.1.03",
        "nama": "PBJT - Jasa Kesenian dan Hiburan",
        "subs": []
    },
    "reklame": {
        "kode": "4.1.1.04",
        "nama": "Pajak Rekalme",
        "subs": []
    },
    "atd": {
        "kode": "4.1.1.08",
        "nama": "Pajak Air Tanah"},
    "walet": {
        "kode": "4.1.1.09",
        "nama": "Pajak Sarang Burung Walet"},
    "minerba": {
        "kode": "4.1.1.06",
        "nama": "Pajak Mineral Bukan Logam dan Batuan",
        "subs": []
    }
}


class Views(BaseView):
    def __init__(self, request):
        super().__init__(request)
        self.db_session = PCDBSession

    @view_config(route_name='eis-pcpd', renderer='templates/pcpd.pt',
                 permission='eis')
    def view_app(self):
        return {"module": "pad",
                "title": "Realisasi Pajak dan Retribusi Daerah"}

    def get_dummy_data(self):
        return {"today": 1000,
                "trx": 155,
                "ytd": 10000,
                "trxYtd": 1550,
                "pie": [("I", 100, '#16a75c'), ("II", 200, '#ffb900'),
                        ("III", 300, '#133132'), ("IV", 200, '#123456'),
                        ("V", 100, '#545355')],
                "daily": [("I", 100), ("II", 200), ("III", 300), ("IV", 200), ("V", 100), ("VI", 100), ("VII", 700)],
                "dailyTrx": [("I", 50), ("II", 25), ("III", 10), ("IV", 10), ("V", 50), ("VI", 34), ("VII", 35)],
                "dailyAcc": [("I", 100), ("II", 200), ("III", 300), ("IV", 200), ("V", 100), ("VI", 100), ("VII", 700)],
                "dailyAccTrx": [("I", 100), ("II", 200), ("III", 300), ("IV", 200), ("V", 100), ("VI", 100), ("VII", 700)],
                "weekly": [("1", 100), ("2", 200), ("3", 300), ("4", 200), ("5", 100), ("6", 100), ("7", 700)],
                "weeklyTrx": [("1", 100), ("2", 200), ("3", 300), ("4", 200), ("5", 100), ("6", 100), ("7", 700)],
                "weeklyAcc": [("1", 100), ("2", 200), ("3", 300), ("4", 200), ("5", 100), ("6", 100), ("7", 700)],
                "weeklyAccTrx": [("1", 100), ("2", 200), ("3", 300), ("4", 200), ("5", 100), ("6", 100), ("7", 700)],
                "monthly": [("JAN", 100), ("FEB", 200), ("MAR", 300), ("APR", 200), ("MAY", 100), ("JUN", 100), ("JUL", 700)],
                "monthlyTrx": [("JAN", 100), ("FEB", 200), ("MAR", 300), ("APR", 400), ("MAY", 500), ("JUN", 600), ("JUL", 700)],
                "monthlyAcc": [("JAN", 100), ("FEB", 200), ("MAR", 300), ("APR", 200), ("MAY", 100), ("JUN", 100), ("JUL", 700)],
                "monthtrAccTrx": [("JAN", 100), ("FEB", 200), ("MAR", 300), ("APR", 200), ("MAY", 100), ("JUN", 100), ("JUL", 700)],
                }

    def get_daily_data(self, table, field, today, filters, typ=None):
        #todo ada kemungkinan menyebabkan error ke transaksi yang lain
        if type(filters) is not list:
            filters = [filters]
        if PCDBSession.registry().in_transaction():
            PCDBSession.rollback() 
        columns = [field.label("step")]
        if typ == 'opsen_pkb':
            qry = table.qry_sum_pkb(columns) \
                .group_by(field)\
                .order_by(field)
        elif typ == 'opsen_bbnkb':
            qry = table.qry_sum_bbnkb(columns) \
                .group_by(field)\
                .order_by(field)            
        else:
            qry = table.qry_sum(columns) \
                .group_by(field)\
                .order_by(field)
            
        qry = qry.filter(*filters)
        opsen = ["opsen_pkb", "opsen_bbnkb"]
        if typ != None and typ not in opsen:
            if typ == "pajak":
                qry = qry.filter(Usaha.id.notin_(PAD_TYP['pbb']))
            else:
                qry = qry.filter(Usaha.id.in_(PAD_TYP[typ]))

        daily = []
        dailyTrx = []
        dailyAcc = []
        dailyAccTrx = []
        amt = trx = acc = accTrx = 0
        

        for r in qry:
            mapped = r._mapping
            step = mapped.get("step","")
            bayar = mapped.get("bayar", 0)
            denda = mapped.get("denda", 0)
            #pokok = float(bayar)
            pokok = bayar-denda
            tx = mapped.get("trx",0)
            daily.append((step, pokok))
            dailyTrx.append((step, tx))
            acc += pokok
            accTrx += tx
            dailyAcc.append((step, acc))
            dailyAccTrx.append((step, accTrx))
            if step == today:
                amt = pokok
                trx = tx
        return amt, trx, daily, dailyTrx, dailyAcc, dailyAccTrx

    def get_targets(self, kode=None):
        targets = TargetsBangbadil.query_from([
            func.sum(TargetsBangbadil.t_anggaran).label("murni"),
            func.sum(TargetsBangbadil.t_perubahan).label("perubahan"),])\
            .filter(
            TargetsBangbadil.tahun == self.ses['tahun'],
        )
        if kode:
            if kode == "pajak":
                return 0
            elif kode == 'opsen_pkb':
                targets = targets.filter(
                TargetsBangbadil.kode.ilike('4.1.1.10%'))
            elif kode == 'opsen_bbnkb':
                targets = targets.filter(
                TargetsBangbadil.kode.ilike('4.1.1.11%'))
            elif kode == 'pbb':
                targets = targets.filter(TargetsBangbadil.kode == jenis_pajak[kode]["kode"])
            else:
                targets = targets.filter(
                    TargetsBangbadil.kode.ilike(jenis_pajak[kode]["kode"]+'%'))
        targets = targets.first()
        if targets:
            target = targets.perubahan or targets.murni or 0
        else:
            target = 0
        target = float(target)
        return target

    def get_pbb_data(self):
        today = datetime.now().date()
        #Piutang

        #Harian
        field = func.to_char(PembayaranSppt.tgl_pembayaran_sppt, 'yyyy-mm-dd')
        filter_exp = PembayaranSppt.tgl_pembayaran_sppt.between(
            today-timedelta(days=6), today)
        
        amt, trx, daily, dailyTrx, dailyAcc, dailyAccTrx = \
            self.get_daily_data(PembayaranSppt, field,
                                today.strftime("%Y-%m-%d"), filter_exp)

        #Total Setahun
        field = func.to_char(PembayaranSppt.tgl_pembayaran_sppt, 'IYYY')
        filter_exp = PembayaranSppt.tgl_pembayaran_sppt.between(
            datetime.strptime(f"{today.year}-01-01", "%Y-%m-%d"), today)
        ytd, ytdTrx, yearly, yearlyTrx, yearlyAcc, yearlyAccTrx = \
            self.get_daily_data(PembayaranSppt, field,
                                str(today.year),  filter_exp)
        #Piutang
        filter_exp = [PembayaranSppt.tgl_pembayaran_sppt.between(
            datetime.strptime(f"{today.year}-01-01", "%Y-%m-%d"), today),
            PembayaranSppt.thn_pajak_sppt < today.year]
        piutang, piutangTrx, yearly, yearlyTrx, yearlyAcc, yearlyAccTrx = \
            self.get_daily_data(PembayaranSppt, field,
                                str(today.year),  filter_exp)

        #Bulanan
        field = func.to_char(PembayaranSppt.tgl_pembayaran_sppt, 'MM')
        month, monthTrx, monthly, monthlyTrx, monthlyAcc, monthlyAccTrx = \
            self.get_daily_data(PembayaranSppt, field, None, filter_exp)

        #Mingguan
        field = func.to_char(PembayaranSppt.tgl_pembayaran_sppt, 'WW')
        filter_exp = PembayaranSppt.tgl_pembayaran_sppt.between(
            today-timedelta(weeks=6), today)
        week, weekTrx, weekly, weeklyTrx, weeklyAcc, weeklyAccTrx = \
            self.get_daily_data(PembayaranSppt,  field, None, filter_exp)

        ytd_target = float(self.get_targets("pbb"))
        ytd_persen = round(ytd/ytd_target * 100, 2) if ytd_target > 0 else 0

        return {"today": amt,
                "trx": trx,
                "daily": daily,
                "dailyTrx": dailyTrx,
                "dailyAcc": dailyAcc,
                "dailyAccTrx": dailyAccTrx,
                "ytd": ytd,
                "pokok": ytd-piutang,
                "piutang": piutang,
                "piutangTrx": piutangTrx,
                "trxYtd": ytdTrx,
                "pie": [("I", 100, '#16a75c'), ("II", 200, '#ffb900'),
                        ("III", 300, '#133132'), ("IV", 200, '#123456'),
                        ("V", 100, '#545355')],
                "weekly": weekly,
                "weeklyTrx": weeklyTrx,
                "weeklyAcc": weeklyAcc,
                "weeklyAccTrx": weeklyAccTrx,
                "monthly": monthly,
                "monthlyTrx": monthlyTrx,
                "monthlyAcc": monthlyAcc,
                "monthlyAccTrx": monthlyAccTrx,
                "ytdTarget": ytd_target,
                "ytdPersen": ytd_persen,
                }

    def get_bphtb_data(self):
        if log.root.level == logging.DEBUG:
            today = datetime.strptime('2025-06-05', "%Y-%m-%d")
        else:
            today = datetime.now().date()

        #Harian
        field = func.to_char(PaymentBPHTB.tgl, 'yyyy-mm-dd')
        filter_exp = PaymentBPHTB.tgl.between(
            today-timedelta(days=6), today)
        amt, trx, daily, dailyTrx, dailyAcc, dailyAccTrx = \
            self.get_daily_data(PaymentBPHTB, field,
                                today.strftime("%Y-%m-%d"), filter_exp)
        
        #Total Tahunan
        field = func.to_char(PaymentBPHTB.tgl, 'IYYY')
        filter_exp = PaymentBPHTB.tgl.between(
            datetime.strptime(f"{today.year}-01-01", "%Y-%m-%d"), today)
        ytd, ytdTrx, yearly, yearlyTrx, yearlyAcc, yearlyAccTrx = \
            self.get_daily_data(PaymentBPHTB, field,
                                str(today.year), filter_exp)

        #Bulanan
        field = func.to_char(PaymentBPHTB.tgl, 'MM')
        month, monthTrx, monthly, monthlyTrx, monthlyAcc, monthlyAccTrx = \
            self.get_daily_data(PaymentBPHTB, field, None, filter_exp)

        #Mingguan
        field = func.to_char(PaymentBPHTB.tgl, 'WW')
        filter_exp = PaymentBPHTB.tgl.between(
            today-timedelta(weeks=6), today)
        week, weekTrx, weekly, weeklyTrx, weeklyAcc, weeklyAccTrx = \
            self.get_daily_data(PaymentBPHTB, field, None, filter_exp)
        
        ytd_target = float(self.get_targets("bphtb"))
        ytd_persen = round(ytd/ytd_target * 100, 2) if ytd_target > 0 else 0
        return {"today": amt,
                "trx": trx,
                "daily": daily,
                "dailyTrx": dailyTrx,
                "dailyAcc": dailyAcc,
                "dailyAccTrx": dailyAccTrx,
                "ytd": ytd,
                "trxYtd": ytdTrx,
                "pie": [("I", 100, '#16a75c'), ("II", 200, '#ffb900'),
                        ("III", 300, '#133132'), ("IV", 200, '#123456'),
                        ("V", 100, '#545355')],
                "weekly": weekly,
                "weeklyTrx": weeklyTrx,
                "weeklyAcc": weeklyAcc,
                "weeklyAccTrx": weeklyAccTrx,
                "monthly": monthly,
                "monthlyTrx": monthlyTrx,
                "monthlyAcc": monthlyAcc,
                "monthlyAccTrx": monthlyAccTrx,
                "ytdTarget": ytd_target,
                "ytdPersen": ytd_persen,
                }

    def get_pad_data(self, typ=None):
        # if log.root.level == logging.DEBUG:
            # today = datetime.strptime('2025-06-05', "%Y-%m-%d")
        # else:
        today = datetime.now().date()
        filter_ex = []

        #Harian
        field = func.to_char(Sspd.sspdtgl, 'yyyy-mm-dd')
        filter_exp = Sspd.sspdtgl.between(today-timedelta(days=6), today)
        amt, trx, daily, dailyTrx, dailyAcc, dailyAccTrx = \
            self.get_daily_data(Sspd, field,
                                today.strftime("%Y-%m-%d"), filter_exp, typ)

        
        #Total Tahun Berjalan
        field = func.to_char(Sspd.sspdtgl, 'IYYY')
        filter_exp = Sspd.sspdtgl.between(
            datetime.strptime(f"{today.year}-01-01", "%Y-%m-%d"), today)
        ytd, ytdTrx, yearly, yearlyTrx, yearlyAcc, yearlyAccTrx = \
            self.get_daily_data(Sspd, field, str(
                today.year), filter_exp, typ)
        #Bulanan
        field = func.to_char(Sspd.sspdtgl, 'MM')
        month, monthTrx, monthly, monthlyTrx, monthlyAcc, monthlyAccTrx = \
            self.get_daily_data(Sspd, field, None, filter_exp, typ)

        #Mingguan
        field = func.to_char(Sspd.sspdtgl, 'WW')
        filter_exp = Sspd.sspdtgl.between(
            today-timedelta(weeks=6), today)
        week, weekTrx, weekly, weeklyTrx, weeklyAcc, weeklyAccTrx = \
            self.get_daily_data(Sspd,  field, None, filter_exp, typ)
        
        #Target 
        ytd_target = float(self.get_targets(typ))
        ytd_persen = round(ytd/ytd_target * 100, 2) if ytd_target > 0 else 0
        return {"today": amt,
                "trx": trx,
                "daily": daily,
                "dailyTrx": dailyTrx,
                "dailyAcc": dailyAcc,
                "dailyAccTrx": dailyAccTrx,
                "ytd": ytd,
                "trxYtd": ytdTrx,
                "pie": [("I", 100, '#16a75c'), ("II", 200, '#ffb900'),
                        ("III", 300, '#133132'), ("IV", 200, '#123456'),
                        ("V", 100, '#545355')],
                "weekly": weekly,
                "weeklyTrx": weeklyTrx,
                "weeklyAcc": weeklyAcc,
                "weeklyAccTrx": weeklyAccTrx,
                "monthly": monthly,
                "monthlyTrx": monthlyTrx,
                "monthlyAcc": monthlyAcc,
                "monthlyAccTrx": monthlyAccTrx,
                "ytdTarget": ytd_target,
                "ytdPersen": ytd_persen,
                }

    def get_webr_data(self):
        if log.root.level == logging.DEBUG:
            today = datetime.strptime('2025-06-05', "%Y-%m-%d")
        else:
            today = datetime.now().date()

        # Harian
        field = func.to_char(PaymentWEBR.tgl, 'yyyy-mm-dd')
        filter_exp = PaymentWEBR.tgl.between(
            today-timedelta(days=6), today)
        amt, trx, daily, dailyTrx, dailyAcc, dailyAccTrx = \
            self.get_daily_data(PaymentWEBR, field,
                                today.strftime("%Y-%m-%d"), filter_exp)

        #Tahunan
        field = func.to_char(PaymentWEBR.tgl, 'IYYY')
        filter_exp = PaymentWEBR.tgl.between(
            datetime.strptime(f"{today.year}-01-01", "%Y-%m-%d"), today)
        ytd, ytdTrx, yearly, yearlyTrx, yearlyAcc, yearlyAccTrx = \
            self.get_daily_data(PaymentWEBR, field,
                                str(today.year), filter_exp)

        #Bulanan
        field = func.to_char(PaymentWEBR.tgl, 'YYYY-MM')
        month, monthTrx, monthly, monthlyTrx, monthlyAcc, monthlyAccTrx = \
            self.get_daily_data(PaymentWEBR, field, None, filter_exp)

        #Mingguan
        field = func.to_char(PaymentWEBR.tgl, 'YYYY-WW')
        filter_exp = PaymentWEBR.tgl.between(
            today-timedelta(weeks=6), today)
        week, weekTrx, weekly, weeklyTrx, weeklyAcc, weeklyAccTrx = \
            self.get_daily_data(PaymentWEBR,  field, None, filter_exp)

        return {"today": amt,
                "trx": trx,
                "daily": daily,
                "dailyTrx": dailyTrx,
                "dailyAcc": dailyAcc,
                "dailyAccTrx": dailyAccTrx,
                "ytd": ytd,
                "trxYtd": ytdTrx,
                "pie": [("I", 100, '#16a75c'), ("II", 200, '#ffb900'),
                        ("III", 300, '#133132'), ("IV", 200, '#123456'),
                        ("V", 100, '#545355')],
                "weekly": weekly,
                "weeklyTrx": weeklyTrx,
                "weeklyAcc": weeklyAcc,
                "weeklyAccTrx": weeklyAccTrx,
                "monthly": monthly,
                "monthlyTrx": monthlyTrx,
                "monthlyAcc": monthlyAcc,
                "monthlyAccTrx": monthlyAccTrx,
                "target": 0,
                }
        
    def get_pkb_data(self):
        if log.root.level == logging.DEBUG:
            today = datetime.strptime('2025-06-05', "%Y-%m-%d")
        else:
            today = datetime.now().date()

        # Harian
        field = func.to_char(UploadRealisasiOpsen.tanggal, 'yyyy-mm-dd')
        filter_exp = UploadRealisasiOpsen.tanggal.between(
            today-timedelta(days=6), today)
        amt, trx, daily, dailyTrx, dailyAcc, dailyAccTrx = \
            self.get_daily_data(UploadRealisasiOpsen, field,
                                today.strftime("%Y-%m-%d"), filter_exp, 'opsen_pkb')

        #Tahunan
        field = func.to_char(UploadRealisasiOpsen.tanggal, 'IYYY')
        filter_exp = UploadRealisasiOpsen.tanggal.between(
            datetime.strptime(f"{today.year}-01-01", "%Y-%m-%d"), today)
        ytd, ytdTrx, yearly, yearlyTrx, yearlyAcc, yearlyAccTrx = \
            self.get_daily_data(UploadRealisasiOpsen, field,
                                str(today.year), filter_exp, 'opsen_pkb')

        #Bulanan
        field = func.to_char(UploadRealisasiOpsen.tanggal, 'YYYY-MM')
        month, monthTrx, monthly, monthlyTrx, monthlyAcc, monthlyAccTrx = \
            self.get_daily_data(UploadRealisasiOpsen, field, None, filter_exp, 'opsen_pkb')

        #Mingguan
        field = func.to_char(UploadRealisasiOpsen.tanggal, 'YYYY-WW')
        filter_exp = UploadRealisasiOpsen.tanggal.between(
            today-timedelta(weeks=6), today)
        week, weekTrx, weekly, weeklyTrx, weeklyAcc, weeklyAccTrx = \
            self.get_daily_data(UploadRealisasiOpsen,  field, None, filter_exp, 'opsen_pkb')
            
        try:
            ytd_target = self.get_targets("opsen_pkb")
        except:
            ytd_target = 0

        ytd_persen = round(ytd/ytd_target * 100, 2) if ytd_target > 0 else 0

        return {"today": amt,
                "trx": trx,
                "daily": daily,
                "dailyTrx": dailyTrx,
                "dailyAcc": dailyAcc,
                "dailyAccTrx": dailyAccTrx,
                "ytd": ytd,
                "trxYtd": ytdTrx,
                "pie": [("I", 100, '#16a75c'), ("II", 200, '#ffb900'),
                        ("III", 300, '#133132'), ("IV", 200, '#123456'),
                        ("V", 100, '#545355')],
                "weekly": weekly,
                "weeklyTrx": weeklyTrx,
                "weeklyAcc": weeklyAcc,
                "weeklyAccTrx": weeklyAccTrx,
                "monthly": monthly,
                "monthlyTrx": monthlyTrx,
                "monthlyAcc": monthlyAcc,
                "monthlyAccTrx": monthlyAccTrx,
                "ytdTarget": ytd_target,
                "ytdPersen": ytd_persen,
                }


    def get_bbnkb_data(self):
        if log.root.level == logging.DEBUG:
            today = datetime.strptime('2025-06-05', "%Y-%m-%d")
        else:
            today = datetime.now().date()

        # Harian
        field = func.to_char(UploadRealisasiOpsen.tanggal, 'yyyy-mm-dd')
        filter_exp = UploadRealisasiOpsen.tanggal.between(
            today-timedelta(days=6), today)
        amt, trx, daily, dailyTrx, dailyAcc, dailyAccTrx = \
            self.get_daily_data(UploadRealisasiOpsen, field,
                                today.strftime("%Y-%m-%d"), filter_exp, 'opsen_bbnkb')

        #Tahunan
        field = func.to_char(UploadRealisasiOpsen.tanggal, 'IYYY')
        filter_exp = UploadRealisasiOpsen.tanggal.between(
            datetime.strptime(f"{today.year}-01-01", "%Y-%m-%d"), today)
        ytd, ytdTrx, yearly, yearlyTrx, yearlyAcc, yearlyAccTrx = \
            self.get_daily_data(UploadRealisasiOpsen, field,
                                str(today.year), filter_exp, 'opsen_bbnkb')

        #Bulanan
        field = func.to_char(UploadRealisasiOpsen.tanggal, 'YYYY-MM')
        month, monthTrx, monthly, monthlyTrx, monthlyAcc, monthlyAccTrx = \
            self.get_daily_data(UploadRealisasiOpsen, field, None, filter_exp, 'opsen_bbnkb')

        #Mingguan
        field = func.to_char(UploadRealisasiOpsen.tanggal, 'YYYY-WW')
        filter_exp = UploadRealisasiOpsen.tanggal.between(
            today-timedelta(weeks=6), today)
        week, weekTrx, weekly, weeklyTrx, weeklyAcc, weeklyAccTrx = \
            self.get_daily_data(UploadRealisasiOpsen,  field, None, filter_exp, 'opsen_bbnkb')
            
        try:
            ytd_target = self.get_targets("opsen_bbnkb")
        except:
            ytd_target = 0

        ytd_persen = round(ytd/ytd_target * 100, 2) if ytd_target > 0 else 0

        return {"today": amt,
                "trx": trx,
                "daily": daily,
                "dailyTrx": dailyTrx,
                "dailyAcc": dailyAcc,
                "dailyAccTrx": dailyAccTrx,
                "ytd": ytd,
                "trxYtd": ytdTrx,
                "pie": [("I", 100, '#16a75c'), ("II", 200, '#ffb900'),
                        ("III", 300, '#133132'), ("IV", 200, '#123456'),
                        ("V", 100, '#545355')],
                "weekly": weekly,
                "weeklyTrx": weeklyTrx,
                "weeklyAcc": weeklyAcc,
                "weeklyAccTrx": weeklyAccTrx,
                "monthly": monthly,
                "monthlyTrx": monthlyTrx,
                "monthlyAcc": monthlyAcc,
                "monthlyAccTrx": monthlyAccTrx,
                "ytdTarget": ytd_target,
                "ytdPersen": ytd_persen,
                }


    def loop_data(self, src, dst):
        for key, val in enumerate(src):
            found = False
            for key2, val2 in enumerate(dst):
                if val[0] == val2[0]:
                    found = True
                    dst[key2][1] += float(val[1])
            if not found:
                dst.append([val[0], float(val[1])])
        dst.sort()

    def get_pajak_data(self):
        pbb = self.get_pbb_data()
        bphtb = self.get_bphtb_data()
        pdl = self.get_pad_data('pajak')
        daily = []
        dailyTrx = []
        dailyAcc = []
        dailyAccTrx = []
        monthly = []
        monthlyTrx = []
        monthlyAcc = []
        monthlyAccTrx = []
        weekly = []
        weeklyTrx = []
        weeklyAcc = []
        weeklyAccTrx = []

        self.loop_data(pbb["daily"], daily)
        self.loop_data(pbb["dailyTrx"], dailyTrx)
        self.loop_data(pbb["dailyAcc"], dailyAcc)
        self.loop_data(pbb["dailyAccTrx"], dailyAccTrx)
        self.loop_data(pbb["monthly"], monthly)
        self.loop_data(pbb["monthlyTrx"], monthlyTrx)
        self.loop_data(pbb["monthlyAcc"], monthlyAcc)
        self.loop_data(pbb["monthlyAccTrx"], monthlyAccTrx)
        self.loop_data(pbb["weekly"], weekly)
        self.loop_data(pbb["weeklyTrx"], weeklyTrx)
        self.loop_data(pbb["weeklyAcc"], weeklyAcc)
        self.loop_data(pbb["weeklyAccTrx"], weeklyAccTrx)

        self.loop_data(bphtb["daily"], daily)
        self.loop_data(bphtb["dailyTrx"], dailyTrx)
        self.loop_data(bphtb["dailyAcc"], dailyAcc)
        self.loop_data(bphtb["dailyAccTrx"], dailyAccTrx)
        self.loop_data(bphtb["monthly"], monthly)
        self.loop_data(bphtb["monthlyTrx"], monthlyTrx)
        self.loop_data(bphtb["monthlyAcc"], monthlyAcc)
        self.loop_data(bphtb["monthlyAccTrx"], monthlyAccTrx)
        self.loop_data(bphtb["weekly"], weekly)
        self.loop_data(bphtb["weeklyTrx"], weeklyTrx)
        self.loop_data(bphtb["weeklyAcc"], weeklyAcc)
        self.loop_data(bphtb["weeklyAccTrx"], weeklyAccTrx)

        self.loop_data(pdl["daily"], daily)
        self.loop_data(pdl["dailyTrx"], dailyTrx)
        self.loop_data(pdl["dailyAcc"], dailyAcc)
        self.loop_data(pdl["dailyAccTrx"], dailyAccTrx)
        self.loop_data(pdl["monthly"], monthly)
        self.loop_data(pdl["monthlyTrx"], monthlyTrx)
        self.loop_data(pdl["monthlyAcc"], monthlyAcc)
        self.loop_data(pdl["monthlyAccTrx"], monthlyAccTrx)
        self.loop_data(pdl["weekly"], weekly)
        self.loop_data(pdl["weeklyTrx"], weeklyTrx)
        self.loop_data(pdl["weeklyAcc"], weeklyAcc)
        self.loop_data(pdl["weeklyAccTrx"], weeklyAccTrx)
        # ytd_target = float(pbb.get("ytdTarget", 0)) + float(bphtb.get("ytdTarget", 0)) + \
        #     float(pdl.get("ytdTarget", 0))
        ytd_target = self.get_targets()
        ytd = float(pbb.get("ytd", 0)) + float(bphtb.get("ytd", 0)) + \
            float(pdl.get("ytd", 0))
        resp = {"today": float(pbb.get("today", 0)) + float(bphtb.get("today", 0)) + float(pdl.get("today", 0)),
                "trx": float(pbb.get("trx", 0)) + float(bphtb.get("trx", 0)) + float(pdl.get("trx", 0)),
                "daily": daily,
                "dailyTrx": dailyTrx,
                "dailyAcc": dailyAcc,
                "dailyAccTrx": dailyAccTrx,
                "ytd": ytd,
                "trxYtd": float(pbb.get("trxYtd", 0)) + float(bphtb.get("trxYtd", 0)) + float(pdl.get("trxYtd", 0)),
                "ytdTarget": ytd_target,
                "ytdPersen": round(ytd/ytd_target * 100, 2) if ytd_target > 0 else 0,
                "pie": [("I", 100, '#16a75c'), ("II", 200, '#ffb900'),
                        ("III", 300, '#133132'), ("IV", 200, '#123456'),
                        ("V", 100, '#545355')],
                "weekly": weekly,
                "weeklyTrx": weeklyTrx,
                "weeklyAcc": weeklyAcc,
                "weeklyAccTrx": weeklyAccTrx,
                "monthly": monthly,
                "monthlyTrx": monthlyTrx,
                "monthlyAcc": monthlyAcc,
                "monthlyAccTrx": monthlyAccTrx,

                }
        return resp
    
    def get_pie(self):
        data = {}
        data.update(self.get_grid_pajak("hotel"))
        data.update(self.get_grid_pajak("resto"))
        data.update(self.get_grid_pajak("hiburan"))
        data.update(self.get_grid_pajak("parkir"))
        data.update(self.get_grid_pajak("ppju"))
        data.update(self.get_grid_pajak("minerba"))
        data.update(self.get_grid_pajak("walet"))
        data.update(self.get_grid_pajak("reklame"))
        data.update(self.get_grid_pajak("atd"))
        data.update(self.get_grid_pajak("pbb"))
        data.update(self.get_grid_pajak("bphtb"))
        data.update(self.get_grid_pajak("opsen_pkb"))
        data.update(self.get_grid_pajak("opsen_bbnkb"))
        
        resp = [{"kode": data[d]["kode"],
                "nama": data[d]["nama"],
                "target": data[d]["target"],
                "realisasi": data[d]["realisasi"],
                "sisa": data[d]["sisa"],
                "persen": data[d]["persen"]} for d in data]
        
        sum_realisasi = 0
        for d in data : 
            sum_realisasi += data[d]["realisasi"]
            
        hotel = f"{(resp[0]['realisasi']/sum_realisasi)*100:.2f}"
        resto = f"{(resp[1]['realisasi']/sum_realisasi)*100:.2f}"
        hiburan = f"{(resp[2]['realisasi']/sum_realisasi)*100:.2f}"
        parkir = f"{(resp[3]['realisasi']/sum_realisasi)*100:.2f}"
        ppju = f"{(resp[4]['realisasi']/sum_realisasi)*100:.2f}"
        minerba = f"{(resp[5]['realisasi']/sum_realisasi)*100:.2f}"
        walet = f"{(resp[6]['realisasi']/sum_realisasi)*100:.2f}"
        reklame = f"{(resp[7]['realisasi']/sum_realisasi)*100:.2f}"
        atd = f"{(resp[8]['realisasi']/sum_realisasi)*100:.2f}"
        pbb = f"{(resp[9]['realisasi']/sum_realisasi)*100:.2f}"
        bphtb = f"{(resp[10]['realisasi']/sum_realisasi)*100:.2f}"
        opsen_pkb = f"{(resp[11]['realisasi']/sum_realisasi)*100:.2f}"
        opsen_bbnkb = f"{(resp[12]['realisasi']/sum_realisasi)*100:.2f}"
        resp = {
            "pie": [
                (resp[0]['nama'], hotel , '#16a75c'), 
                (resp[1]['nama'], resto, '#ffb900'),
                (resp[2]['nama'], hiburan, "#92149B"), 
                (resp[3]['nama'], parkir, "#1188FF"),
                (resp[4]['nama'], ppju, "#C2E915"),
                (resp[5]['nama'], minerba, "#9BC8F4"),
                (resp[6]['nama'], walet, "#FFA3A3"),
                (resp[7]['nama'], reklame, "#082BA9"),
                (resp[8]['nama'], atd, "#F05D89"),
                (resp[9]['nama'], pbb, "#A7950F"),
                (resp[10]['nama'], bphtb, "#73D3E9"),
                (resp[11]['nama'], opsen_pkb, "#32A7E7"),
                (resp[12]['nama'], opsen_bbnkb, "#F87911"),
                ],
        }
        return resp
        

    def get_pbb_area(self):
        if log.root.level == logging.DEBUG:
            today = datetime.strptime('2025-06-05', "%Y-%m-%d")
        else:
            today = datetime.now().date()
        rows = Kecamatan.query().order_by(Kecamatan.kd_kecamatan)

        kecamatan = {f"{row.kd_kecamatan}": {"nama": row.nm_kecamatan,
                                             "ketetapan": 0,
                                             "realisasi": 0,
                                             "sisa": 0,
                                             "persen": 0} for row in rows}
        ketetapan = Sppt.query_from(
            [Sppt.kd_kecamatan,
             func.sum(Sppt.pbb_yg_harus_dibayar_sppt)
             ])\
            .filter(Sppt.thn_pajak_sppt == self.ses['tahun'])\
            .group_by(Sppt.kd_kecamatan)
        for row in ketetapan:
            kecamatan[row[0]]["ketetapan"] = row[1] or 0

        realisasi = PembayaranSppt.query_from(
            [PembayaranSppt.kd_kecamatan,
             func.sum(PembayaranSppt.jml_sppt_yg_dibayar -
                      PembayaranSppt.denda_sppt)
             ])\
            .filter(PembayaranSppt.thn_pajak_sppt == self.tahun)\
            .group_by(PembayaranSppt.kd_kecamatan)
        for row in realisasi:
            kecamatan[row[0]]["realisasi"] = row[1] or 0
            kecamatan[row[0]]["sisa"] = kecamatan[row[0]]["ketetapan"] - row[1]
            kecamatan[row[0]]["persen"] = kecamatan[row[0]]["realisasi"] / \
                kecamatan[row[0]]["ketetapan"] * \
                100 if kecamatan[row[0]]["ketetapan"] > 0 else 0

        return [{"kode": kec, "nama": kecamatan[kec]["nama"],
                 "ketetapan": kecamatan[kec]["ketetapan"],
                 "realisasi": kecamatan[kec]["realisasi"],
                 "sisa": kecamatan[kec]["sisa"],
                 "persen": kecamatan[kec]["persen"],
                 } for kec in kecamatan]

    def get_grid_pajak(self, jenis):

        target = self.get_targets(jenis)
        if jenis == "pbb":
            realisasi = self.get_pbb_data()["ytd"]
            
        elif jenis == "opsen_pkb":
            realisasi = self.get_pkb_data()["ytd"]
        
        elif jenis == "opsen_bbnkb":
            realisasi = self.get_bbnkb_data()["ytd"]

        elif jenis == "bphtb":
            realisasi = self.get_bphtb_data()["ytd"]
        else:
            realisasi = self.get_pad_data(jenis)["ytd"]
            #realisasi = self.get_pad_data(jenis)
            #realisasi = realisasi[f"{jenis}"]["realisasi"]

        return {jenis: {"kode": jenis_pajak[jenis]["kode"].ljust(8, '0'),
                        "nama": jenis_pajak[jenis]["nama"],
                        "target": target,
                        "realisasi": realisasi,
                        "sisa": target - realisasi,

                        "persen": round(realisasi/target * 100, 2) if target > 0 else 0}
                }

    @view_config(route_name='eis-pcpd-act', renderer='json')
    def view_app_act(self):
        tahun = self.ses['tahun']
        req = self.req
        ses = req.session
        params = req.params
        id = 'id' in params and params['id'] or 0
        json_data = {}
        json_data['success'] = False
        act = req.matchdict['act']
        if act == 'grid':
            data = {}
            data.update(self.get_grid_pajak("hotel"))
            data.update(self.get_grid_pajak("resto"))
            data.update(self.get_grid_pajak("hiburan"))
            data.update(self.get_grid_pajak("parkir"))
            data.update(self.get_grid_pajak("ppju"))
            data.update(self.get_grid_pajak("minerba"))
            data.update(self.get_grid_pajak("walet"))
            data.update(self.get_grid_pajak("reklame"))
            data.update(self.get_grid_pajak("atd"))
            data.update(self.get_grid_pajak("pbb"))
            data.update(self.get_grid_pajak("bphtb"))
            data.update(self.get_grid_pajak("opsen_pkb"))
            data.update(self.get_grid_pajak("opsen_bbnkb"))
            return [{"kode": data[d]["kode"],
                     "nama": data[d]["nama"],
                     "target": data[d]["target"],
                     "realisasi": data[d]["realisasi"],
                     "sisa": data[d]["sisa"],
                     "persen": data[d]["persen"]} for d in data]

        elif act == 'pbb':
            resp = self.get_pbb_data()
            resp["tabel"] = self.get_pbb_area()

            ketetapan = Sppt.query_from(func.sum(Sppt.pbb_yg_harus_dibayar_sppt))\
                .filter(Sppt.thn_pajak_sppt == tahun).scalar()
            realisasi = PembayaranSppt.query_from(
                func.sum(PembayaranSppt.jml_sppt_yg_dibayar - PembayaranSppt.denda_sppt))\
                .filter(PembayaranSppt.thn_pajak_sppt == tahun).scalar()
            bagi = 1000000
            resp["realisasi"] = [["Ketetapan", ketetapan and ketetapan/bagi or 0],
                                 ["Realisasi", realisasi and realisasi/bagi or 0]]

        elif act == 'bphtb':
            resp = self.get_bphtb_data()
        elif act == 'webr':
            resp = self.get_webr_data()
        elif act == 'pajak':
            resp = self.get_pajak_data()
        elif act == 'pie':
            return self.get_pie()
        else:
            resp = self.get_pad_data(act)
        resp["time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        return resp

    def realisasi_pad(self, jenis):
        target = self.get_targets(jenis)
        today = datetime.now().date()
        file_dir = os.path.split(__file__)[0]
        filename = os.path.join(file_dir, 'realisasi_pad.sql')
        rekeningkd = PAD2_TYP[jenis]
        with open(filename, 'r') as f:
            qry = f.read().format(bulan = today.month, tahun=today.year, kondisi=f"and levelid in (3,4) and issummary = 1 and rekeningkd='{rekeningkd}'")
            engine = PdlDBSession.get_bind()
            with engine.connect() as conn:
                result = conn.execute(text(qry.replace('\n', ' ')))
                d = []
                # r = result[0]
                for r in result:
                    d.append(dict(zip(result.keys(), r)))

                d = d[0]
                realisasi = d["realisasi_lalu"] + d["realisasi"]
                return {jenis: {"kode": d["kode"],
                        "nama": d["nama"],
                        "target": target,
                        "realisasi": realisasi,
                        "sisa": target - realisasi,
                        "persen": round(realisasi/target * 100, 2) if target > 0 else 0}
                }
                
    def view_pajak(self):
        return {"module": 'pajak',
                "title": "Realisasi Pajak Daerah"}

    def view_pbb(self):
        return {"module": 'pbb',
                "title": "Realisasi Pajak Bumi dan Bangunan P2"}

    def view_bphtb(self):
        return {"module": 'bphtb',
                "title": "Realisasi BPHTB"}

    def view_hotel(self):
        return {"module": 'hotel',
                "title": "Realisasi Pajak Hotel"}

    def view_resto(self):
        return {"module": 'resto',
                "title": "Realisasi Pajak Restoran"}

    def view_parkir(self):
        return {"module": 'parkir',
                "title": "Realisasi Pajak Parkir"}

    def view_hiburan(self):
        return {"module": 'hiburan',
                "title": "Realisasi Pajak Hiburan"}

    def view_ppju(self):
        return {"module": 'ppju',
                "title": "Realisasi Pajak Penerangan Jalan Umum"}

    def view_minerba(self):
        return {"module": 'minerba',
                "title": "Realisasi Pajak Minerba"}

    def view_reklame(self):
        return {"module": 'reklame',
                "title": "Realisasi Pajak Reklame"}

    def view_atd(self):
        return {"module": 'atd',
                "title": "Realisasi Pajak Air Tanah"}

    def view_webr(self):
        return {"module": 'webr',
                "title": "Realisasi Retribusi"}

    def view_opsen(self):
        return {"module": 'opsen',
                "title": "Opsen Pajak PKB dan BBNKB"}

    def view_walet(self):
        return {"module": 'walet',
                "title": "Pajak Sarang Burung Walet"}