async def handle_money_transfer(*args, **kwargs):
    req_data, kkt_info = kwargs['valid_schema_data'], kwargs[
        'opened_port_info']
    cashbox = Cashbox.box()
    cashier_name = req_data['cashier_name']
    cashier_id = req_data['cashier_id']
    amount = req_data['amount']
    pennies = int(amount * 100)
    doc_type = kwargs['document_type']
    paygate_url = kwargs['paygate_url']

    kkt_result = KKTDevice.insert_remove_operation(cashier_name, pennies,
                                                   doc_type)

    data_to_db = {
        'cashier_id': cashier_id,
        'cashier_name': cashier_name,
        'amount': amount,
        'document_type': doc_type
    }
    operation, errs = CashOperationSchema().load({
        **kkt_info,
        **kkt_result,
        **data_to_db
    })
    cashbox.add_cash_operation_to_shift(operation)
    cashbox.update_shift_money_counter(doc_type, amount)
    data_to_paygate = CashOperationSchema(
        only=['cashID', 'amount']).dump(operation).data
    data_to_paygate.update({'url': paygate_url})
    cashbox.save_paygate_data_for_send(data_to_paygate)
Exemple #2
0
async def open_new_shift(*args, **kwargs):
    cashbox = Cashbox.box()
    req_data, kkt_info = kwargs['valid_schema_data'], kwargs[
        'opened_port_info']
    cashier_name, cashier_id = req_data['cashier_name'], req_data['cashier_id']
    open_shift_data = KKTDevice.open_shift(cashbox.cash_number, cashier_name)
    data_to_db = {
        'cashier_name': cashier_name,
        'cashier_id': cashier_id,
        'shop_number': cashbox.shop,
        'project_number': cashbox.project_number,
        'system_id': System.get_sys_id(),
        'cash_number': cashbox.cash_number,
        'cash_name': cashbox.cash_name
    }
    shift, errs = OpenShiftSchema().load({
        **kkt_info,
        **open_shift_data,
        **data_to_db
    })
    cashbox.set_current_shift(shift)
    data_to_paygate = OpenShiftSchema.get_data_for_paygate(shift)
    data_to_paygate.update({'url': PaygateURLs.open_shift})
    cashbox.save_paygate_data_for_send(data_to_paygate)
    return {}
        async def wrapper(*args, **kwargs):
            cb = Cashbox.box()
            is_opened_fiscal_shift = kwargs['opened_port_info'][
                'is_open_shift']
            current_fiscal_shift_number = kwargs['opened_port_info'][
                'shift_number']
            actual_fiscal_device_number = kwargs['opened_port_info'][
                'fn_number']
            current_fiscal_device_number_in_db = cb.cash_id
            current_shift_in_db = cb.current_opened_shift

            if current_fiscal_device_number_in_db != actual_fiscal_device_number:
                raise CashboxException(data=ERR_IF_FISCAL_ID_NOT_SYNCED)
            if skip_shift_check:
                return await func(*args, **kwargs)
            if is_opened_fiscal_shift:
                if current_shift_in_db:
                    check_current_shift_is_expired(current_shift_in_db)
                    if current_shift_in_db.shiftNumber != current_fiscal_shift_number:
                        raise CashboxException(
                            data=ERR_SHIFT_NUMBER_NOT_SYNCED)
                else:
                    # Экстренное закрытие смены
                    urgent_close_shift(current_fiscal_device_number_in_db, cb)
                    KKTDevice.force_close_shift()
                    msg = f'{ERR_FISCAL_SHIFT_OPENED_BUT_NOT_IN_DB}. ' \
                          f'Смена закрыта принудительно. ' \
                          f'Теперь откройте смену'
                    raise CashboxException(data=msg)
            else:
                if current_shift_in_db:
                    # Экстренное закрытие смены
                    urgent_close_shift(current_fiscal_device_number_in_db, cb)
                    cb.current_opened_shift = None
                    cb.save()
                    raise CashboxException(
                        data=ERR_DB_SHIFT_OPENED_BUT_NOT_IN_FISCAL)
            return await func(*args, **kwargs)
Exemple #4
0
async def return_order(*args, **kwargs):
    req_data, kkt_info = kwargs['valid_schema_data'], kwargs[
        'opened_port_info']

    cashier_name = req_data['cashier_name']
    cashier_id = req_data['cashier_id']
    order_uuid = req_data['internal_order_uuid']
    doc_type = DocumentTypes.RETURN.value
    cashbox = Cashbox.box()
    order = Order.objects(clientOrderID=order_uuid).first()

    if not order:
        msg = 'Нет такого заказа'
        raise CashboxException(data=msg)

    if order.returned:
        msg = 'Этот заказ уже был возвращен'
        raise CashboxException(data=msg)

    order_dict = OrderSchema().dump(order).data
    kkt_kwargs = {
        'cashier_name': cashier_name,
        'document_type': doc_type,
        'payment_type': order_dict['payType'],
        'wares': order_dict['wares'],
        'amount_entered': order_dict['amount_with_discount'],
        'pay_link': order_dict['payLink'],
        'order_prefix': order_dict['order_prefix']
    }

    canceled_order = KKTDevice.handle_order(**kkt_kwargs)

    if PaymentChoices.CASH.value == kkt_kwargs['payment_type']:
        cashbox.update_shift_money_counter(DocumentTypes.RETURN,
                                           order_dict['amount_with_discount'])

    order.returned = True
    order.return_cashier_name = cashier_name
    order.return_cashier_id = cashier_id
    order.return_date = canceled_order['datetime']
    order.save().reload()

    to_paygate = PaygateOrderSchema(
        only=['clientOrderID', 'cashID', 'checkNumber']).dump(order).data
    to_paygate.update({'creation_date': canceled_order['datetime']})
    to_paygate.update({'proj': cashbox.project_number})
    to_paygate.update({'url': PaygateURLs.cancel_order})
    cashbox.save_paygate_data_for_send(to_paygate)
    return {}
Exemple #5
0
async def close_current_shift(*args, **kwargs):
    cashbox: Cashbox = Cashbox.box()
    req_data, kkt_info = kwargs['valid_schema_data'], kwargs[
        'opened_port_info']
    cashier_name, cashier_id = req_data['cashier_name'], req_data['cashier_id']
    close_shift_data = KKTDevice.close_shift(cashier_name)
    data_to_db = {'cashier_name': cashier_name, 'cashier_id': cashier_id}
    closed_shift, errs = CloseShiftSchema().load({
        **kkt_info,
        **close_shift_data,
        **data_to_db
    })
    cashbox.close_shift(closed_shift)
    data_to_paygate = CloseShiftSchema.get_data_for_paygate(closed_shift)
    data_to_paygate.update({'url': PaygateURLs.close_shift})
    cashbox.save_paygate_data_for_send(data_to_paygate)
    return {}
Exemple #6
0
async def partial_return(*args, **kwargs):
    cashbox = Cashbox.box()
    kkt_info = kwargs['opened_port_info']
    data = kwargs['valid_schema_data']
    order_id = data['internal_order_uuid']
    doc_type = DocumentTypes.RETURN.value
    data_for_checkstatus = {
        'proj': cashbox.project_number,
        'clientOrderID': order_id
    }
    checkstatus_url = CS['paygateAddress'] + PaygateURLs.check_order_status
    return_part_url = CS['paygateAddress'] + PaygateURLs.refund_part
    checkstatus = await request_to_paygate(checkstatus_url, 'POST',
                                           data_for_checkstatus)

    # print('| chekstatus response -> ', checkstatus)

    if checkstatus['orderStatus'] == 'cancelled':
        msg = 'Этот заказ уже был отменён'
        to_log = msg + f'\nОтвет с платежного шлюза: {checkstatus}'
        raise CashboxException(data=msg, to_logging=to_log)

    valid_sum = checkstatus['confirmedSum']

    _wares = []
    total_wares_sum = 0

    for ware in data['wares']:
        total_wares_sum += ware['priceDiscount'] * ware['quantity']
        _wares.append({
            'name': ware['name'],
            'price': ware['priceDiscount'],
            'priceDiscount': ware['priceDiscount'],
            'barcode': ware['barcode'],
            'tax_number': ware['tax_number'],
            'quantity': ware['quantity'],
            'discount': 0,
            'posNumber': ware['posNumber']
        })
    total_wares_sum = round_half_down(total_wares_sum, 2)

    # print('total wares sum ', total_wares_sum, 'valid sum ', valid_sum)
    if total_wares_sum > valid_sum:
        msg = 'Сумма переданых товаров превышает оставшуюся сумму заказа!'
        to_log = msg + f'\nСумма товаров: {total_wares_sum} \nСумма заказа в paygate: {valid_sum}'
        raise CashboxException(data=msg, to_logging=to_log)

    to_kkt = {
        'total_wares_sum': total_wares_sum,
        'cashier_name': data['cashier_name'],
        'payment_type': data['payment_type'],
        'document_type': doc_type,
        'amount_entered': data['total_price_with_discount'],
        'pay_link': data['payment_link'],
        'wares': _wares
    }

    result = KKTDevice.handle_order(**to_kkt)

    # pp('formatted info!!!')
    # pp(result)

    to_paygate = {
        'clientOrderID': order_id,
        'proj': cashbox.project_number,
        'wares': _wares,
        'checkNumber': int(result['check_number']),
        'cashID': kkt_info['fn_number'],
        'refundAmount': result['transaction_sum']
    }

    try:
        content = await request_to_paygate(return_part_url, 'POST', to_paygate)
    except CashboxException as exc:
        to_kkt['document_type'] = DocumentTypes.PAYMENT.value
        # TODO: Что-нибудь придумать с этим кейсом. Пока что это не работает должным образом
        KKTDevice.handle_order(**to_kkt)
        raise CashboxException(data=exc.data['errors'], to_logging=exc.data)

    # print('| refund_part response -> ', content)

    return {'actual_order_price': content.get('confirmedSum', 0)}
Exemple #7
0
async def create_order(*args, **kwargs):
    cashbox = Cashbox.box()
    # raise CashboxException(data='Holy Shield')
    if not cashbox.cash_character:
        msg = 'Символ кассы отсутствует. Зарегистрируйте'
        raise CashboxException(data=msg)

    req_data, kkt_info = kwargs['valid_schema_data'], kwargs[
        'opened_port_info']
    cashier_name = req_data['cashier_name']
    cashier_id = req_data['cashier_id']
    payment_type = req_data['payment_type']
    document_type = DocumentTypes.PAYMENT.value
    amount_entered = req_data['amount_entered']
    wares = req_data['wares']
    character = cashbox.cash_character
    real_money = False
    order_prefix = f'{character}-'
    order_number = cashbox.get_shift_order_number()

    if payment_type == PaymentChoices.CASH:
        wares = find_and_modify_one_ware_with_discount(wares)
        real_money = True
    elif payment_type == PaymentChoices.NON_CASH:
        amount_entered = 0

    wares = _build_wares(wares)

    kkt_kwargs = {
        'cashier_name': cashier_name,
        'payment_type': payment_type,
        'document_type': document_type,
        'order_prefix': order_prefix,
        'order_number': order_number,
        'amount_entered': amount_entered,
        'wares': wares
    }
    created_order = KKTDevice.handle_order(**kkt_kwargs)

    cashbox.modify_shift_order_number()
    data_to_db = {
        'cashier_name': created_order['cashier_name'],
        'cashier_id': cashier_id,
        'clientOrderID': generate_internal_order_id(),
        'amount': created_order['total_without_discount'],
        'amount_with_discount': created_order['transaction_sum'],
        'creation_date': created_order['datetime'],
        'cashID': cashbox.cash_id,
        'checkNumber': get_cheque_number(created_order['check_number']),
        'order_number': created_order['order_num'],
        'doc_number': created_order['doc_number'],
        'cardHolder': created_order.get('cardholder_name', ''),
        'pan': created_order.get('pan_card', ''),
        'payLink': created_order.get('rrn', ''),
        'payType': payment_type,
        'paid': 1,
    }

    if real_money:
        cashbox.update_shift_money_counter(DocumentTypes.PAYMENT,
                                           created_order['transaction_sum'])

    # data_to_db.update({'wares': _build_wares(wares)})
    order, errs = OrderSchema().load({**kkt_kwargs, **data_to_db})
    pp(errs)
    to_paygate, _errs = PaygateOrderSchema().dump(order)
    to_paygate.update({'amount': data_to_db['amount_with_discount']})
    to_paygate.update({'proj': cashbox.project_number})
    to_paygate.update({'url': PaygateURLs.new_order})

    pp('to paygate')
    pp(to_paygate)
    cashbox.add_order(order)
    cashbox.save_paygate_data_for_send(to_paygate)

    to_print = {
        'pref': order_prefix,
        'num': data_to_db['order_number'],
        'wares': wares
    }
    await print_to_secondary_printer(to_print)

    to_response, errs = ConvertToResponseCreateOrder().load({
        'device_id':
        System.get_sys_id(),
        **kkt_kwargs,
        **data_to_db
    })
    return to_response
 async def wrapper(*args, **kwargs):
     opened_port = KKTDevice.open_comport()
     kwargs.update({'opened_port_info': opened_port})
     result = await func(*args, **kwargs)
     KKTDevice.close_port()
     return result