payment_list.py 15.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
import colander
import logging
from datatables import ColumnDT
from deform import widget, Form, ValidationFailure
from opensipkd.base.views import DataTables
from opensipkd.base.tools.report import csv_response
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from sqlalchemy import case, func
from sqlalchemy.orm import aliased

from . import BaseView
from ..models import (DBSession, PartnerPay, Partner)
from opensipkd.base.tools import format_json
from opensipkd.base.tools.db import column_concat
from datetime import datetime
from ..tools import json_rpc_header
from .api_merchant import payment_advice

log = logging.getLogger(__name__)

status_payment = [
    (9999, '--Semua--'),
    (0, 'Pending'),
    (1, 'Sukses'),
    (2, 'Batal'),
]



def filter_tanggal(request, query, field):
    awal  = request.session['awal'] + ' 00:00:00' #None
    akhir = request.session['akhir'] + ' 23:59:59'#None
    
    if awal and akhir:
        tglawal    = datetime.strptime(awal, '%d-%m-%Y %H:%M:%S')
        tglakhir   = datetime.strptime(akhir, '%d-%m-%Y %H:%M:%S')
        query = query.filter(field.between(tglawal, tglakhir))

    return query

def query_csv(request, status):
    vendor = aliased(Partner, name='vendor')
    customer = aliased(Partner, name='customer')
    query = DBSession.query(PartnerPay.cust_inv_no.label('Nomor_Invoice'),
                            PartnerPay.created.label('Tanggal'),
                            column_concat([
                                PartnerPay.inv_cust_nm,
                                ' - (',
                                customer.nama,
                                ')'
                            ]).label('Nama_Customer'),
                            vendor.nama.label('Nama_Vendor'),
                            PartnerPay.amt_buy.label('Harga_Beli'),
                            PartnerPay.amt_sell.label('Harga_Jual'),
                            PartnerPay.fee.label('Fee'),
                            case(
                            [
                                (PartnerPay.status <= 0, 0)
                            ],
                            else_=PartnerPay.status).label('Status')
                           ).\
                            join(vendor, vendor.id == PartnerPay.vendor_id)\
                            .join(customer, customer.id == PartnerPay.customer_id)

    if status != 9999:
        if status <= 0:
            query = query.filter(H2hArInvoiceDet.status <= status)
        else:
            query = query.filter(H2hArInvoiceDet.status == status)

    filter_tanggal(request, query, PartnerPay.created)

    return query

def form_validator(form, value):
    pass

def get_vendors():
    vend_get = Partner.get_vendor_list()    
    select_vendor = [(9999, '--Semua--')]    
    for val in vend_get:
        select_vendor.append(tuple((val.id, val.nama)))
    print('isi vendors >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
    print(select_vendor)
    return select_vendor

def get_customers():
    cust_get = Partner.get_customer_list()
    select_customer = [(9999, '--Semua--')]
    for val in cust_get:
        # select_customer.append(val)
        select_customer.append(tuple((val.id, val.nama)))
    print('isi customer >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
    print(select_customer)
    return select_customer

class ViewData(BaseView):
        
        


            # select_vendor.append(val)

        # print('isi list >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        # print(a)
        # print(b)

    @view_config(route_name='api-payment-list',
                 permission="api-payment-list",
                 renderer='templates/payment/list.pt')
    def view_list(self):
        class ToolbarSchema(colander.Schema):
            status = colander.SchemaNode(
                colander.String(),
                oid="status", 
                widget=widget.SelectWidget(values=status_payment)
            )
            awal = colander.SchemaNode(
                colander.String(),
                oid = "awal",
                title = "Tgl."
            )
            akhir = colander.SchemaNode(
                colander.String(),
                oid = "akhir",
                title = "-"
            )
            cust_sel = colander.SchemaNode(
                colander.String(),
                oid="cust_sel",
                title="Customer",
                widget=widget.SelectWidget(values=get_vendors()),
            )
            vend_sel = colander.SchemaNode(
                colander.String(),
                oid="vend_sel",
                title="Vendor",
                widget=widget.SelectWidget(values=get_customers()),
            )

        toolbar = ToolbarSchema(Validator=form_validator)
        toolbar.request = self.req
        form = Form(schema=toolbar)

        params = {
            'form': form,
            'status_payment': [s for k, s in status_payment if k != 9999],
            'columns': [
                dict(title="ID"),
                dict(title="No. Invoice"),
                dict(title = "Tanggal"),
                dict(title="Customer"),
                dict(title="Vendor"),
                dict(title="Harga Beli"),
                dict(title="Harga Jual"),
                dict(title="Fee"),
                dict(title="Status"),
            ],
            'column_data': [
                dict(data="id", width="0px"),
                dict(data="nomor", width="150px"),
                dict(data = "created"),
                dict(data="customer"),
                dict(data="vendor"),
                dict(data="amount_buy", width="70px"),
                dict(data="amount", width="70px"),
                dict(data="fee", width="70px"),
                dict(data="status", width="70px"),
            ],
            'buttons': [
                dict(id="btn_view", cls="btn btn btn-primary", title="View"),
                dict(id="btn_close", cls="btn btn-danger", title="Tutup"),
                dict(id="btn_csv", cls="btn btn-primary", title="CSV"),
            ],
            'route': "/api/payment",
            'scripts': """
                $("#btn_close").click(function() {
                    window.location = '/api/merchant';
                    return false;
                });
        """}

        return dict(params=params)

    @view_config(route_name='api-payment-act', renderer='json',
                 permission="api-payment-list"
                 )
    def view_act(self):
        request = self.req
        url_dict = request.matchdict
        act = url_dict['act']

        def filter_tanggal(query, field):
            awal  = request.session['awal'] + ' 00:00:00' #None
            akhir = request.session['akhir'] + ' 23:59:59'#None
            
            print('isi awal dan akhir >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
            print(awal)
            print(akhir)
            if awal and akhir:
                tglawal    = datetime.strptime(awal, '%d-%m-%Y %H:%M:%S')
                tglakhir   = datetime.strptime(akhir, '%d-%m-%Y %H:%M:%S')
                query = query.filter(field.between(tglawal, tglakhir))

            return query


        if act == "grid":
            status = 9999
            if 'status' in request.params:
                status = int(request.params['status'])
            opt_cust = 9999
            if 'cust' in request.params:
                opt_cust = int(request.params['cust'])
            opt_vend = 9999
            if 'vend' in request.params:
                opt_vend = int(request.params['vend'])

            vendor = aliased(Partner, name='vendor')
            customer = aliased(Partner, name='customer')

            columns = [
                ColumnDT(PartnerPay.id, mData='id'),
                ColumnDT(PartnerPay.cust_inv_no, mData='nomor'),
                # ColumnDT(PartnerPay.created, mData = 'created'),
                ColumnDT(func.to_char(PartnerPay.created, 'dd-mm-yyyy HH24:MI'), mData = 'created'),
                ColumnDT(
                    column_concat([
                        PartnerPay.inv_cust_nm,
                        ' - (',
                        customer.nama,
                        ')'
                    ]),
                    mData='customer'
                ),
                ColumnDT(vendor.nama, mData='vendor'),
                ColumnDT(PartnerPay.amt_buy, mData='amount_buy'),
                ColumnDT(PartnerPay.amt_sell, mData='amount'),
                ColumnDT(PartnerPay.fee, mData='fee'),
                ColumnDT(case(
                    [
                        (PartnerPay.status <= 0, 0)
                    ],
                    else_=PartnerPay.status
                ), mData='status'),
            ]
            # print('masuk query grid')
            query = DBSession.query().select_from(PartnerPay)\
                .join(vendor, vendor.id == PartnerPay.vendor_id)\
                .join(customer, customer.id == PartnerPay.customer_id)
            if status != 9999:
                if status <= 0:
                    query = query.filter(PartnerPay.status <= status)
                else:
                    query = query.filter(PartnerPay.status == status)
            query = filter_tanggal(query, PartnerPay.created)
            if opt_cust != 9999:
                query = query.filter(customer.id == opt_cust)
            if opt_vend != 9999:
                query = query.filter(vendor.id == opt_vend)
            row_table = DataTables(request.GET, query, columns)
            return row_table.output_result()
        elif act == "csv":
            status = 9999
            if 'status' in request.params:
                status = int(request.params['status'])

            query = query_csv(request, status)
            row = query.first()

            if row == None:
                header = [
                    'Nomor_Invoice',
                    'Tanggal',
                    'Nama_Customer',
                    'Nama_Vendor',
                    'Harga_Beli',
                    'Harga_Jual',
                    'Fee',
                    'Status'
                ]
            else:
                header = row.keys()
            rows = []
            for item in query.all():
                rows.append(list(item))

            filename = 'list_payment.csv'
            value = {
                  'header': header,
                  'rows'  : rows,
                }
            return csv_response(request, value, filename)
        elif act == "advice":
            idnya = 0
            if 'id' in request.params:
                idnya = int(request.params['id'])

            row = PartnerPay.query_id(id=idnya).first()
            dat = {
                'tx_id': row.tx_id,
                'invoice_no': row.vend_inv_no
            }

            return payment_advice(dat)

    # @view_config(route_name='api-payment-view',
    #              permission="api-payment-list",
    #              renderer='templates/payment/view.pt')
    # def view_detail(self):
    #     request = self.req
    #     url_dict = request.matchdict
    #     view_id = url_dict['id']
    #     data = PartnerPay.query_id(id=view_id).first()
    #     params = dict(
    #         form=None
    #     )
    #     if data:
    #         customer = '{cust} - ({merc})'.format(cust=data.inv_cust_nm, merc=data.customer.nama)
    #         form_list = (
    #             ('vend_inv_no', data.vend_inv_no or '', 'text'),
    #             ('cust_inv_no', data.cust_inv_no or '', 'text'),
    #             ('tx_id', data.tx_id or '', 'text'),
    #             ('vendor', data.vendor.nama, 'text'),
    #             ('produk', data.produk.nama, 'text'),
    #             # ('id_pel', data.id_pel or '', 'text'),

    #             ('customer', customer, 'text'),
    #             ('cust_addr', data.inv_cust_addr or '', 'text'),
    #             ('cust_phone', data.inv_cust_phone or '', 'text'),
    #             ('cust_email', data.inv_cust_email or '', 'text'),
    #             ('cust_city', data.inv_cust_city or '', 'text'),
    #             ('cust_state', data.inv_cust_state or '', 'text'),
    #             ('cust_pos', data.inv_cust_pos or '', 'text'),
    #             ('cust_country', data.inv_cust_country or '', 'text'),

    #             # ('inv_valid_date', data.description, 'text'),
    #             # ('inv_valid_time', data.description, 'text'),
    #             # ('inv_time_stamp', data.description, 'text'),
    #             # ('inv_cust_va', data.description, 'text'),
    #             #
    #             # ('delivery_addr', data.description, 'text'),
    #             # ('delivery_city', data.description, 'text'),
    #             # ('delivery_country', data.description, 'text'),
    #             # ('delivery_nm', data.description, 'text'),
    #             # ('delivery_phone', data.description, 'text'),
    #             # ('delivery_pos', data.description, 'text'),
    #             # ('delivery_state', data.description, 'text'),
    #             # ('delivery_email', data.description, 'text'),

    #             # ('subtotal', data.subtotal, 'text'),
    #             # ('discount', data.discount, 'text'),
    #             # ('amt_sell', data.amt_sell, 'text'),
    #             ('inquiry', format_json(data.inquiry), 'textarea'),
    #             ('payment', format_json(data.payment), 'textarea'),
    #             ('advice', format_json(data.advice), 'textarea'),
    #             ('notify', format_json(data.notify), 'textarea'),
    #             ('cancel', format_json(data.cancel), 'textarea'),
    #             ('cart', format_json(data.cart), 'textarea'),
    #             # ('notes', data.notes, 'text'),
    #             # ('description', data.description, 'text'),

    #             # ('fee', data.description, 'text'),
    #             # ('instmnt_mon', data.description, 'text'),
    #             # ('instmnt_type', data.description, 'text'),
    #             # ('recurr_opt', data.description, 'text'),

    #             # ('m_ref_no', data.description, 'text'),

    #             # ('notax_amt', data.description, 'text'),
    #             # ('pay_valid_dt', data.description, 'text'),
    #             # ('pay_valid_tm', data.description, 'text'),
    #             #
    #             # ('req_dt', data.description, 'text'),
    #             # ('req_tm', data.description, 'text'),
    #             #
    #             # ('vat', data.description, 'text'),

    #             # ('trans_dt', data.description, 'text'),
    #             # ('trans_tm', data.description, 'text'),
    #             # ('card_no', data.description, 'text'),
    #             # ('callback_url', data.description, 'text'),
    #         )

    #         sm = colander.Schema()
    #         values = {}

    #         for f in form_list:
    #             k = f[0]
    #             v = f[1]
    #             wg = f[2] == 'textarea' and widget.TextAreaWidget(rows=5, css_class="readonly") or\
    #                  widget.TextInputWidget(readonly=True)

    #             sm.add(colander.SchemaNode(
    #                 colander.String(),
    #                 name=k,
    #                 oid=k,
    #                 widget=wg
    #             ))
    #             values.update({k: v})

    #         form = Form(sm)
    #         form.render(values)
    #         params['form'] = form

    #     return dict(params=params)