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
| import json import boto3 from datetime import datetime from decimal import Decimal from shared.database import get_dynamodb_table from shared.auth import verify_token from shared.exceptions import ValidationError, NotFoundError from shared.utils import generate_order_id, send_message_to_queue
def create_order(event, context): """创建订单""" try: token = extract_token_from_headers(event['headers']) user_data = verify_token(token) user_id = user_data['user_id'] body = json.loads(event['body']) items = body.get('items', []) shipping_address = body.get('shipping_address', {}) if not items: raise ValidationError("Order items are required") if not shipping_address: raise ValidationError("Shipping address is required") total_amount = Decimal('0') order_items = [] products_table = get_dynamodb_table('products') for item in items: product_id = item['product_id'] quantity = int(item['quantity']) if quantity <= 0: raise ValidationError(f"Invalid quantity for product {product_id}") product_response = products_table.get_item(Key={'product_id': product_id}) if 'Item' not in product_response: raise ValidationError(f"Product {product_id} not found") product = product_response['Item'] if int(product['stock']) < quantity: raise ValidationError(f"Insufficient stock for product {product['name']}") price = Decimal(str(product['price'])) subtotal = price * quantity total_amount += subtotal order_items.append({ 'product_id': product_id, 'product_name': product['name'], 'price': price, 'quantity': quantity, 'subtotal': subtotal }) order_id = generate_order_id() order_data = { 'order_id': order_id, 'user_id': user_id, 'items': order_items, 'total_amount': total_amount, 'shipping_address': shipping_address, 'status': 'pending', 'created_at': datetime.utcnow().isoformat(), 'updated_at': datetime.utcnow().isoformat() } orders_table = get_dynamodb_table('orders') orders_table.put_item(Item=order_data) message = { 'order_id': order_id, 'action': 'process_order', 'items': [{'product_id': item['product_id'], 'quantity': item['quantity']} for item in order_items] } send_message_to_queue('order-processing-queue', message) response_data = { 'order_id': order_id, 'total_amount': float(total_amount), 'status': 'pending', 'created_at': order_data['created_at'] } return { 'statusCode': 201, 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, 'body': json.dumps(response_data) } except ValidationError as e: return create_error_response(400, str(e)) except Exception as e: print(f"Create order error: {str(e)}") return create_error_response(500, "Internal server error")
def process_order_queue(event, context): """处理订单队列消息""" try: for record in event['Records']: message_body = json.loads(record['body']) order_id = message_body['order_id'] action = message_body['action'] if action == 'process_order': await process_order_payment(order_id, message_body['items']) elif action == 'update_inventory': await update_inventory(message_body['items']) elif action == 'send_notification': await send_order_notification(order_id, message_body['notification_type']) return {'statusCode': 200} except Exception as e: print(f"Process order queue error: {str(e)}") raise e
async def process_order_payment(order_id, items): """处理订单支付""" try: orders_table = get_dynamodb_table('orders') order_response = orders_table.get_item(Key={'order_id': order_id}) if 'Item' not in order_response: raise NotFoundError(f"Order {order_id} not found") order = order_response['Item'] payment_result = await simulate_payment_processing(order) if payment_result['success']: orders_table.update_item( Key={'order_id': order_id}, UpdateExpression='SET #status = :status, payment_id = :payment_id, updated_at = :timestamp', ExpressionAttributeNames={'#status': 'status'}, ExpressionAttributeValues={ ':status': 'paid', ':payment_id': payment_result['payment_id'], ':timestamp': datetime.utcnow().isoformat() } ) for item in items: update_product_stock_internal(item['product_id'], -item['quantity']) notification_message = { 'order_id': order_id, 'action': 'send_notification', 'notification_type': 'payment_success' } send_message_to_queue('order-processing-queue', notification_message) else: orders_table.update_item( Key={'order_id': order_id}, UpdateExpression='SET #status = :status, payment_error = :error, updated_at = :timestamp', ExpressionAttributeNames={'#status': 'status'}, ExpressionAttributeValues={ ':status': 'payment_failed', ':error': payment_result['error'], ':timestamp': datetime.utcnow().isoformat() } ) except Exception as e: print(f"Process order payment error: {str(e)}") raise e
def get_user_orders(event, context): """获取用户订单列表""" try: token = extract_token_from_headers(event['headers']) user_data = verify_token(token) user_id = user_data['user_id'] query_params = event.get('queryStringParameters') or {} limit = int(query_params.get('limit', 20)) offset = query_params.get('offset', '0') orders_table = get_dynamodb_table('orders') response = orders_table.query( IndexName='user-id-index', KeyConditionExpression='user_id = :user_id', ExpressionAttributeValues={':user_id': user_id}, ScanIndexForward=False, Limit=limit, ExclusiveStartKey=json.loads(offset) if offset != '0' else None ) orders = [] for item in response['Items']: order = { 'order_id': item['order_id'], 'total_amount': float(item['total_amount']), 'status': item['status'], 'created_at': item['created_at'], 'updated_at': item.get('updated_at'), 'items_count': len(item['items']) } orders.append(order) next_offset = None if 'LastEvaluatedKey' in response: next_offset = json.dumps(response['LastEvaluatedKey']) return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, 'body': json.dumps({ 'orders': orders, 'next_offset': next_offset, 'count': len(orders) }) } except Exception as e: print(f"Get user orders error: {str(e)}") return create_error_response(500, "Internal server error")
def get_order_detail(event, context): """获取订单详情""" try: token = extract_token_from_headers(event['headers']) user_data = verify_token(token) user_id = user_data['user_id'] order_id = event['pathParameters']['order_id'] orders_table = get_dynamodb_table('orders') response = orders_table.get_item(Key={'order_id': order_id}) if 'Item' not in response: raise NotFoundError("Order not found") order = response['Item'] if order['user_id'] != user_id: raise NotFoundError("Order not found") order_detail = { 'order_id': order['order_id'], 'total_amount': float(order['total_amount']), 'status': order['status'], 'created_at': order['created_at'], 'updated_at': order.get('updated_at'), 'shipping_address': order['shipping_address'], 'items': [ { 'product_id': item['product_id'], 'product_name': item['product_name'], 'price': float(item['price']), 'quantity': int(item['quantity']), 'subtotal': float(item['subtotal']) } for item in order['items'] ], 'payment_id': order.get('payment_id') } return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, 'body': json.dumps(order_detail) } except NotFoundError as e: return create_error_response(404, str(e)) except Exception as e: print(f"Get order detail error: {str(e)}") return create_error_response(500, "Internal server error")
async def simulate_payment_processing(order): """模拟支付处理""" import random import asyncio await asyncio.sleep(2) success = random.random() < 0.9 if success: return { 'success': True, 'payment_id': f"pay_{generate_order_id()}" } else: return { 'success': False, 'error': 'Payment processing failed' }
def update_product_stock_internal(product_id, quantity_change): """内部库存更新""" products_table = get_dynamodb_table('products') try: products_table.update_item( Key={'product_id': product_id}, UpdateExpression='ADD stock :change', ConditionExpression='stock + :change >= :zero', ExpressionAttributeValues={ ':change': quantity_change, ':zero': 0 } ) except products_table.meta.client.exceptions.ConditionalCheckFailedException: print(f"Failed to update stock for product {product_id}: insufficient stock") raise ValidationError("Insufficient stock")
|