def modify_order(conn, users_id, order_id, telephone_id, order_items, shipaddr, billaddr): _modify_order_shipment_detail(conn, order_id, shipaddr, billaddr, telephone_id) shipments = get_shipments_by_order(conn, order_id) shipment_ids = [s['id'] for s in shipments] wwwOrderShipments(conn, order_id, order_items, shipaddr, users_id).update(shipment_ids) return int(order_id)
class BaseShippingListResource(BaseXmlResource): template = "shipping_list.xml" def _on_get(self, req, resp, conn, **kwargs): try: self._order_check(conn) except UserError, e: conn.rollback() logging.error("%s" % str(e), exc_info=True) return {"error": e.code} id_order = req._params.get('id_order') order_status = get_order_status(conn, id_order) order = get_order(conn, id_order) order_create_date = order['confirmation_time'].date() id_user = order['id_user'] id_shipaddr = order['id_shipaddr'] shipping_dest = get_user_dest_addr(conn, id_user, id_shipaddr) shipment_list = get_shipments_by_order(conn, id_order) object_list = [] for shipment in shipment_list: if shipment['status'] == SHIPMENT_STATUS.DELETED: continue id_shipment = shipment['id'] shipment['carriers'] = self._get_supported_services(conn, shipment) shipment['tracking_info'] = self._get_tracking_info(id_shipment) shipment['fee_info'] = self._get_shipping_fee(conn, shipment['id']) shipment['shipping_list'] = self._get_shipping_list( conn, id_shipment) shipment['postage'] = get_shipping_postage(conn, id_shipment) if int(order_status) == ORDER_STATUS.AWAITING_SHIPPING: paid_time = get_shipment_paid_time(conn, id_shipment)['paid_time'] shipment['paid_date'] = paid_time.date() object_list.append(shipment) unpacking_list = self._get_unpacking_shipment(conn, id_order) object_list.extend(unpacking_list) return { 'object_list': object_list, 'order_status': order_status, 'order_create_date': order_create_date, 'shipping_currency': SHIPPING_CURRENCY, 'shipping_weight_unit': SHIPPING_WEIGHT_UNIT, 'shipping_dest': shipping_dest }
def confirm_order(self, req, resp, conn, id_order, id_brand): shipments = get_shipments_by_order(conn, id_order, id_brand) params = [] for s in shipments: update_shipment(conn, s['id'], {'status': SHIPMENT_STATUS.PACKING}) params += stock_req_params(conn, s['id']) success, errmsg = decrease_stock(params) if not success: raise Exception(out_of_stock_errmsg(errmsg)) try: push_order_confirming_event(conn, id_order, id_brand) except Exception, e: logging.error( 'confirmed_event_err: %s, ' 'order_id: %s, ' 'brand: %s', e, id_order, id_brand, exc_info=True)
def push_order_confirmed_event(conn, id_order, id_brand, id_shops=None): id_user, confirmation_time = db_utils.select(conn, "orders", columns=("id_user", "confirmation_time"), where={'id': id_order})[0] user_info = get_user_info(conn, id_user) month, day = confirmation_time.strftime('%b|%d').split('|') params = { 'email': user_info['fo_user_email'], 'service_email': settings.SERVICE_EMAIL, 'id_brand': id_brand, 'id_order': id_order, 'fo_user_name': user_info['fo_user_name'], 'order_created_month': month, 'order_created_day': day, 'order_url': os.path.join(settings.FRONT_ROOT_URI, 'orders/%s' % id_order), } from models.invoice import get_invoice_by_order from models.shipments import get_shipments_by_order shipments = get_shipments_by_order(conn, id_order) spm_dict = dict([(spm['id'], spm) for spm in shipments]) invoices = get_invoice_by_order(conn, id_order) _xslts = [] for iv in invoices: id_shipment = iv['id_shipment'] spm = spm_dict.get(id_shipment) if not spm: continue if str(spm['id_brand']) != id_brand: continue if id_shops and str(spm['id_shop']) not in id_shops: continue _xslts.append(invoice_xslt(iv['invoice_xml'])) params['invoices_xslt'] = ''.join(_xslts) _push_specific_event('USR_ORDER_CONFIRMED', **params)
def get_and_save_invoices(self, conn, req, id_user, id_shipments=None): id_order = req.get_param('order') if not id_order: raise ValidationError("Miss param in request") order = get_order(conn, id_order, id_user=id_user) if order is None: raise ValidationError("Order not exist") # address id_shipaddr = order['id_shipaddr'] dest = get_user_dest_addr(conn, id_user, id_shipaddr) dest = ujson.dumps(dest) # customer user = get_user_profile(conn, id_user) if id_shipments is not None: shipments = get_shipments_by_id(conn, id_shipments) else: shipments = get_shipments_by_order(conn, id_order) invoices = {} for sp in shipments: invoice_xml = self.get_shipment_invoice(conn, dest, user, sp) if invoice_xml is None: continue invoices[sp['id']] = invoice_xml shipments_id = invoices.keys() shipments_id.sort() content = self.gen_invoices_content([ invoices[id_shipment] for id_shipment in shipments_id if invoices.get(id_shipment) ]) return content
def _get_invoices(self, conn, id_order, id_brand, id_shops): try: shipments = get_shipments_by_order(conn, id_order) invoices = get_invoice_by_order(conn, id_order) spm_dict = dict([(spm['id'], spm) for spm in shipments]) content = [] for iv in invoices: id_shipment = iv['id_shipment'] spm = spm_dict.get(id_shipment) if not spm: continue if spm['id_brand'] != id_brand: continue if id_shops and spm['id_shop'] not in id_shops: continue content.append({ 'id': iv['id'], 'id_shipment': iv['id_shipment'], 'html': self.invoice_xslt(iv['invoice_xml']) }) order_iv_status = order_iv_sent_status(conn, id_order, id_brand, id_shops) order_status = get_order_status(conn, id_order) to_sent_qty = iv_to_sent_qty(conn, id_order, id_brand, id_shops) return { 'res': SUCCESS, 'iv_sent_status': order_iv_status, 'iv_to_sent_qty': to_sent_qty, 'order_status': order_status, 'content': content } except Exception, e: conn.rollback() logging.error("get_invoice_server_err: %s", str(e), exc_info=True) return {'res': FAILURE, 'reason': str(e), 'err': "SERVER_ERROR"}
def create_order(conn, users_id, telephone_id, order_items, upc_shop=None, shipaddr=None, billaddr=None, user_info=None, chosen_gifts=None): order_id = _create_order(conn, users_id) _create_order_shipment_detail(conn, order_id, shipaddr, billaddr, telephone_id) sellers = defaultdict(set) id_sales = [] for item in order_items: sale = CachedSale(item['id_sale']).sale item_id = _create_order_item( conn, sale, item['id_variant'], sale.brand.id, upc_shop=upc_shop, barcode=item.get('barcode', None), id_shop=item['id_shop'], id_type=item.get('id_type', None), id_price_type=item.get('id_price_type', None), id_weight_type=item.get('id_weight_type', None)) # populate id_order_item into order params, it will be # used when create shipping list. item['id_order_item'] = item_id id_sales.append(sale.id) _create_order_details(conn, order_id, item_id, item['quantity']) sellers[sale.brand.id].add(item['id_shop']) gevent.spawn(gen_bought_history, users_id, id_sales) _log_order(conn, users_id, order_id, sellers) if upc_shop is None: wwwOrderShipments(conn, order_id, order_items, shipaddr, users_id).create() else: posOrderShipments(conn, order_id, order_items, None, users_id).create() up_order_log(conn, order_id, sellers) if not _order_need_confirmation(conn, order_id): params = [] shipments = get_shipments_by_order(conn, order_id) for s in shipments: params += stock_req_params(conn, s['id']) success, errmsg = decrease_stock(params) if not success: raise UserError(E_C.OUT_OF_STOCK[0], out_of_stock_errmsg(errmsg)) for brand, shops in sellers.iteritems(): try: if _order_need_confirmation(conn, order_id, brand): push_order_confirming_event(conn, order_id, brand) except Exception, e: logging.error( 'confirming_event_err: %s, ' 'order_id: %s, ' 'brand: %s', e, order_id, brand, exc_info=True)
def _calc_discount_result(conn, id_coupon, coupon, id_order, chosen_gifts, all_order_items, match_order_items): results = db_utils.select_dict(conn, 'coupon_discount', 'id_coupon', where={ 'id_coupon': id_coupon }).values() if results: discount_value = results[0] if discount_value[ 'discount_type'] == COUPON_DISCOUNT_APPLIES.VALUE_CHEAPEST: min_price_item = min_price = match_order_items[0] for o_item in match_order_items[1:]: if 0 < o_item['price'] < min_price_item['price']: min_price_item = o_item for o_item in all_order_items: if o_item == min_price_item: o_item['discount'] = _calc_discount( o_item['price'], discount_value['discount']) break elif discount_value[ 'discount_type'] == COUPON_DISCOUNT_APPLIES.VALUE_MATCHING: for o_item in all_order_items: if o_item in match_order_items and o_item['price'] > 0: o_item['discount'] = _calc_discount( o_item['price'], discount_value['discount']) elif discount_value[ 'discount_type'] == COUPON_DISCOUNT_APPLIES.VALUE_INVOICED: for o_item in all_order_items: o_item['discount'] = _calc_discount(o_item['price'], discount_value['discount']) elif discount_value[ 'discount_type'] == COUPON_DISCOUNT_APPLIES.VALUE_SHIPPING: shipments = get_shipments_by_order(conn, id_order) for shipment in shipments: fee = get_shipping_fee(conn, shipment['id']) update_values = { 'shipping_fee': 0, 'handling_fee': 0, 'details': ujson.dumps({ 'free_fee': True, 'shipping_fee': fee['shipping_fee'] or 0, 'handling_fee': fee['handling_fee'] or 0, 'manufacturer_promo': coupon['manufacturer'], }) } update_shipping_fee(conn, shipment['id'], update_values) for o_item in all_order_items: if 'discount' not in o_item: continue _copy_fake_order_item(conn, id_order, o_item['item_id'], { 'price': -o_item['discount'], 'description': coupon['description'], 'weight': 0, 'barcode': '', 'external_id': '', 'name': '', 'item_detail': '{"name": ""}', 'type_name': '', 'modified_by_coupon': id_coupon, }, quantity=o_item['quantity']) else: gift_values = db_utils.select(conn, 'coupon_gift', columns=('id_sale', 'quantity'), where={'id_coupon': id_coupon}) chosen_gifts = get_chosen_gifts(conn, id_coupon, chosen_gifts) if chosen_gifts: for id_sale, quantity in chosen_gifts: _create_free_order_item(conn, id_order, id_sale, match_order_items[0]['item_id'], { 'price': 0, 'modified_by_coupon': id_coupon }, quantity=quantity)
def _calc_currency_credit(conn, id_coupon, coupon, id_order, id_user, match_order_items): credit_value = db_utils.select_dict(conn, 'store_credit', 'id_coupon', where={ 'id_coupon': id_coupon }).values()[0] if credit_value['redeemed_in_full']: raise ValidationError('COUPON_ERR_REDEEMED_FULL') redeemed_amount = db_utils.query( conn, "select COALESCE(sum(redeemed_amount), 0) from store_credit_redeemed " "where id_coupon=%s and order_status in (%s, %s) ", [ id_coupon, ORDER_STATUS_FOR_COUPON.PENDING, ORDER_STATUS_FOR_COUPON.PAID ])[0][0] left_amount = credit_value['amount'] - redeemed_amount total_redeemable_amount = 0 match_id_items = [item['item_id'] for item in match_order_items] shipments = get_shipments_by_order(conn, id_order) for shipment in shipments: if left_amount <= 0: continue shipping_list = get_shipping_list(conn, shipment['id']) price = sum([ o['price'] * o['quantity'] for o in shipping_list if o['id_item'] in match_id_items and o['currency'] == credit_value['currency'] ]) redeemed_amount = abs( sum([ o['price'] * o['quantity'] for o in shipping_list if o['id_sale'] == 0 and o['currency'] == credit_value['currency'] ])) taxes = get_apply_before_coupons_taxes(conn, id_user, shipment['id_shop'], shipping_list[0]['id_sale']) price_with_tax = price + sum( [(price + redeemed_amount) * float(tax['rate']) / 100.0 for tax in taxes]) redeemable_amount = min(price_with_tax, left_amount) fake_item = { 'id_sale': 0, 'id_variant': 0, 'id_brand': match_order_items[0]['brand_id'], 'id_shop': match_order_items[0]['shop_id'], 'name': '', 'price': -min(price, left_amount), 'currency': credit_value['currency'], 'description': coupon['description'], 'weight': 0, 'weight_unit': match_order_items[0]['weight_unit'], 'barcode': '', 'external_id': '', 'item_detail': ujson.dumps({ 'name': '', 'redeemable_credits': redeemable_amount, }), 'type_name': '', 'modified_by_coupon': id_coupon, } _create_fake_order_item(conn, id_order, match_id_items[0], fake_item) left_amount -= redeemable_amount total_redeemable_amount += redeemable_amount return to_round(total_redeemable_amount), credit_value['currency']
def _on_post(self, req, resp, conn, **kwargs): try: params = req.stream.read() params = ujson.loads(params) req._params.update(params) id_order = params.get('order') id_shipments = params.get('shipment') or '[]' id_brand = params.get('brand') id_shops = params.get('shops') if not id_brand or not id_shops or not id_order: raise ValidationError("iv_send_req_err: miss params") id_brand = int(id_brand) id_shops = [int(id_shop) for id_shop in ujson.loads(id_shops)] id_shipments = [ int(id_spm) for id_spm in ujson.loads(id_shipments) ] orig_id_spms = id_shipments shipments = get_shipments_by_order(conn, id_order) shipments = dict([(sp['id'], sp) for sp in shipments]) valid_shipments = shipments.keys() order = get_order(conn, id_order) if id_shipments: invalid_shipments = set(id_shipments) - set(valid_shipments) if len(invalid_shipments) > 0: raise ValidationError("shipments %s not belongs to " "order %s" % (invalid_shipments, id_order)) for id_spm in id_shipments: spm_brand = shipments[id_spm]['id_brand'] spm_shop = shipments[id_spm]['id_shop'] if spm_brand != id_brand: raise ValidationError( "iv_send_req_err: spm brand %s is not " "same with given %s" % (spm_brand, id_brand)) if spm_shop not in id_shops: raise ValidationError( "iv_send_req_err: spm shop %s is not " "in given shops %s" % (spm_shop, id_shops)) else: for id_spm, spm in shipments.iteritems(): if (spm['id_brand'] == id_brand and spm['id_shop'] in id_shops): id_shipments.append(id_spm) self.get_and_save_invoices(conn, req, order['id_user'], id_shipments=id_shipments) order_invoices = get_invoice_by_order(conn, id_order) invoices = dict([(oi['id_shipment'], oi) for oi in order_invoices]) users_mail = get_user_email(conn, order['id_user']) if orig_id_spms: for id_spm in id_shipments: if invoices.get(id_spm) is None: continue content = invoices[id_spm]['invoice_xml'] content_html = self.invoice_xslt(content) send_html_email(users_mail, INVOICE_MAIL_SUB, content_html) else: content_list = [] for id_spm in id_shipments: if invoices.get(id_spm) is None: continue content = invoices[id_spm]['invoice_xml'] content = self.parse_invoices_content(content) content_list.append(content) content = self.unitary_content(content_list) content_html = self.invoice_xslt(content) send_html_email(users_mail, INVOICE_MAIL_SUB, content_html) order_iv_status = order_iv_sent_status(conn, id_order, id_brand, id_shops) return {'res': SUCCESS, 'order_iv_status': order_iv_status} except ValidationError, e: conn.rollback() logging.error("send_invoice_invalidate: %s", str(e), exc_info=True) return {'res': FAILURE, 'err': str(e)}