Beispiel #1
0
def save_currency(currency_id):
    ''' Creates or modifies existing currency '''
    payload = request.get_json()
    if not payload:
        abort(Response('No data was provided', status=400))

    if payload.get('rate'):
        try:
            float(payload['rate'])
        except:
            abort(Response('Not number', status=400))

    if currency_id is None:
        currency = Currency()
        currency.when_created = datetime.now()
        db.session.add(currency)
    else:
        currency = Currency.query.get(currency_id)
        if not currency:
            abort(
                Response(f'No currency <{currency_id}> was found', status=400))
    if 'rate' in payload.keys():
        today_rate = currency.history.filter_by(
            when_created=datetime.now().date()).first()
        if today_rate is None:
            currency.history.append(
                CurrencyHistoryEntry(code=currency.code,
                                     rate=float(payload['rate']),
                                     when_created=datetime.now().date()))
        else:
            today_rate.rate = float(payload['rate'])
    modify_object(currency, payload, ['code', 'name', 'rate'])

    db.session.commit()
    return jsonify(currency.to_dict())
Beispiel #2
0
def admin_save_order(order_id):
    '''
    Updates existing order
    Payload is provided in JSON
    '''
    logger = current_app.logger.getChild('admin_save_order')
    order_input = request.get_json()
    order = Order.query.get(order_id)
    if not order:
        abort(Response(f'No order {order_id} was found', status=404))
    with OrderEditValidator(request) as validator:
        if not validator.validate():
            return jsonify({
                'data': [],
                'error':
                "Couldn't edit an order",
                'fieldErrors': [{
                    'name': message.split(':')[0],
                    'status': message.split(':')[1]
                } for message in validator.errors]
            })
    logger.info('Modifying order %s by %s with data: %s', order_id,
                current_user, order_input)
    modify_object(order, order_input, ['tracking_id', 'tracking_url'])
    if order_input.get('status'):
        try:
            order.set_status(order_input['status'], current_user)
        except UnfinishedOrderError as ex:
            abort(Response(str(ex), status=409))

    db.session.commit()
    return jsonify(order.to_dict())
Beispiel #3
0
def save_product(product_id):
    '''Saves updates in product or creates new product'''
    payload = request.get_json()
    if product_id is None:
        if not payload.get('id'):
            abort(Response('No product ID is provided', status=400))
        else:
            product_id = payload['id']

    product = Product.query.get(product_id)
    if not product:
        product = Product()
        product.id = product_id
        db.session.add(product)
    if 'shipping' in payload.keys():
        product.available_shipping = []
        if len(payload['shipping']) < Shipping.query.count():
            product.available_shipping = \
                Shipping.query.filter(Shipping.id.in_(payload['shipping']))
    editable_attributes = [
        'name', 'name_english', 'name_russian', 'price', 'points', 'weight',
        'available', 'separate_shipping', 'synchronize', 'purchase', 'color'
    ]
    modify_object(product, payload, editable_attributes)

    db.session.commit()

    return jsonify(product.to_dict(details=True))
Beispiel #4
0
def admin_update_notification(notification_id):
    notification = Notification.query.get(notification_id)
    if notification is None:
        return jsonify(
            {'error': f'No notification is found by ID {notification_id}'})
    payload = request.get_json()
    if payload is None:
        return jsonify({'error': 'No payload'})
    modify_object(notification, payload, ['short_desc', 'long_desc'])
    db.session.commit()
    return jsonify({'data': notification.to_dict()})
Beispiel #5
0
def user_save_payment(payment_id):
    '''Saves updates in payment'''
    payment = Payment.query.get(payment_id)
    if not payment:
        abort(404)
    if not payment.is_editable():
        abort(
            Response(f"Can't update payment in state <{payment.status}>",
                     status=409))
    with PaymentValidator(request) as validator:
        if not validator.validate():
            abort(jsonify(validator.errors))
        # return jsonify({
        #     'id': payment_id,
        #     'data': [payment.to_dict()],
        #     'cancelled': [payment_id],
        #     'error': "Couldn't update a Payment",
        #     'fieldErrors': [{'name': message.split(':')[0], 'status': message.split(':')[1]}
        #                     for message in payload.errors]
        # })
    payload = request.get_json()
    if current_user.has_role('admin'):
        modify_object(payment, payload, [
            'additional_info', 'amount_sent_krw', 'amount_sent_original',
            'amount_received_krw', 'currency_code', 'status', 'user_id'
        ])
        if payload.get('payment_method') \
            and payment.payment_method_id != payload['payment_method']['id']:
            payment.payment_method_id = payload['payment_method']['id']
            payment.when_changed = datetime.now()
        evidences = {e.path: e for e in payment.evidences}
        payment.evidences = []
        for evidence in payload.get('evidences'):
            if evidence.get('id'):
                payment.evidences.append(
                    File(file_name=evidence['file_name'],
                         path=_move_uploaded_file(evidence['id'])))
            elif evidence.get('path'):
                payment.evidences.append(evidences[evidence['path']])
        # removed_evidences = payment.evidences.filter(
        #     File.path.notin_(remaining_evidences))
        # for evidence in removed_evidences:
        #     payment.evidences.filter_by(id=evidence.id).delete()
        #     db.session.delete(evidence)
        if payload.get('orders'):
            payment.orders = Order.query.filter(Order.id.in_(
                payload['orders']))
    else:
        modify_object(payment, payload, ['status'])

    payment.changed_by = current_user
    db.session.commit()
    return jsonify({'data': [payment.to_dict()]})
Beispiel #6
0
def save_payment_method(payment_method_id):
    payment_method = PaymentMethod.query.get(payment_method_id)
    if payment_method_id:
        if not payment_method:
            abort(
                Response(f"Payment method <{payment_method_id}> wasn't found",
                         status=404))
    else:
        payment_method = PaymentMethod()
        db.session.add(payment_method)
    payload = request.get_json()
    if not payload:
        abort(Response("No payment method details are provided", status=400))
    modify_object(payment_method, payload,
                  ['name', 'payee_id', 'instructions'])
    db.session.commit()
    return jsonify({'data': [payment_method.to_dict()]})
Beispiel #7
0
def admin_save_subcustomer(subcustomer_id):
    payload = request.get_json()
    if payload is None:
        abort(Response("No customer data is provided", status=400))
    subcustomer = Subcustomer.query.get(subcustomer_id)
    if subcustomer is None:
        abort(Response(f"No customer <{subcustomer_id}> is found", status=404))

    if payload.get('username') and \
        Subcustomer.query.filter_by(username=payload['username']).count() > 0:
        abort(
            Response(
                f"Subcustomer with username <{payload['username']}> already exists",
                status=409))
    modify_object(subcustomer, payload,
                  ['name', 'username', 'password', 'in_network'])
    db.session.commit()
    return jsonify(subcustomer.to_dict())
Beispiel #8
0
def save_user(user_id):
    with UserEditValidator(request) as validator:
        if not validator.validate():
            return jsonify({
                'data': [],
                'error':
                "Couldn't update a user",
                'fieldErrors': [{
                    'name': message.split(':')[0],
                    'status': message.split(':')[1]
                } for message in validator.errors]
            }), 400
    user = User.query.get(user_id)
    payload = request.get_json()
    modify_object(user, payload,
                  ['username', 'email', 'phone', 'atomy_id', 'enabled'])
    if 'password' in payload.keys() and payload['password'] != '':
        user.set_password(payload['password'])
    user.when_changed = datetime.now()
    db.session.commit()
    return jsonify({'data': [user.to_dict()]})
Beispiel #9
0
def update_purchase_order(po_id):
    po = PurchaseOrder.query.get(po_id)
    if po is None:
        abort(Response("No purchase order <{po_id}> was found", status=404))

    from ..jobs import post_purchase_orders, update_purchase_orders_status
    try:
        if request.values.get('action') == 'repost':
            po.reset_status()
            db.session.commit()
            task = post_purchase_orders.apply_async(kwargs={'po_id': po.id},
                                                    retry=False,
                                                    connect_timeout=1)
            # post_purchase_orders(po.id)
            current_app.logger.info("Post purchase orders task ID is %s",
                                    task.id)
            result = jsonify({'data': [po.to_dict()]})
        elif request.values.get('action') == 'update_status':
            current_app.logger.info("Updating POs status")
            task = update_purchase_orders_status.apply_async(
                kwargs={'po_id': po_id}, retry=False, connect_timeout=1)
            current_app.logger.info("Update POs status task ID is %s", task.id)
            result = jsonify({'data': [po.to_dict()]})
        else:
            if not po.is_editable():
                return jsonify({
                    'data':
                    po.to_dict(),
                    'error':
                    f"The purchase order &lt;{po.id}&gt; isn't in editable state"
                })
            editable_attributes = [
                'payment_account', 'purchase_date', 'status', 'vendor',
                'vendor_po_id'
            ]
            po = modify_object(po, request.get_json(), editable_attributes)
            result = jsonify({'data': [po.to_dict()]})
    except:  # Exception as ex:
        current_app.logger.exception("Couldn't update PO %s", po_id)
        abort(Response(po_id, 500))
    db.session.commit()
    return result