The log/narrate naming test: every output we can share ====================================================== Models: Claude Opus 5.5 and Claude Haiku 5.5. Each run was a fresh Claude Code session (claude -p) started in an empty folder, with no tools, no skills, no MCP servers, no project files and the system prompt "You are a helpful assistant." Prompts for the same code differ only in the method name: ctx.log, ctx.narrate, ctx.breadcrumb or ctx.zorp (a made-up word). 40 runs per word per model. Part 1 is the small order processor. Part 2 is a made-up contact sync with a similar shape to our automations, whose own outputs stay private. PART 1: THE ORDER PROCESSOR =========================== PROMPT (shown with ctx.log) --------------------------- Do not read, search or open any files, and do not use any tools. Answer from this message alone. Here is a Python function. The context object `ctx` has one method for recording what happens during a run: `ctx.log(message: str) -> None`. def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: if order.allow_partial: order.items = [i for i in order.items if i not in missing] else: return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: quote = carrier.fallback_quote(order.items) if quote is None: return Result.NO_SHIPPING label = carrier.buy_label(quote) return Result.SHIPPED Add calls to `ctx.log` at the decision points in this function. Reply with only the complete updated function in one Python code block, and nothing else. Claude Opus 5.5, ctx.log (order processor) ========================================== --- run 1 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Insufficient inventory for SKUs {missing_skus}; partial allowed, " f"proceeding with {len(order.items)} remaining item(s)" ) else: ctx.log( f"Insufficient inventory for SKUs {missing_skus}; partial not allowed, " f"returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 2 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; requesting fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 3 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 4 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 5 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 6 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 7 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address ctx.log(f"Processing order with {len(order.items) if order.items else 0} item(s)") if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 8 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 9 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 10 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 11 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(i.sku for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 12 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 13 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment allowed, removing them" ) order.items = [i for i in order.items if i not in missing] ctx.log(f"{len(order.items)} item(s) remain after removing unavailable items") else: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote also unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Obtained fallback shipping quote") else: ctx.log("Obtained primary shipping quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 14 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment allowed, removing them from the order" ) order.items = [i for i in order.items if i not in missing] ctx.log(f"{len(order.items)} item(s) remain after removing unavailable items") else: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 15 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 16 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Partial fulfillment allowed; proceeding with {len(order.items)} in-stock item(s)" ) else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Obtained fallback shipping quote") else: ctx.log("Obtained primary shipping quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 17 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Insufficient inventory for SKUs [{missing_skus}]; partial fulfillment allowed, " f"continuing with {len(order.items)} item(s)" ) else: ctx.log( f"Insufficient inventory for SKUs [{missing_skus}]; partial fulfillment not allowed, " f"returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 18 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 19 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; proceeding with {len(order.items)} remaining item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 20 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Insufficient inventory for SKUs [{missing_skus}]; partial allowed, " f"continuing with {len(order.items)} remaining item(s)" ) else: ctx.log( f"Insufficient inventory for SKUs [{missing_skus}]; partial not allowed, " f"returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 21 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] ctx.log(f"Proceeding with {len(order.items)} remaining item(s)") else: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 22 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"process_order: processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.log(f"process_order: insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"process_order: partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("process_order: fallback quote obtained") else: ctx.log("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 23 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(i.sku for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 24 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address ctx.log(f"Processing order with {len(order.items)} item(s)") if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 25 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 26 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 27 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(i.sku for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 28 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 29 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Obtained fallback shipping quote") else: ctx.log("Obtained primary shipping quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 30 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(i.sku for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 31 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment allowed, continuing with {len(order.items)} item(s)" ) else: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 32 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment allowed, continuing with {len(order.items)} item(s)" ) else: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 33 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment allowed, removing them from order" ) order.items = [i for i in order.items if i not in missing] ctx.log(f"{len(order.items)} item(s) remain after removing unavailable items") else: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Obtained fallback shipping quote") else: ctx.log("Obtained primary shipping quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 34 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log( f"Insufficient inventory for SKUs [{missing_skus}]; partial allowed, " f"removed {len(missing)} item(s), {len(order.items)} item(s) remaining" ) else: ctx.log( f"Insufficient inventory for SKUs [{missing_skus}]; partial not allowed, " f"returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Obtained fallback shipping quote") else: ctx.log("Obtained primary shipping quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 35 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 36 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment allowed, removing them" ) order.items = [i for i in order.items if i not in missing] ctx.log(f"Continuing with {len(order.items)} remaining item(s)") else: ctx.log( f"Insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " f"partial fulfillment not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.log(f"All {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 37 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 38 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 39 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 40 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY ctx.log(f"Processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(i.sku for i in missing) ctx.log(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED Claude Opus 5.5, ctx.narrate (order processor) ============================================== --- run 1 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) have insufficient stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 2 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item line(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate( f"Insufficient inventory for {len(missing)} item line(s): {missing_skus}." ) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} item line(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Obtained fallback shipping quote.") else: ctx.narrate("Obtained primary shipping quote.") label = carrier.buy_label(quote) ctx.narrate("Purchased shipping label; returning SHIPPED.") return Result.SHIPPED --- run 3 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Order has {len(order.items)} item(s); checking inventory.") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) have insufficient stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the shipping address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained for the shipping address.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 4 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Order has {len(order.items)} item(s); checking inventory.") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 5 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate( f"Insufficient inventory for {len(missing)} item(s): {missing_skus}." ) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with " f"{len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 6 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) lack sufficient stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Obtained fallback shipping quote.") else: ctx.narrate("Obtained carrier shipping quote.") label = carrier.buy_label(quote) ctx.narrate("Purchased shipping label; returning SHIPPED.") return Result.SHIPPED --- run 7 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the customer address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 8 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Order has {len(order.items)} line item(s); checking inventory.") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 9 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item line(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item line(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} item line(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the customer address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 10 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} line item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} line item(s) have insufficient stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} line item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All line items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the shipping address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 11 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Order has {len(order.items)} item(s); checking inventory.") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) lack sufficient stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped missing items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no address-based quote; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained for shipping address.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 12 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; proceeding with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the shipping address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 13 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 14 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) have insufficient stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 15 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 16 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item line(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item line(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped missing items, " f"{len(order.items)} item line(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 17 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the customer address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 18 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item line(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate( f"Insufficient inventory for {len(missing)} item line(s): {missing_skus}." ) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with " f"{len(order.items)} in-stock item line(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 19 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped missing items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 20 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the shipping address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 21 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate( f"Insufficient inventory for {len(missing)} item(s): {missing_skus}." ) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with " f"{len(order.items)} remaining item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the customer address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 22 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the customer address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 23 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the shipping address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 24 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped missing items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the customer address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 25 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; proceeding with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 26 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) short on stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped short items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 27 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} line item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate( f"{len(missing)} item(s) have insufficient inventory: {missing_skus}." ) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with " f"{len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 28 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) short on stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped short items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 29 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item line(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate( f"Insufficient inventory for {len(missing)} item line(s): {missing_skus}." ) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with " f"{len(order.items)} in-stock item line(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 30 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Order has {len(order.items)} item(s); checking inventory.") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) have insufficient stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped short items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 31 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 32 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Order has {len(order.items)} item line(s); checking inventory.") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item line(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped missing items, " f"{len(order.items)} item line(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the shipping address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained for the shipping address.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 33 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the shipping address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 34 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) short on stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 35 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 36 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the customer's address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 37 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Order has {len(order.items)} item line(s); checking inventory.") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item line(s) have insufficient stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; continuing with {len(order.items)} in-stock item line(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the destination; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 38 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Checking inventory for {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"{len(missing)} item(s) short on stock: {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped short items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 39 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Processing order with {len(order.items)} item(s).") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; dropped unavailable items, " f"{len(order.items)} item(s) remain." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 40 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY ctx.narrate(f"Order has {len(order.items)} item(s); checking inventory.") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.narrate(f"Insufficient stock for {len(missing)} item(s): {missing_skus}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate( f"Partial fulfillment allowed; proceeding with {len(order.items)} in-stock item(s)." ) else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Carrier returned no quote for the shipping address; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED Claude Opus 5.5, ctx.breadcrumb (order processor) ================================================= --- run 1 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 2 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb( f"insufficient inventory for {len(missing)} of {len(order.items)} items: " f"skus={[i.sku for i in missing]}" ) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} items" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb(f"all {len(order.items)} items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 3 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock (SKUs: {missing_skus}); " f"partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"process_order: {len(order.items)} item(s) remain after dropping") else: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock (SKUs: {missing_skus}); " f"partial not allowed; returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 4 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on inventory (skus: {missing_skus})" ) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"process_order: partial allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("process_order: partial not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 5 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 6 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock (skus: {missing_skus}); " f"partial allowed, continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock (skus: {missing_skus}); " "partial not allowed; returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 7 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 8 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 9 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 10 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 11 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 12 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 13 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 14 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock ({missing_skus}); " "partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock ({missing_skus}); " "partial not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb(f"process_order: label purchased for {len(order.items)} item(s); returning SHIPPED") return Result.SHIPPED --- run 15 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 16 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 17 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.breadcrumb( f"{len(missing)} item(s) short on inventory ({missing_skus}); " "partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"{len(order.items)} item(s) remain after dropping") else: ctx.breadcrumb( f"{len(missing)} item(s) short on inventory ({missing_skus}); " "partial not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 18 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] if order.allow_partial: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock {missing_skus}; " "partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock {missing_skus}; " "partial not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: using fallback quote") else: ctx.breadcrumb("process_order: using primary carrier quote") label = carrier.buy_label(quote) ctx.breadcrumb(f"process_order: label purchased for {len(order.items)} item(s); returning SHIPPED") return Result.SHIPPED --- run 19 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 20 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 21 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 22 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 23 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 24 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 25 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 26 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 27 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 28 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 29 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 30 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock " f"(skus: {missing_skus}); partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock " f"(skus: {missing_skus}); partial not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb(f"process_order: label purchased for {len(order.items)} item(s); returning SHIPPED") return Result.SHIPPED --- run 31 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.breadcrumb( f"{len(missing)} item(s) short on inventory (skus: {missing_skus}); " "partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb( f"{len(missing)} item(s) short on inventory (skus: {missing_skus}); " "partial not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 32 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 33 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 34 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock ({missing_skus}); " "partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"process_order: {len(order.items)} item(s) remain after dropping") else: ctx.breadcrumb( f"process_order: {len(missing)} item(s) short on stock ({missing_skus}); " "partial not allowed; returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 35 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 36 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 37 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 38 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 39 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.breadcrumb( f"{len(missing)} item(s) short on stock (skus: {missing_skus}); " "partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb( f"{len(missing)} item(s) short on stock (skus: {missing_skus}); " "partial not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb(f"label purchased for {len(order.items)} item(s); returning SHIPPED") return Result.SHIPPED --- run 40 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY ctx.breadcrumb(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.breadcrumb(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("fallback quote obtained") else: ctx.breadcrumb("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED Claude Opus 5.5, ctx.zorp (order processor) =========================================== --- run 1 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"{len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"partial fulfillment allowed; continuing with {len(order.items)} item(s)" ) else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 2 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; " f"continuing with {len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 3 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; " f"continuing with {len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 4 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 5 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"process_order: partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 6 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 7 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; " f"continuing with {len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 8 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.zorp(f"insufficient inventory for {len(missing)} item(s): skus={missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 9 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.zorp(f"process_order: insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"process_order: partial fulfillment allowed; proceeding with {len(order.items)} item(s)") else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 10 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 11 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 12 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory (skus: {missing_skus})") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"process_order: partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: obtained fallback quote") else: ctx.zorp("process_order: obtained primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 13 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 14 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp(f"all {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 15 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 16 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.zorp( f"{len(missing)} item(s) short on inventory (skus: {missing_skus}); " "partial allowed, dropping them" ) order.items = [i for i in order.items if i not in missing] else: ctx.zorp( f"{len(missing)} item(s) short on inventory (skus: {missing_skus}); " "partial not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.zorp(f"all {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp(f"label purchased for {len(order.items)} item(s); returning SHIPPED") return Result.SHIPPED --- run 17 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: [{missing_skus}]") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; " f"continuing with {len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 18 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 19 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: {len(missing)} item(s) short on inventory " f"(skus={missing_skus}); partial allowed, continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp( f"process_order: {len(missing)} item(s) short on inventory " f"(skus={missing_skus}); partial not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.zorp(f"process_order: all {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 20 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 21 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; " f"continuing with {len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 22 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 23 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 24 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; " f"continuing with {len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 25 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 26 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 27 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 28 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"process_order: partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 29 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"process_order: partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 30 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 31 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: obtained fallback quote") else: ctx.zorp("process_order: obtained primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 32 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 33 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: start with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"process_order: partial allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("process_order: partial not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 34 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"process_order: partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 35 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"process_order: partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 36 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: obtained fallback quote") else: ctx.zorp("process_order: obtained primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 37 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"process_order: checking inventory for {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"process_order: {len(missing)} item(s) short on stock: {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp( f"process_order: partial fulfillment allowed; continuing with " f"{len(order.items)} item(s)" ) else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("process_order: all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: fallback quote obtained") else: ctx.zorp("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 38 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = [i.sku for i in missing] ctx.zorp(f"insufficient inventory for {len(missing)} item(s): skus={missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 39 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) if order.allow_partial: ctx.zorp( f"insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " "partial fulfillment allowed, dropping missing items" ) order.items = [i for i in order.items if i not in missing] ctx.zorp(f"{len(order.items)} item(s) remain after dropping missing items") else: ctx.zorp( f"insufficient inventory for {len(missing)} item(s) [{missing_skus}]; " "partial fulfillment not allowed, returning BACKORDERED" ) return Result.BACKORDERED else: ctx.zorp(f"all {len(order.items)} item(s) in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 40 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("order has no items; returning EMPTY") return Result.EMPTY ctx.zorp(f"processing order with {len(order.items)} item(s)") missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: missing_skus = ", ".join(str(i.sku) for i in missing) ctx.zorp(f"insufficient inventory for {len(missing)} item(s): {missing_skus}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.zorp("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("all items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("fallback quote obtained") else: ctx.zorp("primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("shipping label purchased; returning SHIPPED") return Result.SHIPPED Claude Haiku 5.5, ctx.log (order processor) =========================================== --- run 1 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 2 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 3 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 4 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback carrier quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 5 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"process_order: {len(missing)} item(s) short on inventory: {[i.sku for i in missing]}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"process_order: allow_partial is set; proceeding with {len(order.items)} available item(s)") else: ctx.log("process_order: allow_partial is not set; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("process_order: fallback quote obtained") else: ctx.log("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 6 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 7 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 8 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 9 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Missing inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 10 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 11 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 12 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback carrier quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 13 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 14 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 15 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"{len(missing)} item(s) short on inventory") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback carrier quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 16 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 17 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial allowed; proceeding with {len(order.items)} item(s)") else: ctx.log("Partial not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 18 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; requesting fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 19 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 20 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 21 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 22 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 23 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 24 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 25 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 26 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 27 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback carrier quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 28 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 29 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 30 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 31 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"{len(missing)} item(s) below requested quantity") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 32 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; requesting fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 33 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Missing inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial allowed; continuing with {len(order.items)} available item(s)") else: ctx.log("Partial not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 34 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.log("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 35 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 36 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; requesting fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback carrier quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 37 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("No fallback quote available; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Using fallback quote") else: ctx.log("Using primary carrier quote") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 38 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; requesting fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 39 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.log("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 40 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.log("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.log(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.log(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.log("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.log("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.log("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.log("Fallback quote obtained") else: ctx.log("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.log("Shipping label purchased; returning SHIPPED") return Result.SHIPPED Claude Haiku 5.5, ctx.narrate (order processor) =============================================== --- run 1 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate(f"Partial fulfillment allowed; proceeding with {len(order.items)} available item(s).") else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier returned no quote; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 2 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 3 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) short on inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing short items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 4 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items and continuing.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 5 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) short on inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier returned no quote; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 6 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate(f"Partial fulfillment allowed; proceeding with {len(order.items)} available item(s).") else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 7 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) short on inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing short items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 8 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) short on inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing short items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 9 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing unavailable items.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; order SHIPPED.") return Result.SHIPPED --- run 10 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing unavailable items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 11 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 12 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) short on inventory.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate(f"Partial allowed; proceeding with {len(order.items)} available item(s).") else: ctx.narrate("Partial not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 13 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 14 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing unavailable items.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 15 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: if order.allow_partial: ctx.narrate(f"{len(missing)} item(s) out of stock and partial fulfillment allowed; removing them from the order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate(f"{len(missing)} item(s) out of stock and partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 16 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 17 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing unavailable items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; requesting fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback carrier quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback carrier quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 18 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 19 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing unavailable items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 20 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing unavailable items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 21 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items and continuing.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 22 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 23 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) short on inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing short items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 24 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Found {len(missing)} item(s) with insufficient inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 25 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items and continuing with the rest.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 26 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing unavailable items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 27 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate(f"Partial fulfillment allowed; proceeding with {len(order.items)} available item(s).") else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 28 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Order allows partial fulfillment; removing unavailable items.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Order does not allow partial fulfillment; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback carrier quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 29 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 30 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) are short on inventory.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items and continuing.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 31 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) short on inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 32 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate(f"Partial fulfillment allowed; proceeding with {len(order.items)} remaining item(s).") else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 33 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; dropping missing items and continuing.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Using fallback quote.") else: ctx.narrate("Using primary carrier quote.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 34 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate(f"Partial fulfillment allowed; proceeding with {len(order.items)} available item(s).") else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier returned no quote; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 35 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing unavailable items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 36 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Missing inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED else: ctx.narrate("All items are in stock.") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 37 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) below requested quantity: {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier returned no quote; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 38 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: ctx.narrate("Partial fulfillment allowed; removing missing items and continuing.") order.items = [i for i in order.items if i not in missing] else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote also unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; order SHIPPED.") return Result.SHIPPED --- run 39 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) have insufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate(f"Partial fulfillment allowed; proceeding with {len(order.items)} available item(s).") else: ctx.narrate("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier returned no quote; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("No fallback quote available; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 40 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.narrate("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.narrate(f"{len(missing)} item(s) lack sufficient inventory: {[i.sku for i in missing]}.") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.narrate(f"Partial allowed; continuing with {len(order.items)} available item(s).") else: ctx.narrate("Partial not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.narrate("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.narrate("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.narrate("Fallback quote obtained.") else: ctx.narrate("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.narrate("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED Claude Haiku 5.5, ctx.breadcrumb (order processor) ================================================== --- run 1 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, dropping missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial fulfillment not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 2 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, dropping missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 3 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Missing inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 4 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: allow_partial is not set, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 5 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial set; dropping missing items and continuing") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 6 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: partial fulfillment allowed, removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial fulfillment not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 7 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Missing inventory for {len(missing)} item(s)") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Using fallback quote") else: ctx.breadcrumb("Using primary carrier quote") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 8 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"process_order: partial allowed, continuing with {len(order.items)} item(s)") else: ctx.breadcrumb("process_order: partial not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: using fallback quote") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 9 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Found {len(missing)} item(s) with insufficient inventory") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Using fallback quote") else: ctx.breadcrumb("Using primary carrier quote") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 10 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: if order.allow_partial: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s); allow_partial is set, removing them and continuing") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s); allow_partial is not set, returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("All items in stock; proceeding to shipping quote") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 11 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 12 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory: {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("process_order: partial fulfillment allowed, removing short items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial fulfillment not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: using fallback quote") else: ctx.breadcrumb("process_order: using primary carrier quote") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 13 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 14 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory: {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, removing missing items and continuing") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: allow_partial is not set, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 15 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 16 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Missing inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.breadcrumb("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; requesting fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 17 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 18 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial set; dropping missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 19 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Using fallback carrier quote") else: ctx.breadcrumb("Using primary carrier quote") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 20 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 21 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: no items in order, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial fulfillment not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: using fallback quote") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 22 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Found {len(missing)} item(s) with insufficient inventory") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 23 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: allow_partial is not set, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 24 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set; removing short items and continuing") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: allow_partial is not set; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 25 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, dropping missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial fulfillment not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: quote obtained, purchasing label") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: label purchased, returning SHIPPED") return Result.SHIPPED --- run 26 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 27 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"process_order: partial allowed; continuing with {len(order.items)} item(s)") else: ctx.breadcrumb("process_order: partial not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 28 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Found {len(missing)} item(s) with insufficient inventory") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 29 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 30 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set; dropping missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial shipment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: using fallback quote") else: ctx.breadcrumb("process_order: using primary carrier quote") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 31 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 32 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: partial allowed, dropping missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: using fallback quote") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 33 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.breadcrumb(f"Partial fulfillment allowed; continuing with {len(order.items)} item(s)") else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 34 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory: {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set, removing missing items and continuing") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial fulfillment not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 35 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Using fallback carrier quote") else: ctx.breadcrumb("Using primary carrier quote") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 36 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"{len(missing)} item(s) below requested quantity") if order.allow_partial: ctx.breadcrumb("partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("using fallback quote") else: ctx.breadcrumb("using primary carrier quote") label = carrier.buy_label(quote) ctx.breadcrumb("shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 37 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items, returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial set, removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: partial not allowed, returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable, trying fallback") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable, returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: fallback quote obtained") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased, returning SHIPPED") return Result.SHIPPED --- run 38 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.breadcrumb("process_order: allow_partial is set; shipping available items only") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("process_order: allow_partial is not set; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("process_order: using fallback quote") else: ctx.breadcrumb("process_order: primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 39 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 40 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.breadcrumb("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.breadcrumb(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.breadcrumb("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.breadcrumb("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.breadcrumb("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.breadcrumb("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.breadcrumb("Fallback quote obtained") else: ctx.breadcrumb("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.breadcrumb("Shipping label purchased; returning SHIPPED") return Result.SHIPPED Claude Haiku 5.5, ctx.zorp (order processor) ============================================ --- run 1 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 2 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Using fallback quote") else: ctx.zorp("Using primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 3 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 4 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("All items are in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 5 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 6 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 7 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 8 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 9 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.zorp("process_order: allow_partial is set; dropping missing items and continuing") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("process_order: allow_partial is not set; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: using fallback quote") else: ctx.zorp("process_order: using primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 10 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Using fallback quote") else: ctx.zorp("Using primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 11 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; requesting fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 12 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Using fallback quote") else: ctx.zorp("Using primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 13 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY.") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}.") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order.") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED.") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote.") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING.") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained.") else: ctx.zorp("Primary carrier quote obtained.") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED.") return Result.SHIPPED --- run 14 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 15 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 16 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Using fallback quote") else: ctx.zorp("Using primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 17 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 18 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 19 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 20 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; requesting fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 21 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 22 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: order.items = [i for i in order.items if i not in missing] ctx.zorp(f"Partial fulfillment allowed; proceeding with {len(order.items)} item(s)") else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 23 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 24 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.zorp("process_order: allow_partial is set; dropping missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: using fallback quote") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 25 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) short on inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing short items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Using fallback quote") else: ctx.zorp("Using primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 26 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 27 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("process_order: order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"process_order: {len(missing)} item(s) short on inventory") if order.allow_partial: ctx.zorp("process_order: allow_partial is set; removing missing items and continuing") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("process_order: partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("process_order: primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("process_order: fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("process_order: using fallback quote") label = carrier.buy_label(quote) ctx.zorp("process_order: shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 28 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Missing inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Using fallback quote") else: ctx.zorp("Using primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 29 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 30 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 31 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 32 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Using fallback quote") else: ctx.zorp("Using primary carrier quote") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 33 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 34 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) lack sufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 35 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 36 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) below requested quantity: {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 37 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"{len(missing)} item(s) have insufficient inventory") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 38 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 39 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s): {[i.sku for i in missing]}") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing missing items from order") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED else: ctx.zorp("All items in stock") quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED --- run 40 --- def process_order(ctx, order, inventory, carrier): customer = order.customer # has .name, .email, .address if not order.items: ctx.zorp("Order has no items; returning EMPTY") return Result.EMPTY missing = [i for i in order.items if inventory.count(i.sku) < i.qty] if missing: ctx.zorp(f"Insufficient inventory for {len(missing)} item(s)") if order.allow_partial: ctx.zorp("Partial fulfillment allowed; removing unavailable items") order.items = [i for i in order.items if i not in missing] else: ctx.zorp("Partial fulfillment not allowed; returning BACKORDERED") return Result.BACKORDERED quote = carrier.quote(customer.address, order.items) if quote is None: ctx.zorp("Primary carrier quote unavailable; trying fallback quote") quote = carrier.fallback_quote(order.items) if quote is None: ctx.zorp("Fallback quote unavailable; returning NO_SHIPPING") return Result.NO_SHIPPING ctx.zorp("Fallback quote obtained") else: ctx.zorp("Primary carrier quote obtained") label = carrier.buy_label(quote) ctx.zorp("Shipping label purchased; returning SHIPPED") return Result.SHIPPED PART 2: THE CONTACT SYNC ======================== PROMPT (shown with ctx.log) --------------------------- Do not read, search or open any files, and do not use any tools. Answer from this message alone. Here is a Python module that syncs an online shop's new customers into a CRM and records their delivery preferences with the carrier. `from integrations.context import ctx` is available; `ctx` has one method for recording what happens during a run: `ctx.log(message: str) -> None`. """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: skipped += 1 return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True return saved Add calls to `ctx.log` to this module. Reply with only the complete updated module in one Python code block, and nothing else. Claude Opus 5.5, ctx.log (contact sync) ======================================= --- run 1 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop orders page {pages} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) ctx.log(f"Shop orders page {pages}: {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already up to date, skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"CRM update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"Order {contact.source_order}: CRM update for contact {existing['id']} " "failed after retry; skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {contact.source_order}: CRM create failed; skipping") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"Setting carrier delivery preferences for {ref} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={quote_plus(window)}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__})") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"{ref}: no address on contact; leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"{ref}: save confirmation did not appear within 60s ({type(exc).__name__})") ctx.log(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 2 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.log(f"Fetched orders page {pages}: {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Stopped after MAX_PAGES={MAX_PAGES} with more orders pending; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if by_email is None: ctx.log(f"CRM email lookup failed for order {contact.source_order}") if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order} matched an existing CRM contact by phone, not email") return by_phone["results"][0] if by_phone is None: ctx.log(f"CRM phone lookup failed for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: contact_id = existing.get("id") merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {contact_id} (order {order_id}) failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {contact_id} from order {order_id}; filled fields: {', '.join(filled)}") updated += 1 else: ctx.log(f"Failed to update CRM contact {contact_id} from order {order_id} after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}; counted as skipped") skipped += 1 duplicates = len(orders) - len(seen) - sum(1 for o in orders if _to_contact(o) is None) ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, {updated} updated, " f"{skipped} skipped (including {duplicates} repeat-customer orders)" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(step: str, contact: Contact, action) -> bool: """Run one portal step, logging (without personal data) if it fails.""" try: action() return True except Exception as exc: ctx.log(f"Carrier portal step '{step}' failed for order {contact.source_order}: {type(exc).__name__}") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log(f"No delivery window given for order {contact.source_order}; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery window '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") _attempt("wait for preferences form", contact, lambda: client.wait_for("#preferences-form", timeout=30)) _attempt("fill email", contact, lambda: client.fill("#email", contact.email)) _attempt("fill name", contact, lambda: client.fill("#name", full_name)) if contact.address: _attempt("fill city", contact, lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.log(f"No address for order {contact.source_order}; city left blank on carrier form") _attempt("click save", contact, lambda: client.click("#save")) saved = _attempt( "wait for save confirmation", contact, lambda: client.wait_for(".preferences-saved", timeout=60) ) if saved: ctx.log(f"Carrier delivery preferences saved for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm delivery preferences for order {contact.source_order}; not saved") return saved --- run 3 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 stopped_early = False for _ in range(MAX_PAGES): if not url: stopped_early = True break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop orders: page {pages} returned no response; stopping pagination") stopped_early = True break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders: page {pages} contained no orders; stopping pagination") stopped_early = True break orders.extend(batch) url = page.get("next") if not stopped_early and url: ctx.log( f"Shop orders: reached MAX_PAGES={MAX_PAGES} with more pages remaining; " f"results are truncated" ) ctx.log(f"Shop orders: fetched {len(orders)} order(s) across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.log(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.log( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone " f"(email did not match)" ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already processed earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']} (filled fields: {', '.join(filled)})") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} order(s), " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(step: str, order_ref: object, action) -> bool: """Run one portal step, logging (but not raising) any failure.""" try: action() return True except Exception as exc: # noqa: BLE001 - failures are tolerated by design ctx.log(f"Delivery preferences for order {order_ref}: step '{step}' failed ({type(exc).__name__})") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" ref = contact.source_order ctx.log( f"Delivery preferences for order {ref}: setting window '{window}'" + (" (default)" if used_default else "") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") _attempt("wait for form", ref, lambda: client.wait_for("#preferences-form", timeout=30)) _attempt("fill email", ref, lambda: client.fill("#email", contact.email)) _attempt("fill name", ref, lambda: client.fill("#name", full_name)) if contact.address: _attempt("fill city", ref, lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.log(f"Delivery preferences for order {ref}: no address on contact; city left blank") _attempt("click save", ref, lambda: client.click("#save")) saved = _attempt( "wait for save confirmation", ref, lambda: client.wait_for(".preferences-saved", timeout=60), ) ctx.log( f"Delivery preferences for order {ref}: " + ("saved" if saved else "NOT confirmed as saved") ) return saved --- run 4 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.log(f"Shop orders page {pages}: got {len(batch)} orders (total {len(orders)})") url = page.get("next") else: if url: ctx.log( f"Stopped after MAX_PAGES={MAX_PAGES} pages with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" order_id = contact.source_order by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {order_id}: CRM lookup by email failed (no response)") if by_email and by_email.get("results"): ctx.log(f"Order {order_id}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {order_id}: CRM lookup by phone failed (no response)") if by_phone and by_phone.get("results"): ctx.log(f"Order {order_id}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] ctx.log(f"Order {order_id}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped (customer already processed in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete, skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry, skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed, skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" order_id = contact.source_order full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.log(f"Order {order_id}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.log(f"Order {order_id}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Order {order_id}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {order_id}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {order_id}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {order_id}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"Order {order_id}: no address on contact, city left blank") try: client.click("#save") except Exception as exc: ctx.log(f"Order {order_id}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Order {order_id}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.log(f"Order {order_id}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 5 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order fetch: page {pages + 1} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.log(f"Order fetch: page {pages} returned {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Order fetch: hit MAX_PAGES={MAX_PAGES} with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Order fetch: {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.log(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Customer sync: starting for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("Customer sync: no orders found; nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: customer already handled earlier in this run; skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (no retry); skipping") skipped += 1 ctx.log( f"Customer sync: finished — {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.log(f"Delivery prefs (order {contact.source_order}): no window given; using default 'weekday-daytime'") window = window or "weekday-daytime" label = f"Delivery prefs (order {contact.source_order})" ctx.log(f"{label}: opening carrier preferences form with window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"{label}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"{label}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"{label}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"{label}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"{label}: contact has no address; leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"{label}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"{label}: no save confirmation within 60s ({type(exc).__name__})") ctx.log(f"{label}: {'saved' if saved else 'NOT saved'}") return saved --- run 6 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop returned no data for orders page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Orders page {pages} was empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched orders page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.log( f"Stopped after MAX_PAGES={MAX_PAGES} with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup returned no response (order {contact.source_order})") if by_email and by_email.get("results"): ctx.log( f"Matched order {contact.source_order} to CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup returned no response (order {contact.source_order})") if by_phone and by_phone.get("results"): ctx.log( f"Matched order {contact.source_order} to CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"Filling empty fields on CRM contact {existing.get('id')}: {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Skipping order {order_id}: CRM contact {existing.get('id')} already up to date" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.log( f"Update of CRM contact {existing['id']} failed after retry; " f"skipping order {order_id}" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Created CRM contact {new_id} from order {order_id}") created += 1 else: ctx.log(f"Creating CRM contact failed for order {order_id}; skipping") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"Setting carrier delivery preferences for {ref} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as e: ctx.log(f"Preferences form did not appear within 30s for {ref} ({type(e).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as e: ctx.log(f"Could not fill email field for {ref} ({type(e).__name__})") try: client.fill("#name", full_name) except Exception as e: ctx.log(f"Could not fill name field for {ref} ({type(e).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as e: ctx.log(f"Could not fill city field for {ref} ({type(e).__name__})") else: ctx.log(f"No address on file for {ref}; leaving city blank") try: client.click("#save") except Exception as e: ctx.log(f"Could not click save for {ref} ({type(e).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as e: ctx.log(f"No save confirmation within 60s for {ref} ({type(e).__name__})") ctx.log(f"Delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 7 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop orders page {pages + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.log(f"Fetched shop orders page {pages}: {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Stopped fetching shop orders at the {MAX_PAGES}-page limit; " "more orders may remain unsynced" ) ctx.log(f"Fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already processed earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {order_id}: CRM contact {existing.get('id')} already up to date; skipped" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Order {order_id}: updated CRM contact {existing['id']} " f"(filled fields: {', '.join(filled)})" ) updated += 1 else: ctx.log( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " "counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed; counted as skipped") skipped += 1 ctx.log( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"contact from order {contact.source_order}" ctx.log(f"Setting carrier delivery preferences for {ref} (window: {window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Carrier preferences form did not appear within 30s for {ref} " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill the email field for {ref} ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill the name field for {ref} ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill the city field for {ref} ({type(exc).__name__})") else: ctx.log(f"No address on file for {ref}; leaving the city field blank") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click Save on the carrier form for {ref} ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"No save confirmation from the carrier within 60s for {ref} ({type(exc).__name__})" ) if saved: ctx.log(f"Carrier delivery preferences saved for {ref}") else: ctx.log(f"Carrier delivery preferences were NOT confirmed saved for {ref}") return saved --- run 8 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: ctx.log("No further order pages") break page = client.get_json(url) if not page: ctx.log(f"Order page {pages + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {pages + 1} was empty; stopping pagination") break pages += 1 orders.extend(batch) ctx.log(f"Fetched order page {pages} with {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"WARNING: reached MAX_PAGES={MAX_PAGES} with more order pages remaining; " "results are truncated" ) ctx.log(f"Fetched {len(orders)} orders across {pages} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup failed for order {contact.source_order}") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup failed for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 failed = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already up to date") skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.log( f"Order {order_id}: updating CRM contact {existing.get('id')} " f"(filling fields: {', '.join(changed)})" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing.get('id')} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.log( f"ERROR: Order {order_id}: update of CRM contact {existing.get('id')} " "failed after retry; counted as skipped" ) failed += 1 skipped += 1 else: ctx.log(f"Order {order_id}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"ERROR: Order {order_id}: CRM contact creation failed; counted as skipped") failed += 1 skipped += 1 ctx.log( f"Customer sync finished: created={created}, updated={updated}, " f"skipped={skipped} (of which {failed} were failed CRM writes)" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"contact from order {contact.source_order}" ctx.log(f"Setting delivery preferences for {ref} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Preferences form did not appear within 30s for {ref} ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill #email for {ref} ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill #name for {ref} ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill #city for {ref} ({type(exc).__name__})") else: ctx.log(f"No address for {ref}; leaving #city blank") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click #save for {ref} ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"No save confirmation within 60s for {ref} ({type(exc).__name__})") if saved: ctx.log(f"Delivery preferences saved for {ref}") else: ctx.log(f"ERROR: Delivery preferences NOT confirmed saved for {ref}") return saved --- run 9 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email address; cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop returned no data for page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Page {pages} contained no orders; stopping pagination") break orders.extend(batch) ctx.log(f"Page {pages}: received {len(batch)} orders ({len(orders)} total so far)") url = page.get("next") else: if url: ctx.log( f"Reached the {MAX_PAGES}-page limit with more pages still available; " "remaining orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Order {order.get('id')}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: skipped (customer already processed in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already complete; skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"CRM contact {existing['id']}: update failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.log( f"Order {contact.source_order}: creating CRM contact failed; " "counted as skipped" ) skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.log( f"Order {contact.source_order}: no delivery window given; " "defaulting to weekday-daytime" ) window = window or "weekday-daytime" ctx.log(f"Order {contact.source_order}: setting carrier delivery window to {window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"Order {contact.source_order}: no address on file; city field left blank") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Order {contact.source_order}: carrier confirmed delivery preferences saved") else: ctx.log( f"Order {contact.source_order}: no save confirmation from carrier within 60s; " "preferences may not have been recorded" ) return saved --- run 10 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages_fetched = 0 for page_num in range(1, MAX_PAGES + 1): if not url: ctx.log(f"No further pages after page {pages_fetched}") break page = client.get_json(url) if not page: ctx.log(f"Shop returned no data for orders page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Orders page {page_num} was empty; stopping pagination") break orders.extend(batch) pages_fetched = page_num ctx.log(f"Fetched orders page {page_num}: {len(batch)} orders (running total {len(orders)})") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES={MAX_PAGES} with more pages still available; " "remaining orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup returned no response for order {contact.source_order}") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup returned no response for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync; finished with nothing created, updated or skipped") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already processed earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: existing_id = existing.get("id") merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing_id} already complete; no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing_id} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing_id}") updated += 1 else: ctx.log( f"Order {order_id}: update of CRM contact {existing_id} failed after retry; " "counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (no retry); counted as skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None or not window: ctx.log(f"Order {contact.source_order}: no delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.log(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"Order {contact.source_order}: no address on contact; city field left blank") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__})" ) if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved with carrier") else: ctx.log(f"Order {contact.source_order}: delivery preferences were NOT confirmed as saved") return saved --- run 11 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop orders page {pages + 1} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.log( f"Stopped fetching shop orders at the {MAX_PAGES}-page limit; " "more orders remain and were not synced" ) ctx.log(f"Fetched {len(orders)} shop orders created since {since} across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup failed for order {contact.source_order}") if by_email and by_email.get("results"): ctx.log(f"Order {contact.source_order} matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup failed for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order} matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting CRM sync of shop customers created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new shop orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipped order {contact.source_order}: customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipped order {contact.source_order}: CRM contact {existing['id']} already up to date") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Updated CRM contact {existing['id']} from order {contact.source_order} " f"(filled: {', '.join(filled)})" ) updated += 1 else: ctx.log( f"Failed to update CRM contact {existing['id']} from order {contact.source_order} " "after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact for order {contact.source_order}") created += 1 else: ctx.log(f"Failed to create CRM contact for order {contact.source_order}; counted as skipped") skipped += 1 ctx.log( f"CRM sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log(f"No delivery window given for order {contact.source_order}; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill the email field on the carrier form ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill the name field on the carrier form ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill the city field on the carrier form ({type(exc).__name__})") else: ctx.log(f"Order {contact.source_order} has no address; leaving the city field blank") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save on the carrier form ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"No save confirmation from the carrier within 60s for order {contact.source_order} " f"({type(exc).__name__}); preference may not have been recorded" ) if saved: ctx.log(f"Carrier confirmed delivery preference '{window}' for order {contact.source_order}") return saved --- run 12 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from collections.abc import Iterator from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 @contextlib.contextmanager def _suppress_and_log(step: str) -> Iterator[None]: """Suppress any exception like contextlib.suppress(Exception), but record that it happened. Only the exception type is logged, because exception messages from form fills can echo back the customer data that was being entered. """ try: yield except Exception as exc: ctx.log(f"Carrier form step '{step}' failed and was skipped: {type(exc).__name__}") def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop orders page {pages} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.log(f"Shop orders page {pages}: {len(batch)} orders (more pages: {bool(url)})") else: if url: ctx.log( f"Reached MAX_PAGES={MAX_PAGES} with more shop orders still available; " "remaining orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page request(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log( f"Order {contact.source_order}: skipped, customer already processed earlier in this run" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already complete, nothing to update" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"CRM update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"Order {contact.source_order}: CRM update of contact {existing['id']} " "failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.log( f"Order {contact.source_order}: CRM contact creation failed; counted as skipped" ) skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log( f"Order {contact.source_order}: no delivery window given, using default 'weekday-daytime'" ) window = window or "weekday-daytime" ctx.log( f"Order {contact.source_order}: setting carrier delivery preference to '{window}'" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") with _suppress_and_log("wait for preferences form"): client.wait_for("#preferences-form", timeout=30) with _suppress_and_log("fill email"): client.fill("#email", contact.email) with _suppress_and_log("fill name"): client.fill("#name", full_name) if contact.address: with _suppress_and_log("fill city"): client.fill("#city", contact.address.get("city", "")) else: ctx.log(f"Order {contact.source_order}: no address on contact, city left blank") with _suppress_and_log("click save"): client.click("#save") saved = False with _suppress_and_log("wait for save confirmation"): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Order {contact.source_order}: carrier delivery preference saved") else: ctx.log( f"Order {contact.source_order}: carrier did not confirm the delivery preference was saved" ) return saved --- run 13 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: ctx.log(f"Order pagination finished: no further pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.log(f"Shop returned no data for order page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders ({len(orders)} total so far)") url = page.get("next") else: if url: ctx.log( f"Reached page limit of {MAX_PAGES} with more order pages remaining; " "remaining orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM lookup by email returned no response (order {contact.source_order})") if by_email and by_email.get("results"): ctx.log( f"Matched existing CRM contact {by_email['results'][0].get('id')} by email " f"(order {contact.source_order})" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM lookup by phone returned no response (order {contact.source_order})") if by_phone and by_phone.get("results"): ctx.log( f"Matched existing CRM contact {by_phone['results'][0].get('id')} by phone " f"(order {contact.source_order})" ) return by_phone["results"][0] ctx.log(f"No existing CRM contact found (order {contact.source_order})") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"Filling empty fields on CRM contact {existing.get('id')}: {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: customer already processed earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Skipping order {order_id}: CRM contact {existing.get('id')} " "already has all available details" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.log( f"Failed to update CRM contact {existing['id']} from order {order_id} " "after retry; counting as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Created CRM contact {new_id} from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}; counting as skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log("No delivery window given; using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preferences (window '{window}') for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " "continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field on carrier form ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field on carrier form ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field on carrier form ({type(exc).__name__})") else: ctx.log("Contact has no address; leaving city blank on carrier form") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save on carrier form ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Carrier did not confirm the preferences were saved within 60s ({type(exc).__name__})" ) if saved: ctx.log(f"Carrier delivery preferences saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preferences NOT saved for order {contact.source_order}") return saved --- run 14 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from collections.abc import Callable from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages_fetched = 0 for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num}: empty or failed response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num}: no orders; stopping pagination") break orders.extend(batch) pages_fetched = page_num ctx.log(f"Order page {page_num}: fetched {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages_fetched} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: existing_id = existing.get("id") merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing_id} already complete; skipped") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing_id} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Order {order_id}: updated CRM contact {existing_id} " f"(filled fields: {', '.join(filled)})" ) updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing_id} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(step: str, order_ref: object, action: Callable[[], object]) -> bool: """Run one portal step, logging (but not raising) any failure.""" try: action() return True except Exception as exc: ctx.log(f"Delivery preferences for order {order_ref}: step '{step}' failed ({type(exc).__name__})") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log(f"Delivery preferences for order {contact.source_order}: no window given, using default") window = window or "weekday-daytime" ref = contact.source_order ctx.log(f"Delivery preferences for order {ref}: opening carrier form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") _attempt("wait for form", ref, lambda: client.wait_for("#preferences-form", timeout=30)) _attempt("fill email", ref, lambda: client.fill("#email", contact.email)) _attempt("fill name", ref, lambda: client.fill("#name", full_name)) if contact.address: _attempt("fill city", ref, lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.log(f"Delivery preferences for order {ref}: no address on contact; city left blank") _attempt("click save", ref, lambda: client.click("#save")) saved = _attempt( "wait for save confirmation", ref, lambda: client.wait_for(".preferences-saved", timeout=60) ) if saved: ctx.log(f"Delivery preferences for order {ref}: saved") else: ctx.log(f"Delivery preferences for order {ref}: not confirmed as saved") return saved --- run 15 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email address, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.log(f"Shop orders page {pages}: {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Stopped after the {MAX_PAGES}-page limit while more pages remained; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders created after {since} across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email failed or returned nothing") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone failed or returned nothing") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log( f"CRM contact {existing.get('id')}: filling empty fields from order " f"{contact.source_order}: {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: customer already handled earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete, no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"CRM contact {existing['id']}: updated from order {contact.source_order}") updated += 1 else: ctx.log( f"CRM contact {existing['id']}: update failed after retry; " f"order {contact.source_order} counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.log( f"Order {contact.source_order}: creating CRM contact failed; counted as skipped" ) skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log(f"Order {contact.source_order}: no delivery window given, using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.log(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) for selector, label, value in ( ("#email", "email", contact.email), ("#name", "name", full_name), ): try: client.fill(selector, value) except Exception as exc: ctx.log( f"Order {contact.source_order}: could not fill {label} field " f"({type(exc).__name__}); continuing" ) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log( f"Order {contact.source_order}: could not fill city field " f"({type(exc).__name__}); continuing" ) else: ctx.log(f"Order {contact.source_order}: no address on file, leaving city blank") try: client.click("#save") except Exception as exc: ctx.log( f"Order {contact.source_order}: clicking save failed ({type(exc).__name__})" ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__})" ) if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved with carrier") else: ctx.log(f"Order {contact.source_order}: delivery preferences were NOT confirmed as saved") return saved --- run 16 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) phone = _normalize_phone(order.get("phone", "")) address = _parse_address(order) or None ctx.log( f"Order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Order page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {pages}: no orders, stopping pagination") break orders.extend(batch) url = page.get("next") ctx.log(f"Order page {pages}: got {len(batch)} orders (total {len(orders)}), more pages: {bool(url)}") else: if url: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; some orders were not fetched") ctx.log(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.log( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email " f"({len(by_email['results'])} result(s))" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.log( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone " f"({len(by_phone['results'])} result(s))" ) return match ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.log( f"CRM contact {existing.get('id')}: merge filled fields {filled}" if filled else f"CRM contact {existing.get('id')}: merge found no gaps to fill" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped (duplicate customer already processed this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: skipped (CRM contact {existing['id']} already up to date)") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (no retry); counted as skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window: ctx.log(f"Order {contact.source_order}: setting delivery window '{window}'") else: window = "weekday-daytime" ctx.log(f"Order {contact.source_order}: no delivery window given, using default '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"Order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})") ctx.log( f"Order {contact.source_order}: delivery preferences " f"{'saved' if saved else 'NOT confirmed saved'} with carrier" ) return saved --- run 17 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop returned an empty or failed response for page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Page {pages} contained no orders; stopping pagination") break orders.extend(batch) ctx.log(f"Page {pages}: fetched {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact {existing['id']} already complete, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {contact.source_order}: failed to create CRM contact") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"Order {contact.source_order}" ctx.log(f"{ref}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"{ref}: no address on file, leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"{ref}: save confirmation did not appear within 60s ({type(exc).__name__})") ctx.log(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 18 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages_fetched = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no response for orders page {pages_fetched + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages_fetched += 1 orders.extend(batch) ctx.log(f"Fetched orders page {pages_fetched}: {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES ({MAX_PAGES}) while more order pages remained; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages_fetched} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup returned no response for order {contact.source_order}") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup returned no response for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already up to date") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Order {order_id}: updated CRM contact {existing['id']} " f"(filled: {', '.join(filled)})" ) updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"Setting delivery preferences for {ref} (window: {window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"{ref}: no address on contact; leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"{ref}: save confirmation did not appear within 60s ({type(exc).__name__})") ctx.log(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 19 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email address; skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop orders page {pages}: empty or failed response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders page {pages}: no orders; stopping pagination") break orders.extend(batch) ctx.log(f"Shop orders page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order.get('id')}: customer already processed in this run; skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {order.get('id')}: CRM contact {existing.get('id')} " "already complete; nothing to update" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"CRM contact {existing['id']}: update failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"Order {order.get('id')}: update of CRM contact {existing['id']} " "failed after retry; skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order.get('id')}: creating CRM contact failed; skipping") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"Setting delivery preferences for {ref} (window: {window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Delivery preferences for {ref}: form did not appear within 30s " f"({type(exc).__name__}); continuing" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Delivery preferences for {ref}: could not fill email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Delivery preferences for {ref}: could not fill name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log( f"Delivery preferences for {ref}: could not fill city ({type(exc).__name__})" ) else: ctx.log(f"Delivery preferences for {ref}: no address on file; leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"Delivery preferences for {ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Delivery preferences for {ref}: no save confirmation within 60s " f"({type(exc).__name__})" ) ctx.log(f"Delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 20 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no response for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.log( f"Reached the {MAX_PAGES}-page limit while fetching orders; " "more orders remain and were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup returned no response for order {contact.source_order}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup returned no response for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log(f"Matched order {contact.source_order} to an existing CRM contact by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Updated CRM contact {existing['id']} from order {order_id} " f"(filled: {', '.join(changed)})" ) updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} from order {order_id} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Created CRM contact {new_id} from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"Setting delivery window '{window}' with the carrier for {ref}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Carrier preferences form did not appear within 30s for {ref} ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field on carrier form for {ref} ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field on carrier form for {ref} ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field on carrier form for {ref} ({type(exc).__name__})") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save on carrier form for {ref} ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Carrier did not confirm saved preferences within 60s for {ref} ({type(exc).__name__})") ctx.log(f"Delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 21 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"fetch_orders: page {pages + 1} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"fetch_orders: page {pages + 1} contained no orders; stopping pagination") break pages += 1 orders.extend(batch) ctx.log(f"fetch_orders: page {pages} returned {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"fetch_orders: hit MAX_PAGES={MAX_PAGES} with more pages remaining; " "results are truncated" ) ctx.log(f"fetch_orders: fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"find_existing: email lookup failed for order {contact.source_order}") if by_email and by_email.get("results"): ctx.log( f"find_existing: order {contact.source_order} matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"find_existing: phone lookup failed for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log( f"find_existing: order {contact.source_order} matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"sync_new_customers: starting sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("sync_new_customers: no orders to process") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"sync_new_customers: skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"sync_new_customers: skipping order {order_id}: customer already processed this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"sync_new_customers: order {order_id}: CRM contact {existing.get('id')} " "already complete; nothing to update" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log( f"sync_new_customers: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"sync_new_customers: order {order_id}: updated CRM contact {existing['id']} " f"(filled fields: {', '.join(filled)})" ) updated += 1 else: ctx.log( f"sync_new_customers: order {order_id}: update of CRM contact {existing['id']} " "failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"sync_new_customers: order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log( f"sync_new_customers: order {order_id}: creating CRM contact failed; " "counted as skipped (not retried)" ) skipped += 1 ctx.log( f"sync_new_customers: done; processed {len(orders)} orders: " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(label: str, order_id, fn, *args, **kwargs) -> bool: """Run one portal step, logging (but swallowing) any failure. Returns True on success.""" try: fn(*args, **kwargs) return True except Exception as exc: # noqa: BLE001 - deliberately swallowed, as before ctx.log( f"set_delivery_preferences: order {order_id}: step '{label}' failed " f"({type(exc).__name__}); continuing" ) return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() defaulted = window is None or window == "" window = window or "weekday-daytime" order_id = contact.source_order ctx.log( f"set_delivery_preferences: order {order_id}: setting window '{window}'" + (" (default)" if defaulted else "") ) client.open(f"{CARRIER_URL}/preferences/new?window={quote_plus(window)}" if False else f"{CARRIER_URL}/preferences/new?window={window}") _attempt("wait for form", order_id, client.wait_for, "#preferences-form", timeout=30) _attempt("fill email", order_id, client.fill, "#email", contact.email) _attempt("fill name", order_id, client.fill, "#name", full_name) if contact.address: _attempt("fill city", order_id, client.fill, "#city", contact.address.get("city", "")) else: ctx.log(f"set_delivery_preferences: order {order_id}: no address; city left blank") _attempt("click save", order_id, client.click, "#save") saved = _attempt( "wait for save confirmation", order_id, client.wait_for, ".preferences-saved", timeout=60 ) ctx.log( f"set_delivery_preferences: order {order_id}: " + ("preferences saved" if saved else "save NOT confirmed; returning False") ) return saved --- run 22 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Orders page {pages + 1} was empty; stopping pagination") break pages += 1 orders.extend(batch) ctx.log(f"Fetched orders page {pages} with {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Stopped after MAX_PAGES={MAX_PAGES} with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders created after {since} across {pages} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup failed for order {contact.source_order}") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order} matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup failed for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order} matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Skipping order {order_id}: CRM contact {existing.get('id')} " "already has all fields" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Updated CRM contact {existing['id']} from order {order_id}; " f"filled fields: {', '.join(filled)}" ) updated += 1 else: ctx.log( f"Failed to update CRM contact {existing['id']} from order {order_id} " "after retry; counting as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Created CRM contact {new_id} from order {order_id}") created += 1 else: ctx.log( f"Failed to create CRM contact from order {order_id}; counting as skipped" ) skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log("No delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"Setting delivery preferences for {ref} with window {window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Preferences form did not appear within 30s for {ref} " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field for {ref} ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field for {ref} ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field for {ref} ({type(exc).__name__})") else: ctx.log(f"No address on file for {ref}; leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save for {ref} ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"No save confirmation within 60s for {ref} ({type(exc).__name__}); " "preferences may not have been recorded" ) if saved: ctx.log(f"Delivery preferences saved for {ref}") return saved --- run 23 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no response for order page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.log(f"Fetched order page {pages}: {len(batch)} orders") url = page.get("next") else: if url: ctx.log(f"Stopped after MAX_PAGES={MAX_PAGES} pages; more orders remain unfetched") ctx.log(f"Fetched {len(orders)} orders since {since} across {pages} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']} (filled fields: {', '.join(filled)})") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _log_step_failure(order_id: object, step: str, exc: Exception) -> None: """Record a failed carrier-form step without including exception text, which may echo customer data.""" ctx.log(f"Order {order_id}: carrier form step '{step}' failed ({type(exc).__name__})") def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None window = window or "weekday-daytime" order_id = contact.source_order ctx.log( f"Order {order_id}: setting carrier delivery window '{window}'" + (" (default)" if used_default else "") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: _log_step_failure(order_id, "wait for form", exc) try: client.fill("#email", contact.email) except Exception as exc: _log_step_failure(order_id, "fill email", exc) try: client.fill("#name", full_name) except Exception as exc: _log_step_failure(order_id, "fill name", exc) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: _log_step_failure(order_id, "fill city", exc) else: ctx.log(f"Order {order_id}: no address on contact; city left blank") try: client.click("#save") except Exception as exc: _log_step_failure(order_id, "click save", exc) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: _log_step_failure(order_id, "wait for save confirmation", exc) if saved: ctx.log(f"Order {order_id}: carrier confirmed delivery preferences saved") else: ctx.log(f"Order {order_id}: carrier did not confirm save; delivery preferences may not be recorded") return saved --- run 24 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from collections.abc import Callable from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop order fetch: page {pages + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.log( f"Shop order fetch: hit MAX_PAGES={MAX_PAGES} with more pages remaining; " f"orders beyond this point were NOT fetched" ) ctx.log(f"Shop order fetch: {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"CRM sync starting for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("CRM sync: no orders to process") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = failed = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already processed earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']} (filled: {', '.join(filled)})") updated += 1 else: ctx.log( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped" ) failed += 1 skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (no retry); counted as skipped") failed += 1 skipped += 1 ctx.log( f"CRM sync finished: {len(orders)} orders, {created} created, {updated} updated, " f"{skipped} skipped (of which {failed} were write failures)" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _try_step(step: str, ref: object, action: Callable[[], object]) -> bool: """Run one portal step, logging (rather than silently swallowing) any failure.""" try: action() return True except Exception as exc: ctx.log(f"Carrier preferences (order {ref}): step '{step}' failed: {type(exc).__name__}") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.log(f"Carrier preferences (order {contact.source_order}): no window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ref = contact.source_order ctx.log(f"Carrier preferences (order {ref}): opening form with window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") _try_step("wait for form", ref, lambda: client.wait_for("#preferences-form", timeout=30)) _try_step("fill email", ref, lambda: client.fill("#email", contact.email)) _try_step("fill name", ref, lambda: client.fill("#name", full_name)) if contact.address: _try_step("fill city", ref, lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.log(f"Carrier preferences (order {ref}): no address on contact; city left blank") _try_step("click save", ref, lambda: client.click("#save")) saved = _try_step( "wait for save confirmation", ref, lambda: client.wait_for(".preferences-saved", timeout=60) ) if saved: ctx.log(f"Carrier preferences (order {ref}): saved") else: ctx.log(f"Carrier preferences (order {ref}): NOT confirmed saved") return saved --- run 25 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) contact = Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) ctx.log( f"Order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(contact.phone)}, " f"has_address={contact.address is not None})" ) return contact def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since} (max {MAX_PAGES} pages)") pages_fetched = 0 for page_num in range(1, MAX_PAGES + 1): if not url: ctx.log(f"No further pages after page {page_num - 1}") break page = client.get_json(url) pages_fetched += 1 if not page: ctx.log(f"Page {page_num}: empty or failed response from shop; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Page {page_num}: no orders; stopping pagination") break orders.extend(batch) ctx.log(f"Page {page_num}: fetched {len(batch)} orders (total so far {len(orders)})") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; " f"later orders were NOT fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages_fetched} page request(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped (invalid or missing email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped (duplicate customer already processed this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {order_id}: skipped (CRM contact {existing.get('id')} " f"already has all available data)" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"Order {order_id}: FAILED to update CRM contact {existing['id']} " f"after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log( f"Order {order_id}: FAILED to create CRM contact (no retry); " f"counted as skipped" ) skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window: ctx.log(f"Order {contact.source_order}: setting delivery window '{window}'") else: window = "weekday-daytime" ctx.log( f"Order {contact.source_order}: no delivery window given; " f"using default '{window}'" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") def _attempt(step: str, action) -> bool: try: action() return True except Exception as exc: ctx.log( f"Order {contact.source_order}: carrier form step '{step}' failed " f"({type(exc).__name__}); continuing" ) return False _attempt("wait for form", lambda: client.wait_for("#preferences-form", timeout=30)) _attempt("fill email", lambda: client.fill("#email", contact.email)) _attempt("fill name", lambda: client.fill("#name", full_name)) if contact.address: _attempt("fill city", lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.log(f"Order {contact.source_order}: no address; city field left blank") _attempt("click save", lambda: client.click("#save")) saved = _attempt( "wait for save confirmation", lambda: client.wait_for(".preferences-saved", timeout=60), ) if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved with carrier") else: ctx.log( f"Order {contact.source_order}: delivery preferences NOT confirmed saved " f"with carrier" ) return saved --- run 26 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email address, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.log( f"Order {order.get('id')}: built contact " f"(has_name={bool(first or last)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since} (max {MAX_PAGES} pages)") pages_fetched = 0 for page_num in range(1, MAX_PAGES + 1): if not url: ctx.log(f"No further pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.log(f"Page {page_num}: shop returned no response or an empty body; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Page {page_num}: contained no orders; stopping pagination") break orders.extend(batch) pages_fetched = page_num ctx.log(f"Page {page_num}: fetched {len(batch)} orders ({len(orders)} total so far)") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES={MAX_PAGES} with more pages still available; " f"remaining orders were NOT fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.log( f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by email " f"({len(by_email['results'])} result(s))" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.log( f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by phone " f"({len(by_phone['results'])} result(s))" ) return match ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync; finished with nothing created, updated or skipped") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped (customer already processed earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {order_id}: skipped (CRM contact {existing.get('id')} already has all fields)" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (no response); counted as skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {len(seen)} unique customers, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.log(f"Contact from order {contact.source_order}: no delivery window given, using default") window = window or "weekday-daytime" ctx.log(f"Contact from order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill the email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill the name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill the city field ({type(exc).__name__})") else: ctx.log("Contact has no address; leaving the city field empty") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click the save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"No save confirmation appeared within 60s ({type(exc).__name__})") if saved: ctx.log(f"Contact from order {contact.source_order}: delivery preferences saved") else: ctx.log(f"Contact from order {contact.source_order}: delivery preferences NOT confirmed as saved") return saved --- run 27 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 # Logging note: customer emails, names, phone numbers and addresses are personal # data, so they are never written to the log. Records are identified by shop # order id or CRM contact id instead. Exceptions are logged by type only, since # their messages can echo back the values that were being submitted. def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"fetch_orders: page {pages + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"fetch_orders: page {pages + 1} contained no orders; stopping pagination") break pages += 1 orders.extend(batch) ctx.log(f"fetch_orders: page {pages} returned {len(batch)} orders (running total {len(orders)})") url = page.get("next") else: if url: ctx.log( f"fetch_orders: hit MAX_PAGES={MAX_PAGES} with more pages remaining; " "results are truncated and some orders were not fetched" ) ctx.log(f"fetch_orders: fetched {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"find_existing: order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): if len(by_email["results"]) > 1: ctx.log( f"find_existing: order {contact.source_order}: {len(by_email['results'])} CRM contacts " "matched by email; using the first" ) ctx.log(f"find_existing: order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"find_existing: order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): if len(by_phone["results"]) > 1: ctx.log( f"find_existing: order {contact.source_order}: {len(by_phone['results'])} CRM contacts " "matched by phone; using the first" ) ctx.log(f"find_existing: order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] ctx.log(f"find_existing: order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"merge: CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"sync_new_customers: starting sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("sync_new_customers: no orders to process; nothing synced") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"sync_new_customers: order {order_id}: skipped, missing or invalid email") skipped += 1 continue if contact.email in seen: ctx.log(f"sync_new_customers: order {order_id}: skipped, customer already processed earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"sync_new_customers: order {order_id}: CRM contact {existing.get('id')} already complete; no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"sync_new_customers: order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"sync_new_customers: order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"sync_new_customers: order {order_id}: update of CRM contact {existing['id']} failed after retry; " "counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"sync_new_customers: order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"sync_new_customers: order {order_id}: CRM contact creation failed; counted as skipped") skipped += 1 ctx.log( f"sync_new_customers: finished; {len(orders)} orders processed, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"set_delivery_preferences: {ref}: opening carrier preferences form with window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={quote_plus(window)}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"set_delivery_preferences: {ref}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"set_delivery_preferences: {ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"set_delivery_preferences: {ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"set_delivery_preferences: {ref}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"set_delivery_preferences: {ref}: no address on contact; city field left blank") try: client.click("#save") except Exception as exc: ctx.log(f"set_delivery_preferences: {ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"set_delivery_preferences: {ref}: no save confirmation within 60s ({type(exc).__name__})" ) if saved: ctx.log(f"set_delivery_preferences: {ref}: delivery preferences saved (window={window})") else: ctx.log(f"set_delivery_preferences: {ref}: delivery preferences NOT confirmed as saved") return saved --- run 28 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 # Logging note: customer emails, names, phone numbers and addresses are personal # data, so log messages refer to records by shop order id or CRM contact id only. def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: ctx.log(f"No further pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.log(f"Shop returned no response for page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Page {page_num} contained no orders; stopping pagination") break orders.extend(batch) ctx.log(f"Page {page_num}: fetched {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " f"later orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.log(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.log(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone") return match ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped (customer already handled earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete, skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry, skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (no retry), skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log( f"Setting delivery preferences for {ref}: window={window}" + (" (default)" if used_default else "") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"{ref}: no address on contact, city field left blank") try: client.click("#save") except Exception as exc: ctx.log(f"{ref}: clicking save failed ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"{ref}: no save confirmation within 60s ({type(exc).__name__})") ctx.log(f"{ref}: delivery preferences {'saved' if saved else 'NOT confirmed saved'}") return saved --- run 29 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from typing import Any, Callable from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no response for order page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.log( f"Stopped after the {MAX_PAGES}-page limit with more orders still available; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} order(s) across {pages} page(s) created after {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.log(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = failed = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: customer already handled earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete, nothing to update") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']} (filled: {', '.join(filled)})") updated += 1 else: ctx.log(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed after retry; counted as skipped") failed += 1 skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {contact.source_order}: creating CRM contact failed (no retry); counted as skipped") failed += 1 skipped += 1 ctx.log( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"(of which {failed} were CRM write failures) from {len(orders)} order(s)" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(step: str, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> bool: """Run one portal step, logging (rather than silently swallowing) any failure.""" try: fn(*args, **kwargs) return True except Exception as exc: ctx.log(f"Carrier portal step '{step}' failed: {type(exc).__name__}") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") _attempt("wait for preferences form", client.wait_for, "#preferences-form", timeout=30) _attempt("fill email", client.fill, "#email", contact.email) _attempt("fill name", client.fill, "#name", full_name) if contact.address: _attempt("fill city", client.fill, "#city", contact.address.get("city", "")) else: ctx.log(f"Order {contact.source_order}: no address on contact, leaving city blank") _attempt("click save", client.click, "#save") saved = _attempt("wait for save confirmation", client.wait_for, ".preferences-saved", timeout=60) if saved: ctx.log(f"Order {contact.source_order}: carrier confirmed delivery preferences saved") else: ctx.log(f"Order {contact.source_order}: no save confirmation from carrier; preferences may not be recorded") return saved --- run 30 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned an empty or failed response on page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; some orders were not fetched") ctx.log(f"Fetched {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.log(f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: matched existing CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate customer within this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete, no update needed") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']} (filled: {', '.join(filled)})") updated += 1 else: ctx.log(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {contact.source_order}: creating CRM contact failed; skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.log(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={quote_plus(window)}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"Order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: clicking save failed ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})") ctx.log(f"Order {contact.source_order}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 31 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop orders page {pages + 1}: empty or failed response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders page {pages + 1}: no orders; stopping pagination") break orders.extend(batch) pages += 1 url = page.get("next") else: if url: ctx.log( f"Stopped fetching orders at the {MAX_PAGES}-page limit with more pages remaining; " "some orders were not synced" ) ctx.log(f"Fetched {len(orders)} order(s) across {pages} page(s) created after {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.log(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already up to date; skipped") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']} (filled: {', '.join(filled)})") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (no retry); skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} order(s), " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log(f"Contact from order {contact.source_order}: no delivery window given; using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.log(f"Contact from order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") def _step(description: str, action) -> bool: try: action() return True except Exception as exc: ctx.log( f"Contact from order {contact.source_order}: {description} failed " f"({type(exc).__name__}); continuing" ) return False _step("waiting for preferences form", lambda: client.wait_for("#preferences-form", timeout=30)) _step("filling email field", lambda: client.fill("#email", contact.email)) _step("filling name field", lambda: client.fill("#name", full_name)) if contact.address: _step("filling city field", lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.log(f"Contact from order {contact.source_order}: no address on file; city left blank") _step("clicking save", lambda: client.click("#save")) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Contact from order {contact.source_order}: no save confirmation from carrier " f"({type(exc).__name__}); preferences may not have been recorded" ) if saved: ctx.log(f"Contact from order {contact.source_order}: delivery preferences saved (window={window})") return saved --- run 32 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES ({MAX_PAGES}) with more orders still available; " "remaining orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: customer already processed this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already complete, no update needed" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed after retry; skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {contact.source_order}: CRM create failed; skipping") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.log(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.log(f"Order {contact.source_order}: setting carrier delivery window to {window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"Order {contact.source_order}: no address on contact, city left blank") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__})" ) if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved with carrier") else: ctx.log(f"Order {contact.source_order}: delivery preferences were NOT confirmed as saved") return saved --- run 33 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from typing import Any, Callable from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no response for order page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.log(f"Fetched order page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.log( f"Stopped after MAX_PAGES={MAX_PAGES} pages with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders created after {since} across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup failed for order {contact.source_order}") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup failed for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (not retried); skipping") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(step: str, contact: Contact, action: Callable[[], Any]) -> bool: """Run one portal step, logging (rather than raising) any failure.""" try: action() return True except Exception as exc: # noqa: BLE001 - portal steps are best-effort ctx.log( f"Delivery preferences for order {contact.source_order}: " f"step '{step}' failed ({type(exc).__name__})" ) return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") _attempt("wait for form", contact, lambda: client.wait_for("#preferences-form", timeout=30)) _attempt("fill email", contact, lambda: client.fill("#email", contact.email)) _attempt("fill name", contact, lambda: client.fill("#name", full_name)) if contact.address: _attempt("fill city", contact, lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.log(f"Order {contact.source_order}: no address on contact; leaving city blank") _attempt("click save", contact, lambda: client.click("#save")) saved = _attempt( "wait for save confirmation", contact, lambda: client.wait_for(".preferences-saved", timeout=60), ) if saved: ctx.log(f"Delivery preferences saved for order {contact.source_order}") else: ctx.log(f"Delivery preferences NOT confirmed for order {contact.source_order}") return saved --- run 34 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages_fetched = 0 for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop order page {page_num} contained no orders; stopping pagination") break orders.extend(batch) pages_fetched = page_num url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES={MAX_PAGES} with more shop pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages_fetched} page(s) created after {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.log( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email " f"({len(by_email['results'])} result(s))" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.log( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone " f"({len(by_phone['results'])} result(s))" ) return match ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete; skipped") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}, filled fields {filled}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed (no response); skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() requested_window = window window = window or "weekday-daytime" ref = f"order {contact.source_order}" if requested_window is None: ctx.log(f"Delivery preferences for {ref}: no window given, using default '{window}'") ctx.log(f"Delivery preferences for {ref}: opening carrier form with window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Delivery preferences for {ref}: form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Delivery preferences for {ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Delivery preferences for {ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Delivery preferences for {ref}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"Delivery preferences for {ref}: contact has no address; city left blank") try: client.click("#save") except Exception as exc: ctx.log(f"Delivery preferences for {ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Delivery preferences for {ref}: save confirmation not seen within 60s " f"({type(exc).__name__})" ) ctx.log(f"Delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 35 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no data for orders page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Orders page {page_num} was empty; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.log( f"Fetched orders page {page_num}: {len(batch)} orders " f"({len(orders)} total, {'more pages' if url else 'last page'})" ) else: if url: ctx.log( f"Stopped after the {MAX_PAGES}-page limit with more orders still available; " "some orders were not fetched" ) return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup failed for order {contact.source_order}") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup failed for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log(f"No orders found since {since}; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.log(f"Syncing {len(orders)} orders into the CRM") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipped order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipped order {order_id}: customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Skipped order {order_id}: CRM contact {existing.get('id')} " "already has all the details" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Updated CRM contact {existing['id']} from order {order_id} " f"(filled: {', '.join(filled)})" ) updated += 1 else: ctx.log( f"Failed to update CRM contact {existing['id']} from order {order_id} " "after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Created CRM contact {new_id} from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}; counted as skipped") skipped += 1 ctx.log(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log("No delivery window given; using default 'weekday-daytime'") window = window or "weekday-daytime" ref = f"contact from order {contact.source_order}" ctx.log(f"Setting delivery window '{window}' with the carrier for {ref}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") def _step(description: str, action) -> bool: try: action() return True except Exception as exc: ctx.log(f"Carrier form: could not {description} for {ref} ({type(exc).__name__}); continuing") return False _step("find the preferences form within 30s", lambda: client.wait_for("#preferences-form", timeout=30)) _step("fill the email field", lambda: client.fill("#email", contact.email)) _step("fill the name field", lambda: client.fill("#name", full_name)) if contact.address: _step("fill the city field", lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.log(f"Carrier form: no address on file for {ref}; city left blank") _step("click save", lambda: client.click("#save")) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Carrier did not confirm the save within 60s for {ref} ({type(exc).__name__}); " "preferences may not have been recorded" ) if saved: ctx.log(f"Carrier confirmed delivery window '{window}' saved for {ref}") return saved --- run 36 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop returned no data for orders page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") else: if url: ctx.log( f"Stopped fetching orders after reaching the {MAX_PAGES}-page limit; " "more orders may remain unsynced" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"CRM email lookup failed for order {contact.source_order}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"CRM phone lookup failed for order {contact.source_order}") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order} matched an existing CRM contact by phone, not email") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipped order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} (order {order_id}) failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {order_id}; filled {', '.join(filled)}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} from order {order_id} after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Created CRM contact {new_id} from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}; skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"Setting carrier delivery window '{window}' for contact from {ref}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Carrier preferences form did not appear within 30s for {ref} ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field on carrier form for {ref} ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field on carrier form for {ref} ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field on carrier form for {ref} ({type(exc).__name__})") else: ctx.log(f"No address on contact from {ref}; leaving city blank on carrier form") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save on carrier form for {ref} ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"No save confirmation from carrier within 60s for {ref} ({type(exc).__name__})") ctx.log(f"Carrier delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 37 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email address; cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since} (up to {MAX_PAGES} pages)") pages_fetched = 0 for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop order page {page_num}: empty or failed response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop order page {page_num}: no orders; stopping pagination") break orders.extend(batch) pages_fetched = page_num ctx.log(f"Shop order page {page_num}: received {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Reached the {MAX_PAGES}-page limit with more pages still available; " "remaining orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log( f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped (customer already processed earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {order_id}: CRM contact {existing.get('id')} already complete; " "no update needed" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " "counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed; counted as skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" label = f"Delivery preferences (order {contact.source_order})" ctx.log(f"{label}: opening carrier form with window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"{label}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"{label}: could not fill the email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"{label}: could not fill the name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"{label}: could not fill the city field ({type(exc).__name__})") else: ctx.log(f"{label}: contact has no address; leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"{label}: could not click the save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"{label}: no save confirmation within 60s ({type(exc).__name__})" ) if saved: ctx.log(f"{label}: carrier confirmed preferences were saved") else: ctx.log(f"{label}: preferences were NOT confirmed as saved") return saved --- run 38 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.log(f"Shop orders page {pages}: fetched {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders created since {since} across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped (customer already handled earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: contact_id = existing.get("id") merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {contact_id} already complete, skipped") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {contact_id} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Order {order_id}: updated CRM contact {contact_id} " f"(filled fields: {', '.join(filled)})" ) updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {contact_id} failed after retry, skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed, skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.log(f"Order {contact.source_order}: no delivery window given, using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.log(f"Order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"Order {contact.source_order}: no address on contact, city field left blank") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__})" ) if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved with carrier") else: ctx.log(f"Order {contact.source_order}: delivery preferences NOT confirmed as saved") return saved --- run 39 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.log(f"Shop orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Shop orders page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.log(f"Shop orders page {pages}: got {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.log( f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; " "some orders were not fetched this run" ) ctx.log(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM lookup by email failed or returned nothing") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM lookup by phone failed or returned nothing") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.log(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped (customer already processed earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already complete, skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry, skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order_id}: created CRM contact {resp.get('id') if isinstance(resp, dict) else ''}".rstrip()) created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed, skipped") skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.log(f"Setting carrier delivery preferences for {ref} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.log(f"{ref}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.log(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"{ref}: no save confirmation within 60s ({type(exc).__name__})") ctx.log(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 40 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 # Log messages identify customers by shop order ID and CRM record ID only. # Emails, names, phone numbers and addresses stay out of the log. def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Shop returned no response for order page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {pages + 1} was empty; stopping pagination") break pages += 1 orders.extend(batch) ctx.log(f"Fetched order page {pages}: {len(batch)} orders") url = page.get("next") else: if url: ctx.log( f"Stopped after MAX_PAGES={MAX_PAGES} pages with more pages remaining; " "some orders were not fetched" ) ctx.log(f"Fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.log(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.log(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.log( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 failed = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: skipped, customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log( f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log( f"Order {order_id}: update of CRM contact {existing['id']} returned no response; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log( f"Order {order_id}: updated CRM contact {existing['id']} " f"(filled fields: {', '.join(filled)})" ) updated += 1 else: ctx.log( f"Order {order_id}: FAILED to update CRM contact {existing['id']} after retry; " "counted as skipped" ) failed += 1 skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.log(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.log( f"Order {order_id}: FAILED to create CRM contact (no response); counted as skipped" ) failed += 1 skipped += 1 ctx.log( f"Customer sync finished: {len(orders)} orders, {created} created, {updated} updated, " f"{skipped} skipped (of which {failed} were failed CRM writes)" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(order_id, step: str, fn, *args, **kwargs) -> bool: """Run one portal step, logging (rather than silently swallowing) any failure.""" try: fn(*args, **kwargs) return True except Exception as exc: ctx.log(f"Order {order_id}: carrier portal step '{step}' failed ({type(exc).__name__})") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" order_id = contact.source_order full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.log(f"Order {order_id}: no delivery window given; using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.log(f"Order {order_id}: opening carrier preferences form with window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") _attempt(order_id, "wait for form", client.wait_for, "#preferences-form", timeout=30) _attempt(order_id, "fill email", client.fill, "#email", contact.email) _attempt(order_id, "fill name", client.fill, "#name", full_name) if contact.address: _attempt(order_id, "fill city", client.fill, "#city", contact.address.get("city", "")) else: ctx.log(f"Order {order_id}: no address on contact; city left blank") _attempt(order_id, "click save", client.click, "#save") saved = _attempt( order_id, "wait for save confirmation", client.wait_for, ".preferences-saved", timeout=60 ) if saved: ctx.log(f"Order {order_id}: delivery preferences saved with carrier") else: ctx.log(f"Order {order_id}: delivery preferences NOT confirmed as saved") return saved Claude Opus 5.5, ctx.narrate (contact sync) =========================================== --- run 1 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for page {pages + 1}; stopping pagination " f"with {len(orders)} order(s) so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Reached the page limit of {MAX_PAGES} while more pages remained; " f"later orders were not fetched." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email; matched existing " f"contact {by_phone['results'][0].get('id')} by phone instead." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders to sync; nothing to do.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped as a repeat customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, filling in {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created a new CRM contact.") created += 1 else: ctx.narrate( f"Order {order_id}: creating the CRM contact failed (no retry); counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate( f"Order {contact.source_order}: no delivery window given; defaulting to weekday-daytime." ) window = window or "weekday-daytime" ctx.narrate( f"Order {contact.source_order}: opening carrier preferences form for window '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Order {contact.source_order}: could not fill the email field ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Order {contact.source_order}: could not fill the name field ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Order {contact.source_order}: could not fill the city field ({type(exc).__name__}).") else: ctx.narrate(f"Order {contact.source_order}: no address on file; city field left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Order {contact.source_order}: clicking Save failed ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})." ) if saved: ctx.narrate(f"Order {contact.source_order}: carrier confirmed delivery preferences were saved.") else: ctx.narrate(f"Order {contact.source_order}: delivery preferences were NOT confirmed as saved.") return saved --- run 2 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for page {pages + 1}; stopping pagination " f"with {len(orders)} order(s) collected so far, which may be incomplete." ) break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Page {pages + 1} contained no orders; pagination finished.") break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported " f"more pages; orders beyond this point were not fetched this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if by_email is None: ctx.narrate( f"CRM email lookup for order {contact.source_order} got no response; " f"treating it as not found." ) if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order} matched CRM contact {match.get('id')} by " f"phone rather than email." ) return match if by_phone is None: ctx.narrate( f"CRM phone lookup for order {contact.source_order} got no response; " f"treating it as not found." ) return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No orders to process; nothing synced.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Update of CRM contact {existing['id']} (order {order_id}) failed; " f"retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Updated CRM contact {existing['id']} from order {order_id}, " f"filling: {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Could not update CRM contact {existing['id']} (order {order_id}) " f"after retry; counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.narrate( f"Could not create CRM contact for order {order_id}; " f"counted as skipped (no retry)." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s) ({len(seen)} distinct customer(s))." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate("No delivery window given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.narrate(f"Opening carrier preferences form for {ref} with window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Preferences form did not appear within 30s for {ref} " f"({type(exc).__name__}); continuing anyway." ) for selector, value in (("#email", contact.email), ("#name", full_name)): try: client.fill(selector, value) except Exception as exc: ctx.narrate( f"Could not fill the {selector} field for {ref} ({type(exc).__name__})." ) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the #city field for {ref} ({type(exc).__name__}).") else: ctx.narrate(f"No address on file for {ref}; leaving the city field blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Clicking Save failed for {ref} ({type(exc).__name__}).") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier confirmed delivery preferences saved for {ref}.") else: ctx.narrate( f"No save confirmation from the carrier within 60s for {ref}; " f"preferences may not have been recorded." ) return saved --- run 3 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Shop returned no data for order page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while more orders remained; " "some orders were not fetched this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s) created after {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, matched an existing " "contact by phone instead." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync for shop orders created after {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = failed = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 no_email += 1 continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Update of CRM contact {existing['id']} (order {contact.source_order}) " "failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate( f"Updated CRM contact {existing['id']} from order {contact.source_order}, " f"filling: {', '.join(filled)}." ) else: skipped += 1 failed += 1 ctx.narrate( f"Could not update CRM contact {existing['id']} (order " f"{contact.source_order}) after retry; counted as skipped." ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created a new CRM contact from order {contact.source_order}.") else: skipped += 1 failed += 1 ctx.narrate( f"Creating a CRM contact from order {contact.source_order} failed " "(no retry); counted as skipped." ) ctx.narrate( f"Sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} without a usable email, {duplicates} repeat customers in this batch, " f"{unchanged} already up to date, {failed} failed CRM writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate("No delivery window given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" ctx.narrate( f"Setting carrier delivery preference '{window}' for the customer from order " f"{contact.source_order}." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " "attempting to fill it anyway." ) problems: list[str] = [] try: client.fill("#email", contact.email) except Exception as exc: problems.append(f"email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: problems.append(f"name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: problems.append(f"city ({type(exc).__name__})") else: ctx.narrate("Customer has no shipping address on file; leaving the city field blank.") if problems: ctx.narrate(f"Could not fill these carrier form fields: {', '.join(problems)}.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Clicking Save on the carrier form failed ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " "the delivery preference may not have been recorded." ) if saved: ctx.narrate(f"Carrier confirmed the '{window}' delivery preference was saved.") return saved --- run 4 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no data for page {pages + 1}; stopping pagination " f"with {len(orders)} orders so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while more pages remained; " f"orders beyond this point were not fetched." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email; matched existing " f"contact {match.get('id')} by phone instead." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, " f"filling {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created a new CRM contact.") created += 1 else: ctx.narrate( f"Order {order_id}: creating a CRM contact failed (not retried); counted as skipped." ) skipped += 1 ctx.narrate( f"Sync finished for {len(orders)} orders: {created} created, {updated} updated, " f"{skipped} skipped (skips include duplicates and records already complete)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" label = f"Delivery preferences for order {contact.source_order}" ctx.narrate(f"{label}: opening the carrier form with window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"{label}: form did not appear within 30s ({type(exc).__name__}); continuing anyway." ) fields = [("#email", contact.email), ("#name", full_name)] if contact.address: fields.append(("#city", contact.address.get("city", ""))) for selector, value in fields: try: client.fill(selector, value) except Exception as exc: ctx.narrate(f"{label}: could not fill {selector} ({type(exc).__name__}); left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"{label}: clicking save failed ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"{label}: no save confirmation within 60s ({type(exc).__name__}); treating as not saved." ) if saved: ctx.narrate(f"{label}: carrier confirmed the preferences were saved.") return saved --- run 5 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Order {order.get('id')} has no usable email address, so it can't become a contact.") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"The shop returned no data for page {pages + 1}; stopping pagination there.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported more pages; " "some orders were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.narrate(f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by email.") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no email match, but matched existing CRM contact " f"{match.get('id')} by phone number." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found, so there is nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order.get('id')}: this customer was already handled earlier in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order.get('id')}: CRM contact {existing.get('id')} already has everything " "this order could add; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order.get('id')}: updating CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order.get('id')}: updated CRM contact {existing['id']}, filling in " f"{', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order.get('id')}: could not update CRM contact {existing['id']} even after " "a retry; counting it as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate( f"Order {order.get('id')}: created a new CRM contact" + (f" ({new_id})." if new_id else ".") ) created += 1 else: ctx.narrate( f"Order {order.get('id')}: creating the CRM contact failed (not retried); " "counting it as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window: ctx.narrate( f"Setting carrier delivery preferences for the customer from order {contact.source_order} " f"with window '{window}'." ) else: ctx.narrate( f"Setting carrier delivery preferences for the customer from order {contact.source_order}; " "no window was given, so defaulting to 'weekday-daytime'." ) window = window or "weekday-daytime" client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The carrier's preferences form didn't appear within 30 seconds ({type(exc).__name__}); " "continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Couldn't fill the email field on the carrier form ({type(exc).__name__}); continuing.") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Couldn't fill the name field on the carrier form ({type(exc).__name__}); continuing.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Couldn't fill the city field on the carrier form ({type(exc).__name__}); continuing.") else: ctx.narrate("This contact has no shipping address on file, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Clicking Save on the carrier form failed ({type(exc).__name__}).") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"The carrier confirmed the delivery preferences were saved (window '{window}').") else: ctx.narrate( "No save confirmation from the carrier within 60 seconds; the delivery preferences " "were probably not recorded." ) return saved --- run 6 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"The shop returned no data for page {pages + 1} of orders; " f"stopping with {len(orders)} order(s) collected so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped fetching orders after the {MAX_PAGES}-page limit while the shop " f"still reported more pages; orders beyond this point were not synced." ) ctx.narrate(f"Fetched {len(orders)} order(s) from the shop across {pages} page(s) since {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched existing " f"contact {by_phone['results'][0].get('id')} by phone number." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order.get('id')}: it has no usable email address.") skipped += 1 no_email += 1 continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Updating CRM contact {existing['id']} (order {contact.source_order}) failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Updated CRM contact {existing['id']} from order {contact.source_order}, " f"filling in: {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Could not update CRM contact {existing['id']} (order {contact.source_order}) " f"after a retry; counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created a new CRM contact from order {contact.source_order}.") created += 1 else: ctx.narrate( f"Creating a CRM contact from order {contact.source_order} failed; counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} without a usable email, {duplicates} repeat customers in this batch, " f"{unchanged} already up to date, {skipped - no_email - duplicates - unchanged} failed writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate( f"No delivery window given for the customer from order {contact.source_order}; " f"using the default 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Opening the carrier's preferences form to set delivery window '{window}' " f"for the customer from order {contact.source_order}." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The carrier's preferences form did not appear within 30s ({type(exc).__name__}); " f"trying to fill it in anyway." ) failed_fields: list[str] = [] try: client.fill("#email", contact.email) except Exception: failed_fields.append("email") try: client.fill("#name", full_name) except Exception: failed_fields.append("name") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception: failed_fields.append("city") if failed_fields: ctx.narrate(f"Could not fill these fields on the carrier form: {', '.join(failed_fields)}.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Clicking Save on the carrier form failed ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception: pass if saved: ctx.narrate( f"The carrier confirmed delivery window '{window}' was saved " f"for the customer from order {contact.source_order}." ) else: ctx.narrate( f"No save confirmation from the carrier within 60s; delivery window '{window}' " f"for the customer from order {contact.source_order} may not have been recorded." ) return saved --- run 7 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages_read = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages_read + 1}; " f"stopping pagination with {len(orders)} order(s) collected so far." ) break batch = page.get("orders") or [] if not batch: break pages_read += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped fetching orders after hitting the {MAX_PAGES}-page limit; " f"more orders remain in the shop and were not synced this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) created since {since} across {pages_read} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched " f"CRM contact {by_phone['results'][0].get('id')} by phone number." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync for shop customers with orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order_id}: it has no usable email address.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Update of CRM contact {existing['id']} (order {order_id}) got no response; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Updated CRM contact {existing['id']} from order {order_id}, " f"filling empty field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Failed to update CRM contact {existing['id']} from order {order_id} after a retry; " f"counted as skipped and the missing details were not saved." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created a new CRM contact from order {order_id}.") created += 1 else: ctx.narrate( f"Failed to create a CRM contact from order {order_id} (no response, not retried); " f"counted as skipped." ) skipped += 1 duplicates = len(orders) - len(seen) - sum(1 for o in orders if _to_contact(o) is None) ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"(including {duplicates} repeat order(s) from customers already handled this run, " f"and existing contacts that needed no changes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate( f"No delivery window given for order {contact.source_order}'s customer; " f"using the default 'weekday-daytime'." ) window = window or "weekday-daytime" client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " f"continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("Contact has no address on file; left the city field on the carrier form blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " f"delivery preferences for order {contact.source_order}'s customer may not have been recorded." ) if saved: ctx.narrate( f"Carrier confirmed delivery window '{window}' for order {contact.source_order}'s customer." ) return saved --- run 8 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping pagination with {len(orders)} orders so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still had more " f"orders; orders beyond page {MAX_PAGES} were not synced this run." ) ctx.narrate(f"Fetched {len(orders)} orders created since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched " f"CRM contact {match.get('id')} by phone number." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = failed = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 no_email += 1 continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Update of CRM contact {existing['id']} (order {contact.source_order}) " f"failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate( f"Updated CRM contact {existing['id']} from order {contact.source_order}, " f"filling empty field(s): {', '.join(filled)}." ) else: skipped += 1 failed += 1 ctx.narrate( f"Could not update CRM contact {existing['id']} (order " f"{contact.source_order}) after retry; counted as skipped." ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: skipped += 1 failed += 1 ctx.narrate( f"Could not create a CRM contact for order {contact.source_order} " f"(no retry attempted); counted as skipped." ) ctx.narrate( f"Sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} without a usable email, {duplicates} repeat customers in this batch, " f"{unchanged} already up to date, {failed} failed CRM writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() defaulted = window is None window = window or "weekday-daytime" ctx.narrate( f"Setting carrier delivery window '{window}'" f"{' (default)' if defaulted else ''} for the customer from order {contact.source_order}." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " f"continuing anyway." ) def _fill(selector: str, value: str, label: str) -> None: try: client.fill(selector, value) except Exception as exc: ctx.narrate(f"Could not fill the {label} field on the carrier form ({type(exc).__name__}).") _fill("#email", contact.email, "email") _fill("#name", full_name, "name") if contact.address: _fill("#city", contact.address.get("city", ""), "city") else: ctx.narrate("No shipping address on file, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier confirmed the delivery preferences for order {contact.source_order}.") else: ctx.narrate( f"No save confirmation from the carrier within 60s for order " f"{contact.source_order}; preferences may not have been recorded." ) return saved --- run 9 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping pagination with {len(orders)} orders so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") if url and pages >= MAX_PAGES: ctx.narrate( f"Stopped fetching orders at the {MAX_PAGES}-page limit while more pages remained; " f"orders beyond the first {len(orders)} were not synced in this run." ) ctx.narrate(f"Fetched {len(orders)} shop orders created since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email; matched CRM contact " f"{match.get('id')} by phone number instead." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate( f"Order {order_id}: skipped because the same customer appeared in an earlier order this run." ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already has all this data; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} got no response; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, filling empty field(s): " f"{', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate( f"Order {order_id}: created new CRM contact" + (f" {new_id}." if new_id is not None else ".") ) created += 1 else: ctx.narrate( f"Order {order_id}: creating CRM contact got no response (not retried); counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None or not window: ctx.narrate( f"Contact from order {contact.source_order}: no delivery window given; " f"defaulting to 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Opening carrier preferences form for contact from order {contact.source_order} " f"with window '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " f"continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("Contact has no address on file; left the city field on the carrier form blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " f"delivery preferences were likely not saved." ) if saved: ctx.narrate( f"Carrier confirmed delivery preferences saved for contact from order {contact.source_order}." ) return saved --- run 10 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no data for order page {pages + 1}; stopping pagination " f"with {len(orders)} orders collected so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported more " f"orders; orders beyond page {MAX_PAGES} were not fetched this run." ) ctx.narrate(f"Fetched {len(orders)} orders created after {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched CRM contact " f"{match.get('id')} by phone number." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of shop customers created after {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = failed = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 no_email += 1 continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {contact.source_order}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate( f"Order {contact.source_order}: updated CRM contact {existing['id']}, " f"filling empty field(s): {', '.join(filled)}." ) else: skipped += 1 failed += 1 ctx.narrate( f"Order {contact.source_order}: update of CRM contact {existing['id']} failed " f"again after retry; counted as skipped." ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: skipped += 1 failed += 1 ctx.narrate( f"Order {contact.source_order}: creating a new CRM contact failed (no retry); " f"counted as skipped." ) ctx.narrate( f"Sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} without a usable email, {duplicates} duplicate emails in this batch, " f"{unchanged} already complete in the CRM, {failed} failed CRM writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate( f"Order {contact.source_order}: no delivery window given; using default 'weekday-daytime'." ) window = window or "weekday-daytime" client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: carrier preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway." ) fields = [("#email", contact.email), ("#name", full_name)] if contact.address: fields.append(("#city", contact.address.get("city", ""))) else: ctx.narrate(f"Order {contact.source_order}: no address on file, so the city field was left blank.") for selector, value in fields: try: client.fill(selector, value) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill carrier form field {selector} " f"({type(exc).__name__}); continuing." ) try: client.click("#save") except Exception as exc: ctx.narrate( f"Order {contact.source_order}: clicking Save on the carrier form failed ({type(exc).__name__})." ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"Order {contact.source_order}: no save confirmation from the carrier within 60s " f"({type(exc).__name__}); preferences may not have been recorded." ) if saved: ctx.narrate(f"Order {contact.source_order}: carrier confirmed delivery window '{window}' was saved.") return saved --- run 11 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Order {order.get('id')} has no usable email address, so it can't become a contact.") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None if address is None: ctx.narrate(f"Order {order.get('id')} has no shipping address; the contact will be created without one.") return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.narrate(f"The shop returned no data for page {pages}; stopping pagination there.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Page {pages} contained no orders; stopping pagination.") break orders.extend(batch) ctx.narrate(f"Page {pages} returned {len(batch)} orders ({len(orders)} so far).") url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported more pages; " "some orders from this period were not fetched." ) ctx.narrate(f"Fetched {len(orders)} orders in total across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.narrate(f"Order {contact.source_order} matches existing CRM contact {match.get('id')} by email.") return match if by_email is None: ctx.narrate(f"The CRM email lookup for order {contact.source_order} returned no response.") if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order} matches existing CRM contact {match.get('id')} by phone " "(the email did not match)." ) return match ctx.narrate(f"No existing CRM contact found for order {contact.source_order}.") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.narrate( f"Filling empty field(s) {', '.join(filled)} on CRM contact {existing.get('id')} " f"from order {contact.source_order}." ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders to sync; nothing was changed in the CRM.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: its customer was already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"CRM contact {existing.get('id')} already has everything order {order.get('id')} " "could add; leaving it unchanged." ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Updating CRM contact {existing['id']} got no response; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") updated += 1 else: ctx.narrate( f"Could not update CRM contact {existing['id']} after a retry; " f"order {order.get('id')} is counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate( f"Created a new CRM contact" f"{f' {new_id}' if new_id else ''} from order {order.get('id')}." ) created += 1 else: ctx.narrate( f"Creating a CRM contact for order {order.get('id')} got no response (not retried); " "counted as skipped." ) skipped += 1 ctx.narrate( f"Sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate("No delivery window was given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" ctx.narrate( f"Opening the carrier's preferences form to set window '{window}' " f"for the customer from order {contact.source_order}." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The preferences form did not appear within 30 seconds ({type(exc).__name__}); " "continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field ({type(exc).__name__}).") else: ctx.narrate("The contact has no address on file, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click the save button ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation appeared within 60 seconds ({type(exc).__name__}); " "the preferences may not have been recorded." ) if saved: ctx.narrate( f"The carrier confirmed delivery window '{window}' for the customer from order {contact.source_order}." ) return saved --- run 12 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping pagination with {len(orders)} orders so far." ) break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {pages + 1} was empty; stopping pagination.") break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported more pages; " f"orders beyond {len(orders)} were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email." ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no email match; matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone instead." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders to sync; nothing was written to the CRM.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order.get('id')}: skipped because it has no usable email.") skipped += 1 continue if contact.email in seen: ctx.narrate( f"Order {contact.source_order}: skipped because an earlier order in this run " f"had the same customer email." ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {contact.source_order}: CRM contact {existing.get('id')} already has " f"everything this order provides; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {contact.source_order}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {contact.source_order}: updated CRM contact {existing['id']}, " f"filling empty field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {contact.source_order}: update of CRM contact {existing['id']} failed again " f"after retry; counted as skipped and not written." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {contact.source_order}: created a new CRM contact.") created += 1 else: ctx.narrate( f"Order {contact.source_order}: creating the CRM contact failed (no retry); " f"counted as skipped and not written." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window: ctx.narrate(f"Order {contact.source_order}: setting carrier delivery window to '{window}'.") else: window = "weekday-daytime" ctx.narrate( f"Order {contact.source_order}: no delivery window given; using default '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: carrier preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the email field ({type(exc).__name__}); " f"continuing without it." ) try: client.fill("#name", full_name) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the name field ({type(exc).__name__}); " f"continuing without it." ) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the city field ({type(exc).__name__}); " f"continuing without it." ) else: ctx.narrate(f"Order {contact.source_order}: contact has no address, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate( f"Order {contact.source_order}: clicking Save on the carrier form failed ({type(exc).__name__})." ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"Order {contact.source_order}: no save confirmation from the carrier within 60s " f"({type(exc).__name__}); delivery preferences were probably not recorded." ) if saved: ctx.narrate(f"Order {contact.source_order}: carrier confirmed delivery preferences were saved.") return saved --- run 13 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since} (up to {MAX_PAGES} pages).") pages_read = 0 for page_number in range(1, MAX_PAGES + 1): if not url: ctx.narrate(f"No further page link after page {page_number - 1}; pagination complete.") break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {page_number}; " f"stopping with {len(orders)} orders collected so far." ) break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_number} was empty; stopping pagination.") break orders.extend(batch) pages_read = page_number ctx.narrate(f"Read order page {page_number}: {len(batch)} orders ({len(orders)} total).") url = page.get("next") else: if url: ctx.narrate( f"Reached the {MAX_PAGES}-page limit while more pages remained; " f"some orders after this point were not fetched." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages_read} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" order_ref = contact.source_order by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.narrate(f"CRM email lookup for order {order_ref} got no response.") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.narrate(f"Order {order_ref}: matched existing CRM contact {match.get('id')} by email.") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.narrate(f"CRM phone lookup for order {order_ref} got no response.") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {order_ref}: no email match, but matched existing CRM contact " f"{match.get('id')} by phone." ) return match ctx.narrate(f"Order {order_ref}: no existing CRM contact found by email or phone.") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.narrate( f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}." ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No orders to sync; nothing created, updated, or skipped.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_ref = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order_ref}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate( f"Skipping order {order_ref}: same customer email as an earlier order in this run." ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Skipping order {order_ref}: CRM contact {existing.get('id')} " f"already has all the information this order provides." ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Update of CRM contact {existing['id']} got no response; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order_ref}.") updated += 1 else: ctx.narrate( f"Failed to update CRM contact {existing['id']} from order {order_ref} " f"after retry; counting it as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate( f"Created CRM contact {new_id if new_id is not None else '(id not returned)'} " f"from order {order_ref}." ) created += 1 else: ctx.narrate( f"Failed to create CRM contact from order {order_ref} (no response); " f"counting it as skipped." ) skipped += 1 ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window: ctx.narrate(f"Setting carrier delivery preference for order {contact.source_order} to '{window}'.") else: ctx.narrate( f"No delivery window given for order {contact.source_order}; " f"using default 'weekday-daytime'." ) window = window or "weekday-daytime" client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " f"continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field ({type(exc).__name__}); continuing.") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field ({type(exc).__name__}); continuing.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field ({type(exc).__name__}); continuing.") else: ctx.narrate("Contact has no address on file; leaving the city field blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click the save button ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " f"preferences may not have been recorded." ) if saved: ctx.narrate( f"Carrier confirmed delivery preference '{window}' for order {contact.source_order}." ) return saved --- run 14 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Shop returned no response for page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while more pages remained; " "some orders were not fetched." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate(f"Order {contact.source_order}: matched existing CRM contact by email.") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate(f"Order {contact.source_order}: matched existing CRM contact by phone.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped, no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped, customer already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.narrate( f"Order {order_id}: updating CRM contact {existing['id']} to fill {', '.join(filled)}." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {order_id}: update of contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.narrate( f"Order {order_id}: update of contact {existing['id']} failed after retry; counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created new CRM contact.") created += 1 else: ctx.narrate(f"Order {order_id}: creating CRM contact failed; counted as skipped.") skipped += 1 ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"from {len(orders)} order(s)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate("No delivery window given; defaulting to weekday-daytime.") window = window or "weekday-daytime" ref = f"contact from order {contact.source_order}" ctx.narrate(f"Opening carrier preferences form for {ref} with window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway.") try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field ({type(exc).__name__}).") else: ctx.narrate("No address on file; leaving the city field blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate(f"No save confirmation within 60s ({type(exc).__name__}).") if saved: ctx.narrate(f"Carrier confirmed delivery preferences saved for {ref}.") else: ctx.narrate(f"Delivery preferences were not confirmed as saved for {ref}.") return saved --- run 15 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Shop returned no data for order page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped fetching orders at the {MAX_PAGES}-page limit; more orders may exist " "and were not synced in this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s) created after {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched existing " f"contact {by_phone['results'][0].get('id')} by phone." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of shop customers created after {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped as a repeat customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already has all details; " "no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, filling in " f"{', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: could not update CRM contact {existing['id']} after retry; " "counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created a new CRM contact.") created += 1 else: ctx.narrate( f"Order {order_id}: CRM rejected or failed to create the new contact; " "counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() defaulted = window is None or window == "" window = window or "weekday-daytime" ref = f"contact from order {contact.source_order}" ctx.narrate( f"Setting carrier delivery window '{window}' for {ref}" + (" (no window given, using the default)." if defaulted else ".") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception: ctx.narrate("Carrier preferences form did not appear within 30s; continuing anyway.") try: client.fill("#email", contact.email) except Exception: ctx.narrate("Could not fill the email field on the carrier form.") try: client.fill("#name", full_name) except Exception: ctx.narrate("Could not fill the name field on the carrier form.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception: ctx.narrate("Could not fill the city field on the carrier form.") else: ctx.narrate("No address on file, so the city field was left blank.") try: client.click("#save") except Exception: ctx.narrate("Could not click Save on the carrier form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier confirmed the delivery preferences were saved for {ref}.") else: ctx.narrate( f"No save confirmation from the carrier within 60s for {ref}; " "preferences may not have been recorded." ) return saved --- run 16 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping pagination with {len(orders)} orders so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Hit the {MAX_PAGES}-page limit while fetching orders; " f"more orders exist that were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} page(s) created since {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, " f"matched existing contact {by_phone['results'][0].get('id')} by phone." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped, no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped, same customer already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, " f"filled empty field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate( f"Order {order_id}: created new CRM contact" + (f" {new_id}." if new_id else ".") ) created += 1 else: ctx.narrate( f"Order {order_id}: creating CRM contact failed (no response); counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() defaulted = window is None or window == "" window = window or "weekday-daytime" ctx.narrate( f"Setting carrier delivery preferences for the customer from order {contact.source_order}: " f"window '{window}'" + (" (default)." if defaulted else ".") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " f"continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("Contact has no address on file; left the city field blank on the carrier form.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " f"preferences may not have been recorded." ) if saved: ctx.narrate( f"Carrier confirmed delivery preferences saved for the customer from order " f"{contact.source_order}." ) return saved --- run 17 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Shop returned no response for order page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Reached the {MAX_PAGES}-page limit while fetching orders; " "more orders may exist and were not fetched." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} page(s) created after {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email; " f"matched CRM contact {match.get('id')} by phone instead." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync for shop orders created after {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped because its customer was already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already has all available details; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, filling in {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate(f"Order {order_id}: created new CRM contact{f' {new_id}' if new_id else ''}.") created += 1 else: ctx.narrate(f"Order {order_id}: creating a CRM contact failed (no retry); counted as skipped.") skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate( f"Contact from order {contact.source_order}: no delivery window given; " "using default 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Setting carrier delivery window '{window}' for contact from order {contact.source_order}." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("Contact has no address on file; left the city field blank on the carrier form.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " "delivery preferences were not confirmed as saved." ) if saved: ctx.narrate( f"Carrier confirmed delivery window '{window}' saved for contact from order {contact.source_order}." ) return saved --- run 18 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from collections.abc import Callable from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping with {len(orders)} orders, which may be incomplete." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped at the {MAX_PAGES}-page limit with more orders still available; " f"orders beyond the first {len(orders)} were not synced." ) ctx.narrate(f"Fetched {len(orders)} orders since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.narrate(f"CRM email lookup for order {contact.source_order} got no response.") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.narrate(f"CRM phone lookup for order {contact.source_order} got no response.") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order} had no email match; matched CRM contact " f"{match.get('id')} by phone only, so it will be merged into that record." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 failed = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update of CRM contact {existing['id']} got no response; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Updated CRM contact {existing['id']} from order {order_id}, " f"filling: {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Failed to update CRM contact {existing['id']} from order {order_id} " f"after a retry; counted as skipped." ) failed += 1 skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.narrate( f"Failed to create a CRM contact for order {order_id} (no response); " f"counted as skipped." ) failed += 1 skipped += 1 ctx.narrate( f"Sync finished: {created} created, {updated} updated, {skipped} skipped " f"({failed} of the skips were CRM write failures) out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def _try_step(order_ref: object, step: str, action: Callable[[], object]) -> bool: """Run one portal step, narrating (but not raising) if it fails.""" try: action() return True except Exception as exc: ctx.narrate( f"Carrier portal step '{step}' failed for order {order_ref} " f"({type(exc).__name__}); continuing." ) return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate(f"No delivery window given for order {contact.source_order}; using weekday-daytime.") window = window or "weekday-daytime" ref = contact.source_order client.open(f"{CARRIER_URL}/preferences/new?window={window}") _try_step(ref, "wait for form", lambda: client.wait_for("#preferences-form", timeout=30)) _try_step(ref, "fill email", lambda: client.fill("#email", contact.email)) _try_step(ref, "fill name", lambda: client.fill("#name", full_name)) if contact.address: _try_step(ref, "fill city", lambda: client.fill("#city", contact.address.get("city", ""))) _try_step(ref, "click save", lambda: client.click("#save")) saved = _try_step( ref, "wait for save confirmation", lambda: client.wait_for(".preferences-saved", timeout=60) ) if saved: ctx.narrate(f"Carrier saved delivery window '{window}' for order {ref}.") else: ctx.narrate(f"Carrier did not confirm saving delivery window '{window}' for order {ref}.") return saved --- run 19 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping pagination with {len(orders)} orders so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still had more " f"orders; orders beyond this point were not synced." ) ctx.narrate(f"Fetched {len(orders)} orders created since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched " f"CRM contact {match.get('id')} by phone number." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, " f"filling empty field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed again " f"after retry; counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.narrate( f"Order {order_id}: creating a new CRM contact failed; counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {len(orders)} orders processed, {created} contacts created, " f"{updated} updated, {skipped} skipped (includes duplicates and records already complete)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate( f"Order {contact.source_order}: no delivery window given; using default 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Order {contact.source_order}: opening carrier preferences form for window '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: carrier form did not appear within 30s " f"({type(exc).__name__}); continuing anyway." ) fields = [("#email", contact.email), ("#name", full_name)] if contact.address: fields.append(("#city", contact.address.get("city", ""))) for selector, value in fields: try: client.fill(selector, value) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill carrier form field {selector} " f"({type(exc).__name__}); continuing without it." ) try: client.click("#save") except Exception as exc: ctx.narrate( f"Order {contact.source_order}: clicking Save on the carrier form failed " f"({type(exc).__name__})." ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"Order {contact.source_order}: carrier never confirmed the save within 60s " f"({type(exc).__name__}); delivery preferences were likely not recorded." ) if saved: ctx.narrate( f"Order {contact.source_order}: carrier confirmed delivery window '{window}' was saved." ) return saved --- run 20 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping with {len(orders)} orders fetched so far, which may be incomplete." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still had more orders; " f"orders beyond the first {len(orders)} were not synced this run." ) ctx.narrate(f"Fetched {len(orders)} orders created since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM contact matched by email, " f"but contact {match.get('id')} matched by phone; treating it as the same person." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of shop customers created since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order_id}: it has no usable email address.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Update of CRM contact {existing['id']} (order {order_id}) got no response; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate( f"Updated CRM contact {existing['id']} from order {order_id}, " f"filling empty field(s): {', '.join(filled)}." ) else: ctx.narrate( f"Failed to update CRM contact {existing['id']} from order {order_id} " f"after a retry; counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created a new CRM contact from order {order_id}.") else: ctx.narrate( f"Failed to create a CRM contact from order {order_id} " f"(no response, not retried); counted as skipped." ) skipped += 1 duplicates = len(orders) - len(seen) - sum(1 for o in orders if _to_contact(o) is None) ctx.narrate( f"Sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders ({duplicates} were repeat orders from an already-processed customer)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None or window == "": ctx.narrate( f"No delivery window given for order {contact.source_order}'s customer; " f"using the default 'weekday-daytime'." ) window = window or "weekday-daytime" client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " f"continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("Contact has no address on file; left the city field on the carrier form blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " f"the '{window}' delivery preference for order {contact.source_order}'s customer " f"may not have been recorded." ) if saved: ctx.narrate( f"Carrier confirmed the '{window}' delivery preference for order {contact.source_order}'s customer." ) return saved --- run 21 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"The shop returned no response for page {pages + 1} of orders; " f"stopping pagination with {len(orders)} orders collected so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped fetching orders after the {MAX_PAGES}-page limit even though the shop " f"reported more pages; orders beyond that limit were not synced in this run." ) ctx.narrate(f"Fetched {len(orders)} orders created since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched existing " f"contact {by_phone['results'][0].get('id')} by phone number." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync from the shop into the CRM for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = failed = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 no_email += 1 continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {contact.source_order}: updating CRM contact {existing['id']} failed; " f"retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate( f"Order {contact.source_order}: filled empty fields ({', '.join(filled)}) " f"on existing CRM contact {existing['id']}." ) else: skipped += 1 failed += 1 ctx.narrate( f"Order {contact.source_order}: update to CRM contact {existing['id']} failed " f"after a retry; counted as skipped." ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: skipped += 1 failed += 1 ctx.narrate( f"Order {contact.source_order}: creating a new CRM contact failed " f"(no retry); counted as skipped." ) ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} with no usable email, {duplicates} duplicate emails in this batch, " f"{unchanged} already up to date, {failed} failed CRM writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate( f"Order {contact.source_order}: no delivery window given; using the default " f"'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Order {contact.source_order}: opening the carrier's preferences form to set " f"delivery window '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: the preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the email field ({type(exc).__name__})." ) try: client.fill("#name", full_name) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the name field ({type(exc).__name__})." ) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the city field " f"({type(exc).__name__})." ) else: ctx.narrate(f"Order {contact.source_order}: no address on file, so city was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate( f"Order {contact.source_order}: clicking Save failed ({type(exc).__name__})." ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"Order {contact.source_order}: no save confirmation from the carrier within 60s " f"({type(exc).__name__})." ) if saved: ctx.narrate( f"Order {contact.source_order}: carrier confirmed delivery window '{window}' was saved." ) else: ctx.narrate( f"Order {contact.source_order}: delivery preferences were not confirmed as saved." ) return saved --- run 22 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for page {pages + 1}; stopping pagination " f"with {len(orders)} order(s) collected so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported more pages; " f"orders beyond this point were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.narrate(f"CRM email lookup for order {contact.source_order} got no response.") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.narrate(f"CRM phone lookup for order {contact.source_order} got no response.") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order} had no email match in the CRM but matched " f"contact {by_phone['results'][0].get('id')} by phone number." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = failed = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order.get('id')}: no usable email address.") skipped += 1 no_email += 1 continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Update of CRM contact {existing['id']} (order {contact.source_order}) " f"got no response; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Updated CRM contact {existing['id']} from order {contact.source_order}, " f"filling empty field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Failed to update CRM contact {existing['id']} (order {contact.source_order}) " f"after a retry; counted as skipped." ) skipped += 1 failed += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created a new CRM contact from order {contact.source_order}.") created += 1 else: ctx.narrate( f"Failed to create a CRM contact from order {contact.source_order} " f"(no response, not retried); counted as skipped." ) skipped += 1 failed += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} without a usable email, {duplicates} repeat customers in this batch, " f"{unchanged} already up to date, {failed} failed CRM writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate( f"No delivery window given for order {contact.source_order}; " f"using the default 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Opening the carrier preferences form for order {contact.source_order} " f"with window '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " f"continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate(f"Order {contact.source_order} has no shipping address; left the city field blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate( f"Carrier confirmed the delivery preferences were saved for order {contact.source_order}." ) else: ctx.narrate( f"No save confirmation from the carrier within 60s for order {contact.source_order}; " f"preferences may not have been recorded." ) return saved --- run 23 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Order {order.get('id')} has no usable email address; it can't become a contact.") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"The shop returned no response for page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported more pages; " "some orders were not fetched." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate( f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email." ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no email match, but matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone." ) return by_phone["results"][0] ctx.narrate(f"Order {contact.source_order}: no existing CRM contact found.") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync for new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {contact.source_order}: same customer as an earlier order in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {contact.source_order}: CRM contact {existing.get('id')} already has everything " "this order provides; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.narrate( f"Order {contact.source_order}: updating CRM contact {existing.get('id')} " f"to fill missing field(s): {', '.join(filled)}." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update of CRM contact {existing.get('id')} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.narrate( f"Update of CRM contact {existing.get('id')} failed again; counting order " f"{contact.source_order} as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {contact.source_order}: created a new CRM contact.") created += 1 else: ctx.narrate( f"Order {contact.source_order}: creating the CRM contact failed (no retry); counting it as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate("No delivery window given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" ctx.narrate( f"Opening the carrier's preferences form for the customer from order {contact.source_order} " f"with delivery window '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The preferences form didn't appear within 30 seconds ({type(exc).__name__}); " "continuing anyway, so the steps below may fail." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Couldn't fill the email field ({type(exc).__name__}); continuing without it.") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Couldn't fill the name field ({type(exc).__name__}); continuing without it.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Couldn't fill the city field ({type(exc).__name__}); continuing without it.") else: ctx.narrate("The contact has no address on file, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Couldn't click the save button ({type(exc).__name__}).") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"The carrier confirmed delivery preferences were saved for order {contact.source_order}.") else: ctx.narrate( f"No save confirmation from the carrier within 60 seconds for order {contact.source_order}; " "the preferences were probably not recorded." ) return saved --- run 24 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Order {order.get('id')} has no usable email address; it can't become a contact.") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"The shop returned no data for page {pages + 1} of orders; stopping there.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still had more orders; " "some new customers were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} orders created since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email." ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no email match, but matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone number." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.narrate( f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)} from the shop order." ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order.get('id')}: same customer as an earlier order in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Updating CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.narrate( f"Updating CRM contact {existing['id']} failed again; leaving it unchanged " "and counting it as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.narrate( f"Order {order.get('id')}: creating a new CRM contact failed; " "the customer was not added and is counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate("No delivery window given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" ctx.narrate( f"Opening the carrier's delivery-preferences form for the customer from order " f"{contact.source_order} (window: {window})." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The preferences form didn't appear within 30s ({type(exc).__name__}); trying to fill it anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Couldn't fill the email field ({type(exc).__name__}); continuing.") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Couldn't fill the name field ({type(exc).__name__}); continuing.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Couldn't fill the city field ({type(exc).__name__}); continuing.") else: ctx.narrate("The customer has no address on file, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Couldn't click Save on the preferences form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"The carrier never confirmed the preferences were saved within 60s ({type(exc).__name__})." ) if saved: ctx.narrate(f"The carrier confirmed the delivery preferences were saved (window: {window}).") return saved --- run 25 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Shop returned no response for page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.narrate(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} so far).") url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while more pages remained; " "some orders were not fetched." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} pages.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.narrate(f"CRM email lookup failed for order {contact.source_order}.") if by_email and by_email.get("results"): ctx.narrate(f"Order {contact.source_order} matched CRM contact {by_email['results'][0].get('id')} by email.") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.narrate(f"CRM phone lookup failed for order {contact.source_order}.") if by_phone and by_phone.get("results"): ctx.narrate(f"Order {contact.source_order} matched CRM contact {by_phone['results'][0].get('id')} by phone.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.narrate(f"Filling empty fields on CRM contact {existing.get('id')}: {', '.join(filled)}.") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order_id}: no usable email.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order_id}: customer already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing['id']} already complete; nothing to update.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order_id}.") updated += 1 else: ctx.narrate(f"Update of CRM contact {existing['id']} failed after retry; counting order {order_id} as skipped.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created a new CRM contact from order {order_id}.") created += 1 else: ctx.narrate(f"Creating a CRM contact from order {order_id} failed; counting it as skipped.") skipped += 1 ctx.narrate( f"Sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate("No delivery window given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" ctx.narrate(f"Opening the carrier preferences form for order {contact.source_order} with window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway.") try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field ({type(exc).__name__}).") else: ctx.narrate("Contact has no address; leaving the city field blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate(f"No save confirmation within 60s ({type(exc).__name__}).") if saved: ctx.narrate(f"Carrier confirmed delivery preferences saved for order {contact.source_order}.") else: ctx.narrate(f"Delivery preferences were not confirmed as saved for order {contact.source_order}.") return saved --- run 26 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " "stopping pagination, so later orders may be missing." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported " "more pages; orders beyond this point were not fetched." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched " f"CRM contact {match.get('id')} by phone number." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, " f"filling empty field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " "counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.narrate( f"Order {order_id}: creating a new CRM contact failed; counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate("No delivery window given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" label = f"contact from order {contact.source_order}" ctx.narrate(f"Opening the carrier preferences form for {label} with window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " "continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field ({type(exc).__name__}); continuing.") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field ({type(exc).__name__}); continuing.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field ({type(exc).__name__}); continuing.") else: ctx.narrate("Contact has no address on file; leaving the city field empty.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click the save button ({type(exc).__name__}).") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier confirmed delivery preferences were saved for {label}.") else: ctx.narrate( f"No save confirmation from the carrier within 60s for {label}; " "preferences may not have been recorded." ) return saved --- run 27 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Shop returned no response for page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.narrate(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} total so far).") url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit even though the shop reported more pages; " "some orders were not fetched." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} pages.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate(f"Order {contact.source_order}: matched existing CRM contact by email.") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate(f"Order {contact.source_order}: matched existing CRM contact by phone.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped, no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped, customer already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.narrate( f"Order {order_id}: updating CRM contact {existing.get('id')} to fill in {', '.join(filled)}." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing.get('id')} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing.get('id')} failed after retry; " "counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created new CRM contact.") created += 1 else: ctx.narrate(f"Order {order_id}: creating CRM contact failed (no retry); counted as skipped.") skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window: ctx.narrate(f"Setting carrier delivery window '{window}' for order {contact.source_order}'s customer.") else: window = "weekday-daytime" ctx.narrate( f"No delivery window given for order {contact.source_order}'s customer; " f"using default '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("Customer has no shipping address on file; leaving the city field blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"Carrier did not confirm the save within 60s ({type(exc).__name__})." ) if saved: ctx.narrate(f"Carrier confirmed delivery preferences saved for order {contact.source_order}'s customer.") else: ctx.narrate( f"Delivery preferences were NOT confirmed for order {contact.source_order}'s customer." ) return saved --- run 28 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping pagination with {len(orders)} orders so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Hit the {MAX_PAGES}-page limit while fetching shop orders; " f"more orders exist that were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} shop orders across {pages} page(s) created after {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, " f"matched existing contact {by_phone['results'][0].get('id')} by phone instead." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync for shop customers created after {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new shop orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped because its customer was already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already has all this " f"information; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, " f"filling empty field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed again after retry; " f"counted as skipped and the CRM record was not changed." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created a new CRM contact.") created += 1 else: ctx.narrate( f"Order {order_id}: creating a new CRM contact failed (no retry); " f"counted as skipped and the customer is not in the CRM." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate( f"Order {contact.source_order}: no delivery window given; " f"defaulting to 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Order {contact.source_order}: opening carrier preferences form with window '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: carrier preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the email field on the carrier form " f"({type(exc).__name__}); continuing without it." ) try: client.fill("#name", full_name) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the name field on the carrier form " f"({type(exc).__name__}); continuing without it." ) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: could not fill the city field on the carrier form " f"({type(exc).__name__}); continuing without it." ) else: ctx.narrate( f"Order {contact.source_order}: no shipping address on file, so the city field was left blank." ) try: client.click("#save") except Exception as exc: ctx.narrate( f"Order {contact.source_order}: clicking Save on the carrier form failed " f"({type(exc).__name__})." ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"Order {contact.source_order}: carrier never confirmed the preferences were saved within 60s " f"({type(exc).__name__}); delivery preferences were NOT recorded." ) if saved: ctx.narrate( f"Order {contact.source_order}: carrier confirmed delivery window '{window}' was saved." ) return saved --- run 29 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages_read = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages_read + 1}; " "stopping pagination early, so some orders may be missing." ) break batch = page.get("orders") or [] if not batch: break orders.extend(batch) pages_read += 1 url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported " "more pages; orders beyond that were not synced in this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages_read} page(s) created since {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched CRM " f"contact {by_phone['results'][0].get('id')} by phone number." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of shop customers created since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped because this customer was already handled earlier in the run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already has all " "available details; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, filling in " f"{', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: could not update CRM contact {existing['id']} after a retry; " "counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate( f"Order {order_id}: created new CRM contact" + (f" {new_id}." if new_id else ".") ) created += 1 else: ctx.narrate( f"Order {order_id}: CRM rejected or did not respond to contact creation; " "counted as skipped (not retried)." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate("No delivery window given; defaulting to weekday-daytime.") window = window or "weekday-daytime" label = f"contact from order {contact.source_order}" ctx.narrate(f"Opening carrier preferences form for {label} with window {window}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " "continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate(f"No address on file for {label}; leaving the city field blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " f"delivery preferences for {label} may not have been recorded." ) if saved: ctx.narrate(f"Carrier confirmed delivery preferences saved for {label} (window {window}).") return saved --- run 30 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Order {order.get('id')} has no usable email address; it can't become a contact.") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.narrate(f"The shop returned no response for page {pages}; stopping pagination there.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit even though the shop reported more pages; " "some orders were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate( f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email." ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no email match, but matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone number." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.narrate(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}.") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order.get('id')}: same customer as an earlier order in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"CRM contact {existing.get('id')} already has everything this order provides; no update needed.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Updating CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']} after a retry; counted as skipped.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {contact.source_order}: created a new CRM contact.") created += 1 else: ctx.narrate(f"Order {contact.source_order}: creating the CRM contact failed; counted as skipped.") skipped += 1 ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate("No delivery window given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" ctx.narrate(f"Opening the carrier's preferences form for order {contact.source_order} with window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") form_ready = False with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) form_ready = True if not form_ready: ctx.narrate("The preferences form did not appear within 30 seconds; continuing anyway.") failed_fields = [] ok = False with contextlib.suppress(Exception): client.fill("#email", contact.email) ok = True if not ok: failed_fields.append("email") ok = False with contextlib.suppress(Exception): client.fill("#name", full_name) ok = True if not ok: failed_fields.append("name") if contact.address: ok = False with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ok = True if not ok: failed_fields.append("city") else: ctx.narrate("Contact has no address on file, so the city field was left blank.") if failed_fields: ctx.narrate(f"Could not fill these form fields: {', '.join(failed_fields)}.") clicked = False with contextlib.suppress(Exception): client.click("#save") clicked = True if not clicked: ctx.narrate("Clicking the Save button failed.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"The carrier confirmed the delivery preference was saved for order {contact.source_order}.") else: ctx.narrate( f"No save confirmation from the carrier within 60 seconds for order {contact.source_order}; " "the preference may not have been recorded." ) return saved --- run 31 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages_read = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages_read + 1}; " f"stopping pagination with {len(orders)} orders collected." ) break batch = page.get("orders") or [] if not batch: break pages_read += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Reached the {MAX_PAGES}-page limit while fetching orders; " f"more orders exist that were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages_read} page(s) created after {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone, not email." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders created after {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped, no usable email address.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, " f"filled empty fields: {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped and not applied." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.narrate( f"Order {order_id}: creating a new CRM contact failed; " f"counted as skipped and the customer is not in the CRM." ) skipped += 1 ctx.narrate( f"Sync finished over {len(orders)} orders: {created} created, {updated} updated, " f"{skipped} skipped (includes duplicates, unchanged records, and failures)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate( f"Order {contact.source_order}: no delivery window given; using default 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate(f"Order {contact.source_order}: opening carrier preferences form for window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway." ) failed_fields: list[str] = [] try: client.fill("#email", contact.email) except Exception: failed_fields.append("email") try: client.fill("#name", full_name) except Exception: failed_fields.append("name") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception: failed_fields.append("city") else: ctx.narrate(f"Order {contact.source_order}: no address on file, so city was left blank.") if failed_fields: ctx.narrate( f"Order {contact.source_order}: could not fill form field(s): {', '.join(failed_fields)}." ) try: client.click("#save") except Exception as exc: ctx.narrate( f"Order {contact.source_order}: clicking save failed ({type(exc).__name__})." ) saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Order {contact.source_order}: carrier confirmed delivery preferences were saved.") else: ctx.narrate( f"Order {contact.source_order}: no save confirmation from carrier within 60s; " f"delivery preferences were likely not recorded." ) return saved --- run 32 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Order {order.get('id')} has no usable email address; it can't become a contact.") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None if address is None: ctx.narrate(f"Order {order.get('id')} has no shipping address; the contact will be created without one.") return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"The shop returned no data for page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Reached the {MAX_PAGES}-page limit with more orders still available; " "later orders were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.narrate(f"Order {contact.source_order} matched existing CRM contact {match.get('id')} by email.") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order} matched existing CRM contact {match.get('id')} by phone " "(no email match)." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.narrate(f"Filling empty field(s) on CRM contact {existing.get('id')}: {', '.join(filled)}.") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order.get('id')} is from a customer already handled in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"CRM contact {existing.get('id')} already has everything from order {order.get('id')}; no update needed.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Updating CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") updated += 1 else: ctx.narrate( f"Updating CRM contact {existing['id']} failed again after a retry; " f"order {order.get('id')} counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created a new CRM contact from order {order.get('id')}.") created += 1 else: ctx.narrate( f"Creating a CRM contact from order {order.get('id')} failed (no retry); counted as skipped." ) skipped += 1 ctx.narrate(f"Sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate("No delivery window given; defaulting to weekday-daytime.") window = window or "weekday-daytime" ctx.narrate(f"Setting delivery window '{window}' with the carrier for the contact from order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The carrier's preferences form didn't appear within 30 seconds ({type(exc).__name__}); " "continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Couldn't fill the email field on the carrier form ({type(exc).__name__}); continuing.") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Couldn't fill the name field on the carrier form ({type(exc).__name__}); continuing.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Couldn't fill the city field on the carrier form ({type(exc).__name__}); continuing.") else: ctx.narrate("The contact has no address, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Clicking Save on the carrier form failed ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60 seconds ({type(exc).__name__}); " "the delivery preference may not have been recorded." ) if saved: ctx.narrate(f"The carrier confirmed the delivery window '{window}' was saved.") return saved --- run 33 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for order page {pages + 1}; " f"stopping pagination with {len(orders)} orders so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Reached the {MAX_PAGES}-page limit while more shop orders remained; " f"later orders were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} shop orders created after {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, matched CRM contact " f"{by_phone['results'][0].get('id')} by phone instead." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new shop orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 no_email += 1 ctx.narrate(f"Order {order.get('id')}: skipped, no usable email address.") continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {contact.source_order}: update of CRM contact {existing['id']} " f"got no response; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate( f"Order {contact.source_order}: updated CRM contact {existing['id']}, " f"filling {', '.join(filled)}." ) else: skipped += 1 ctx.narrate( f"Order {contact.source_order}: failed to update CRM contact " f"{existing['id']} after retry; counted as skipped." ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate( f"Order {contact.source_order}: created new CRM contact" + (f" {new_id}." if new_id else ".") ) else: skipped += 1 ctx.narrate( f"Order {contact.source_order}: CRM did not accept the new contact " f"(no response); counted as skipped." ) ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} without usable email, {duplicates} repeat customers in this batch, " f"{unchanged} already up to date, {skipped - no_email - duplicates - unchanged} failed writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None window = window or "weekday-daytime" ctx.narrate( f"Setting carrier delivery window '{window}'" + (" (default)" if used_default else "") + f" for the customer from order {contact.source_order}." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " f"continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("No shipping address on file, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__})." ) if saved: ctx.narrate(f"Carrier confirmed delivery window '{window}' was saved.") else: ctx.narrate(f"Delivery window '{window}' was not confirmed as saved with the carrier.") return saved --- run 34 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.narrate( f"Shop returned no data for orders page {pages}; stopping pagination " f"with {len(orders)} orders collected so far." ) break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") if url and pages >= MAX_PAGES: ctx.narrate( f"Stopped fetching orders after the {MAX_PAGES}-page limit even though the shop " f"reported more pages; orders beyond this point were not synced in this run." ) ctx.narrate(f"Fetched {len(orders)} shop orders created since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"No CRM contact matched the email for order {contact.source_order}, " f"but CRM contact {match.get('id')} matched by phone number; treating it as the same person." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync for shop customers with orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = failed = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 no_email += 1 continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Updating CRM contact {existing['id']} (from order {contact.source_order}) failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: skipped += 1 failed += 1 ctx.narrate( f"Could not update CRM contact {existing['id']} (from order {contact.source_order}) " f"after a retry; counting it as skipped." ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: skipped += 1 failed += 1 ctx.narrate( f"Could not create a CRM contact for order {contact.source_order}; " f"the CRM rejected or did not answer the request. Counting it as skipped." ) ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} orders without a usable email, {duplicates} repeat customers in this batch, " f"{unchanged} already up to date, {failed} failed CRM writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate( f"No delivery window given for the contact from order {contact.source_order}; " f"using the default 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Opening the carrier portal to set delivery window '{window}' for the contact from order {contact.source_order}." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The carrier preferences form did not appear within 30 seconds ({type(exc).__name__}); " f"trying to fill it in anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("The contact has no shipping address, so the city field was left blank on the carrier form.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate( f"The carrier confirmed the delivery window '{window}' for the contact from order {contact.source_order}." ) else: ctx.narrate( f"No save confirmation from the carrier within 60 seconds for the contact from order " f"{contact.source_order}; the delivery preference may not have been recorded." ) return saved --- run 35 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") pages_read = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no data for order page {pages_read + 1}; " "stopping pagination here, so later orders (if any) were not fetched." ) break batch = page.get("orders") or [] if not batch: break pages_read += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Reached the {MAX_PAGES}-page limit while more order pages remained; " "orders beyond this point were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages_read} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched " f"existing CRM contact {by_phone['results'][0].get('id')} by phone number." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders to sync; nothing was sent to the CRM.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate( f"Order {order_id}: skipped because an earlier order in this run " "already had the same customer email." ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: existing_id = existing.get("id") merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing_id} already has all of this " "customer's details; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: updating CRM contact {existing_id} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing_id}, filling empty " f"field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: could not update CRM contact {existing_id} after a retry; " "counted as skipped, and the CRM record is unchanged." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created a new CRM contact.") created += 1 else: ctx.narrate( f"Order {order_id}: creating a new CRM contact failed (no retry); " "counted as skipped, so this customer is not in the CRM." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" label = f"Order {contact.source_order}" ctx.narrate( f"{label}: opening the carrier preferences form with delivery window '{window}'" + (" (the default, since none was given)." if used_default else ".") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"{label}: the preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"{label}: could not fill the email field ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"{label}: could not fill the name field ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"{label}: could not fill the city field ({type(exc).__name__}).") else: ctx.narrate(f"{label}: no shipping address on file, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"{label}: clicking Save failed ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"{label}: no save confirmation from the carrier within 60s " f"({type(exc).__name__}); the delivery preference may not have been recorded." ) if saved: ctx.narrate(f"{label}: carrier confirmed the delivery preference '{window}' was saved.") return saved --- run 36 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Shop returned no response for order page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported more orders; " "some orders since this timestamp were not fetched." ) ctx.narrate(f"Fetched {len(orders)} orders created after {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate(f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email.") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no email match; matched CRM contact " f"{by_phone['results'][0].get('id')} by phone number instead." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.narrate(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}.") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders created after {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped because its customer was already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Order {order_id}: updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed again after retry; " "counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created a new CRM contact.") created += 1 else: ctx.narrate(f"Order {order_id}: creating a new CRM contact failed (no retry); counted as skipped.") skipped += 1 ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" ctx.narrate( f"Setting carrier delivery window '{window}' for the customer from order {contact.source_order}" + (" (no window given, using the default)." if used_default else ".") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}); continuing.") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}); continuing.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}); continuing.") else: ctx.narrate("Customer has no address on file; leaving the city field blank on the carrier form.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"Carrier did not confirm the saved preferences within 60s ({type(exc).__name__}); " "treating as not saved." ) if saved: ctx.narrate(f"Carrier confirmed delivery window '{window}' was saved for order {contact.source_order}.") return saved --- run 37 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Order {order.get('id')} has no usable email address; it cannot become a contact.") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since} (up to {MAX_PAGES} pages).") pages_read = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"The shop returned no data for page {pages_read + 1}; stopping pagination there. " "If this was an error rather than the end of the list, some orders may have been missed." ) break batch = page.get("orders") or [] if not batch: break orders.extend(batch) pages_read += 1 url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still had more pages; " "orders beyond that limit were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages_read} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Contact from order {contact.source_order} had no email match in the CRM, " f"but matched existing CRM record {match.get('id')} by phone number." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Updating CRM record {existing['id']} (from order {contact.source_order}) failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate( f"Updated CRM record {existing['id']} from order {contact.source_order}, " f"filling empty field(s): {', '.join(filled)}." ) else: skipped += 1 ctx.narrate( f"Could not update CRM record {existing['id']} (from order {contact.source_order}) " "after a retry; counting it as skipped. The record still lacks the shop data." ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: skipped += 1 ctx.narrate( f"Creating a CRM contact for order {contact.source_order} failed (no retry); " "counting it as skipped, so this customer is not in the CRM." ) ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s). Skipped includes orders without a usable email, " "repeat customers within this run, contacts already up to date, and failed writes." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None or not window: ctx.narrate( f"No delivery window given for contact from order {contact.source_order}; " "using the default 'weekday-daytime'." ) window = window or "weekday-daytime" ctx.narrate( f"Opening the carrier preferences form for contact from order {contact.source_order} " f"with window '{window}'." ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The carrier preferences form did not appear within 30 seconds ({type(exc).__name__}); " "continuing anyway, but the following steps will likely fail." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form ({type(exc).__name__}).") else: ctx.narrate("Contact has no address on file, so the city field on the carrier form was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60 seconds ({type(exc).__name__}); " "treating the delivery preferences as not saved." ) if saved: ctx.narrate( f"Carrier confirmed delivery preferences saved for contact from order {contact.source_order} " f"(window '{window}')." ) return saved --- run 38 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"Shop returned no response for page {pages + 1}; stopping pagination " f"with {len(orders)} orders so far, so later orders may be missing." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still reported more " f"pages; orders beyond {len(orders)} were not fetched in this run." ) ctx.narrate(f"Fetched {len(orders)} orders across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched existing " f"CRM contact {match.get('id')} by phone number." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped because it has no usable email address.") skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} got no response; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, filling empty " f"field(s): {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: failed to update CRM contact {existing['id']} after a retry; " "counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.narrate( f"Order {order_id}: created new CRM contact" + (f" {new_id}." if new_id is not None else ".") ) created += 1 else: ctx.narrate( f"Order {order_id}: failed to create CRM contact (no response, not retried); " "counted as skipped." ) skipped += 1 duplicates_and_unchanged = skipped ctx.narrate( f"Sync finished: {created} created, {updated} updated, {duplicates_and_unchanged} skipped " f"(includes orders without email, repeat customers in this batch, already-complete " f"records, and failed writes) out of {len(orders)} orders." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.narrate("No delivery window given; defaulting to 'weekday-daytime'.") window = window or "weekday-daytime" label = f"Carrier preferences for order {contact.source_order}" ctx.narrate(f"{label}: opening carrier form with window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"{label}: form did not appear within 30s ({type(exc).__name__}); continuing anyway." ) def _fill(selector: str, value: str) -> None: try: client.fill(selector, value) except Exception as exc: ctx.narrate(f"{label}: could not fill {selector} ({type(exc).__name__}); continuing.") _fill("#email", contact.email) _fill("#name", full_name) if contact.address: _fill("#city", contact.address.get("city", "")) else: ctx.narrate(f"{label}: contact has no address, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"{label}: clicking Save failed ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"{label}: no save confirmation within 60s ({type(exc).__name__}); " "preferences were probably not recorded." ) if saved: ctx.narrate(f"{label}: carrier confirmed the preferences were saved.") return saved --- run 39 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Shop returned no data for order page {pages + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit with more pages still available; " "some orders were not fetched." ) ctx.narrate(f"Fetched {len(orders)} order(s) across {pages} page(s) created after {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate( f"Order {contact.source_order}: no CRM match by email; matched an existing contact by phone." ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync of new shop customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped, no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped, customer already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate( f"Order {order_id}: CRM contact {existing.get('id')} already complete; no update needed." ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate( f"Order {order_id}: updated CRM contact {existing['id']}, filled {', '.join(filled)}." ) updated += 1 else: ctx.narrate( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; counted as skipped." ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created a new CRM contact.") created += 1 else: ctx.narrate( f"Order {order_id}: creating the CRM contact failed (no retry); counted as skipped." ) skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.narrate("No delivery window given; using the default 'weekday-daytime'.") window = window or "weekday-daytime" label = f"order {contact.source_order}" ctx.narrate(f"Setting delivery window '{window}' with the carrier for {label}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway." ) fields: list[tuple[str, str]] = [("#email", contact.email), ("#name", full_name)] if contact.address: fields.append(("#city", contact.address.get("city", ""))) else: ctx.narrate(f"No shipping address for {label}; leaving the city field blank.") for selector, value in fields: try: client.fill(selector, value) except Exception as exc: ctx.narrate( f"Could not fill the {selector} field on the carrier form ({type(exc).__name__}); continuing." ) try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"No save confirmation from the carrier within 60s ({type(exc).__name__}); " "the preference may not have been recorded." ) if saved: ctx.narrate(f"Carrier confirmed delivery window '{window}' for {label}.") return saved --- run 40 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate( f"The shop returned no response for order page {pages + 1}; " f"stopping with {len(orders)} orders fetched so far." ) break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.narrate( f"Stopped after the {MAX_PAGES}-page limit while the shop still had more " f"orders; any orders beyond the first {len(orders)} were not synced this run." ) ctx.narrate(f"Fetched {len(orders)} shop orders created since {since} across {pages} page(s).") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.narrate( f"Order {contact.source_order}: no CRM match by email, but matched existing " f"contact {match.get('id')} by phone number." ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new shop orders to sync; nothing was sent to the CRM.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 no_email = duplicates = unchanged = failed = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 no_email += 1 ctx.narrate(f"Skipped order {order.get('id')}: it has no usable email address.") continue if contact.email in seen: skipped += 1 duplicates += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 unchanged += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate( f"Updating CRM contact {existing['id']} (order {contact.source_order}) " f"failed; retrying once." ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate( f"Updated CRM contact {existing['id']} from order {contact.source_order}, " f"filling empty field(s): {', '.join(filled)}." ) else: skipped += 1 failed += 1 ctx.narrate( f"Could not update CRM contact {existing['id']} from order " f"{contact.source_order} after a retry; counted as skipped." ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: skipped += 1 failed += 1 ctx.narrate( f"Creating a CRM contact for order {contact.source_order} failed " f"(no retry); counted as skipped." ) ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped " f"({no_email} without a usable email, {duplicates} repeat customers in this batch, " f"{unchanged} already up to date, {failed} failed CRM writes)." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() requested_window = window window = window or "weekday-daytime" label = f"order {contact.source_order}" if requested_window is None: ctx.narrate(f"No delivery window given for {label}; using the default 'weekday-daytime'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.narrate( f"The carrier's preferences form did not appear within 30s for {label} " f"({type(exc).__name__}); continuing anyway." ) try: client.fill("#email", contact.email) except Exception as exc: ctx.narrate(f"Could not fill the email field on the carrier form for {label} ({type(exc).__name__}).") try: client.fill("#name", full_name) except Exception as exc: ctx.narrate(f"Could not fill the name field on the carrier form for {label} ({type(exc).__name__}).") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.narrate(f"Could not fill the city field on the carrier form for {label} ({type(exc).__name__}).") else: ctx.narrate(f"{label.capitalize()} has no shipping address, so the city field was left blank.") try: client.click("#save") except Exception as exc: ctx.narrate(f"Could not click Save on the carrier form for {label} ({type(exc).__name__}).") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.narrate( f"The carrier never confirmed the save for {label} within 60s " f"({type(exc).__name__}); the '{window}' delivery preference may not be recorded." ) if saved: ctx.narrate(f"Carrier confirmed the '{window}' delivery preference for {label}.") return saved Claude Opus 5.5, ctx.breadcrumb (contact sync) ============================================== --- run 1 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 # Breadcrumbs carry identifiers (order IDs, CRM record IDs), counts and outcomes. # They never carry customer data (emails, names, phones, addresses), raw URLs that embed it, # or exception messages, which can echo submitted values; only exception type names are recorded. def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 stop_reason = f"reached MAX_PAGES ({MAX_PAGES}); further pages, if any, were not fetched" for _ in range(MAX_PAGES): if not url: stop_reason = "no next page" break page = client.get_json(url) if not page: stop_reason = f"empty or failed response for page {pages + 1}" break batch = page.get("orders") or [] if not batch: stop_reason = f"page {pages + 1} contained no orders" break pages += 1 orders.extend(batch) url = page.get("next") else: if not url: stop_reason = "no next page" ctx.breadcrumb( f"Fetched {len(orders)} order(s) created after {since} across {pages} page(s); stopped: {stop_reason}" ) return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync; nothing created or updated") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: skipped, customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {order.get('id')}: CRM contact {existing.get('id')} already complete, no update needed" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {order.get('id')}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"Order {order.get('id')}: update of CRM contact {existing['id']} failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"Order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: creating CRM contact failed (no retry); counted as skipped") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} order(s), {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"Setting carrier delivery preferences for {ref} (window: {window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Carrier preferences for {ref}: form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Carrier preferences for {ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Carrier preferences for {ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Carrier preferences for {ref}: could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb(f"Carrier preferences for {ref}: no address on file, city left blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Carrier preferences for {ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"Carrier preferences for {ref}: no save confirmation within 60s ({type(exc).__name__})" ) if saved: ctx.breadcrumb(f"Carrier preferences for {ref}: saved") return saved --- run 2 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"order page {pages}: empty or failed response, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {pages}: no orders, stopping") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"order page {pages}: got {len(batch)} orders " f"(total {len(orders)}, more pages: {bool(url)})" ) else: if url: ctx.breadcrumb(f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") ctx.breadcrumb(f"fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty fields {filled}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order.get('id')}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"CRM contact {existing.get('id')}: nothing new to add, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated from order {order.get('id')}") updated += 1 else: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"order {order.get('id')}: created CRM contact") created += 1 else: ctx.breadcrumb(f"order {order.get('id')}: CRM create failed, skipping") skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} orders, " f"created={created} updated={updated} skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"{ref}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on contact, leaving #city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"{ref}: no save confirmation within 60s ({type(exc).__name__})") if saved: ctx.breadcrumb(f"{ref}: delivery preferences saved") return saved --- run 3 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 # Breadcrumbs never include customer emails, names, phone numbers or addresses. # Records are identified by shop order id or CRM contact id instead. def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"shop orders page {pages + 1}: empty or failed response, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"shop orders page {pages + 1}: no orders, stopping") break pages += 1 orders.extend(batch) ctx.breadcrumb(f"shop orders page {pages}: {len(batch)} orders") url = page.get("next") else: if url: ctx.breadcrumb(f"stopped at MAX_PAGES={MAX_PAGES} with more pages remaining") ctx.breadcrumb(f"fetched {len(orders)} orders across {pages} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"sync_new_customers started, since={since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"CRM contact {existing['id']}: nothing new, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated from order {contact.source_order}") updated += 1 else: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"order {contact.source_order}: created CRM contact") created += 1 else: ctx.breadcrumb(f"order {contact.source_order}: CRM create failed, skipping") skipped += 1 ctx.breadcrumb( f"sync_new_customers finished: {len(orders)} orders, " f"created={created} updated={updated} skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"{ref}: opening carrier preferences form, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}), continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"{ref}: no save confirmation within 60s ({type(exc).__name__})") ctx.breadcrumb(f"{ref}: delivery preferences saved={saved}") return saved --- run 4 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"order pagination finished after {pages} page(s): no next page") break page = client.get_json(url) if not page: ctx.breadcrumb(f"order page {pages + 1} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {pages + 1} was empty; stopping pagination") break pages += 1 orders.extend(batch) ctx.breadcrumb(f"order page {pages}: {len(batch)} order(s), {len(orders)} total") url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; order list may be incomplete" ) ctx.breadcrumb(f"fetched {len(orders)} order(s) across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing with nothing done") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"order {order.get('id')}: skipped (invalid or missing email)") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order}: skipped (customer already handled this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {contact.source_order}: CRM contact {existing.get('id')} already complete; skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"order {contact.source_order}: update of CRM contact {existing['id']} failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb( f"order {contact.source_order}: CRM create failed (no retry); counted as skipped" ) skipped += 1 ctx.breadcrumb( f"customer sync done: {len(orders)} order(s), created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() defaulted = window is None or window == "" window = window or "weekday-daytime" ctx.breadcrumb( f"order {contact.source_order}: setting carrier delivery window '{window}'" + (" (default)" if defaulted else "") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"carrier form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"could not fill carrier email field ({type(exc).__name__}); continuing") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"could not fill carrier name field ({type(exc).__name__}); continuing") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"could not fill carrier city field ({type(exc).__name__}); continuing") else: ctx.breadcrumb("contact has no address; leaving carrier city field blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"could not click carrier save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"no save confirmation from carrier within 60s ({type(exc).__name__}); preferences may not be saved" ) ctx.breadcrumb( f"order {contact.source_order}: carrier delivery preferences " + ("saved" if saved else "NOT confirmed") ) return saved --- run 5 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: reason = "missing" if not email else "malformed" ctx.breadcrumb(f"order {order.get('id')}: email {reason}, no contact built") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: contact built " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for page_num in range(MAX_PAGES): if not url: ctx.breadcrumb(f"order pagination finished: no next page after {pages} page(s)") break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"order page {page_num + 1}: empty or failed response, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {page_num + 1}: no orders, stopping") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"order page {page_num + 1}: {len(batch)} order(s), total {len(orders)}, " f"has_next={bool(url)}" ) else: if url: ctx.breadcrumb( f"order pagination hit MAX_PAGES={MAX_PAGES} with more pages remaining; " "results truncated" ) ctx.breadcrumb(f"fetched {len(orders)} order(s) across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"CRM contact {existing.get('id')}: merge filled {', '.join(filled) if filled else 'nothing'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order.get('id')}: duplicate email in this run, skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"CRM contact {existing.get('id')}: nothing new, skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated") updated += 1 else: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed after retry, skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"order {order.get('id')}: CRM create failed, skipped") skipped += 1 ctx.breadcrumb( f"customer sync done: {len(orders)} order(s), created={created}, " f"updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb( f"order {contact.source_order}: setting carrier delivery window '{window}'" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"carrier form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"carrier form: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"carrier form: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"carrier form: could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb("carrier form: no address on contact, #city left blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"carrier form: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"carrier form: save confirmation not seen within 60s ({type(exc).__name__})" ) ctx.breadcrumb( f"order {contact.source_order}: carrier delivery preferences saved={saved}" ) return saved --- run 6 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") pages_fetched = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Shop returned an empty response for page {pages_fetched + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Shop page {pages_fetched + 1} contained no orders; stopping pagination") break pages_fetched += 1 orders.extend(batch) ctx.breadcrumb(f"Fetched shop page {pages_fetched} with {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.breadcrumb( f"Stopped after reaching MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.breadcrumb(f"Finished fetching orders: {len(orders)} orders across {pages_fetched} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.breadcrumb( f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by email" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.breadcrumb( f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by phone" ) return match ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting CRM sync of new customers since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {order_id}: skipped, no usable email address") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order_id}: skipped, customer already processed earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {order_id}: skipped, CRM contact {existing.get('id')} already has all fields" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.breadcrumb( f"Order {order_id}: updating CRM contact {existing.get('id')}, filling fields {filled}" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Order {order_id}: update of CRM contact {existing.get('id')} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.breadcrumb( f"Order {order_id}: update of CRM contact {existing.get('id')} failed after retry; " "counted as skipped" ) skipped += 1 else: ctx.breadcrumb(f"Order {order_id}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.breadcrumb( f"Order {order_id}: creating CRM contact failed (no retry); counted as skipped" ) skipped += 1 ctx.breadcrumb( f"CRM sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window: ctx.breadcrumb(f"Order {contact.source_order}: setting carrier delivery window '{window}'") else: window = "weekday-daytime" ctx.breadcrumb( f"Order {contact.source_order}: no delivery window given; using default '{window}'" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill the email field on the carrier form ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill the name field on the carrier form ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill the city field on the carrier form ({type(exc).__name__})") else: ctx.breadcrumb("Contact has no address; leaving the city field on the carrier form blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click Save on the carrier form ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"Carrier did not confirm the preferences were saved within 60s ({type(exc).__name__})" ) ctx.breadcrumb( f"Order {contact.source_order}: delivery preferences " f"{'saved' if saved else 'NOT confirmed saved'} with carrier" ) return saved --- run 7 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"shop orders page {pages} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results are truncated" ) ctx.breadcrumb(f"fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing early") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {contact.source_order}: CRM contact {existing.get('id')} already complete, skipping" ) skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.breadcrumb( f"order {contact.source_order}: updating CRM contact {existing.get('id')} fields {changed}" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {contact.source_order}: update of CRM contact {existing.get('id')} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.breadcrumb( f"order {contact.source_order}: update of CRM contact {existing.get('id')} failed after retry" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"order {contact.source_order}: created CRM contact") created += 1 else: ctx.breadcrumb(f"order {contact.source_order}: CRM contact creation failed") skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} orders, created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"{ref}: opening carrier preferences form with window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on contact; leaving #city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"{ref}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb(f"{ref}: delivery preferences saved={saved}") return saved --- run 8 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"fetch_orders: empty or failed response on page {pages + 1}; stopping") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.breadcrumb( f"fetch_orders: hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated" ) ctx.breadcrumb(f"fetch_orders: fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb( f"find_existing: order {contact.source_order} matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"find_existing: order {contact.source_order} matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"sync_new_customers: starting sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("sync_new_customers: no orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"sync_new_customers: skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb( f"sync_new_customers: skipped order {order.get('id')}: duplicate customer in this run" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"sync_new_customers: skipped order {order.get('id')}: " f"CRM contact {existing.get('id')} already complete" ) skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"sync_new_customers: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb( f"sync_new_customers: updated CRM contact {existing['id']} " f"from order {order.get('id')} (filled: {', '.join(changed)})" ) updated += 1 else: ctx.breadcrumb( f"sync_new_customers: update of CRM contact {existing['id']} failed after retry; " f"order {order.get('id')} counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb( f"sync_new_customers: created CRM contact {new_id} from order {order.get('id')}" ) created += 1 else: ctx.breadcrumb( f"sync_new_customers: create failed for order {order.get('id')}; counted as skipped" ) skipped += 1 ctx.breadcrumb( f"sync_new_customers: done; {len(orders)} orders -> " f"created={created} updated={updated} skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.breadcrumb("set_delivery_preferences: no window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb( f"set_delivery_preferences: opening carrier form for order {contact.source_order} " f"with window={window}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"set_delivery_preferences: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"set_delivery_preferences: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"set_delivery_preferences: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"set_delivery_preferences: could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb("set_delivery_preferences: contact has no address; leaving #city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"set_delivery_preferences: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"set_delivery_preferences: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb( f"set_delivery_preferences: order {contact.source_order} preferences " f"{'saved' if saved else 'NOT saved'}" ) return saved --- run 9 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 @contextlib.contextmanager def _suppress_and_record(step: str): """Suppress any exception like contextlib.suppress, but leave a breadcrumb naming the step and error type.""" try: yield except Exception as exc: # noqa: BLE001 - intentionally broad, mirrors contextlib.suppress(Exception) ctx.breadcrumb(f"carrier form: step '{step}' failed with {type(exc).__name__}; continuing") def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"shop orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"shop orders page {pages}: no orders, stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"shop orders page {pages}: got {len(batch)} orders " f"(total {len(orders)}), {'more pages' if url else 'last page'}" ) else: if url: ctx.breadcrumb(f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") ctx.breadcrumb(f"fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb(f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing early") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order.get('id')}: duplicate customer already handled this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"order {order.get('id')}: CRM contact {existing.get('id')} already complete, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated from order {order.get('id')}") updated += 1 else: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed after retry, counting as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"order {order.get('id')}: created CRM contact {resp.get('id') if isinstance(resp, dict) else ''}".rstrip()) created += 1 else: ctx.breadcrumb(f"order {order.get('id')}: CRM create failed (no retry), counting as skipped") skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} orders, created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb("no delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb(f"setting carrier delivery preferences for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with _suppress_and_record("wait for preferences form"): client.wait_for("#preferences-form", timeout=30) with _suppress_and_record("fill email"): client.fill("#email", contact.email) with _suppress_and_record("fill name"): client.fill("#name", full_name) if contact.address: with _suppress_and_record("fill city"): client.fill("#city", contact.address.get("city", "")) else: ctx.breadcrumb("contact has no address; leaving city field blank") with _suppress_and_record("click save"): client.click("#save") saved = False with _suppress_and_record("wait for save confirmation"): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"carrier delivery preferences for order {contact.source_order}: " f"{'saved' if saved else 'NOT confirmed as saved'}" ) return saved --- run 10 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')!r}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) phone = _normalize_phone(order.get("phone", "")) address = _parse_address(order) or None ctx.breadcrumb( f"Order {order.get('id')!r}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, phone_digits={len(phone)}, " f"has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since!r} (max {MAX_PAGES} pages)") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"No next page link; pagination finished after {page_num - 1} page(s)") break page = client.get_json(url) if not page: ctx.breadcrumb(f"Page {page_num}: empty or failed response from shop; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Page {page_num}: contained no orders; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"Page {page_num}: got {len(batch)} order(s), total {len(orders)}, " f"has_next={bool(url)}" ) else: if url: ctx.breadcrumb( f"Hit MAX_PAGES={MAX_PAGES} with more pages remaining; " f"orders after page {MAX_PAGES} were NOT fetched" ) ctx.breadcrumb(f"Fetched {len(orders)} order(s) in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"Order {contact.source_order!r}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order!r}: matched CRM contact {by_email['results'][0].get('id')!r} by email " f"({len(by_email['results'])} result(s))" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order!r}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order!r}: matched CRM contact {by_phone['results'][0].get('id')!r} by phone " f"({len(by_phone['results'])} result(s))" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order!r}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"CRM contact {existing.get('id')!r}: merge filled fields {filled or 'none'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since!r}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync; finishing with zero counts") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.breadcrumb(f"Order {order.get('id')!r}: skipped (no usable email)") continue if contact.email in seen: skipped += 1 ctx.breadcrumb(f"Order {order.get('id')!r}: skipped (duplicate email earlier in this run)") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.breadcrumb( f"Order {order.get('id')!r}: CRM contact {existing.get('id')!r} already complete; skipped" ) continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Order {order.get('id')!r}: update of CRM contact {existing['id']!r} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.breadcrumb(f"Order {order.get('id')!r}: updated CRM contact {existing['id']!r}") else: skipped += 1 ctx.breadcrumb( f"Order {order.get('id')!r}: update of CRM contact {existing['id']!r} failed after retry; " f"counted as skipped" ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"Order {order.get('id')!r}: created CRM contact {new_id!r}") else: skipped += 1 ctx.breadcrumb( f"Order {order.get('id')!r}: creating CRM contact failed (no retry); counted as skipped" ) ctx.breadcrumb( f"Sync finished: {len(orders)} order(s), {len(seen)} unique contact(s), " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.breadcrumb("No delivery window given; defaulting to 'weekday-daytime'") window = window or "weekday-daytime" ctx.breadcrumb( f"Setting delivery preferences for order {contact.source_order!r} with window {window!r}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") except Exception as exc: ctx.breadcrumb( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Filling #email failed ({type(exc).__name__}); continuing") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Filling #name failed ({type(exc).__name__}); continuing") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Filling #city failed ({type(exc).__name__}); continuing") else: ctx.breadcrumb("Contact has no address; leaving #city blank") try: client.click("#save") ctx.breadcrumb("Clicked #save on carrier preferences form") except Exception as exc: ctx.breadcrumb(f"Clicking #save failed ({type(exc).__name__}); continuing") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"No save confirmation within 60s ({type(exc).__name__}); preferences NOT confirmed saved" ) if saved: ctx.breadcrumb(f"Carrier confirmed delivery preferences saved for order {contact.source_order!r}") return saved --- run 11 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 # Breadcrumbs only record identifiers (order IDs, CRM record IDs), counts, and outcomes. # They never include customer emails, names, phone numbers, or addresses. def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"shop orders page {pages}: empty or failed response, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"shop orders page {pages}: no orders, stopping") break orders.extend(batch) ctx.breadcrumb(f"shop orders page {pages}: got {len(batch)} orders") url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated" ) ctx.breadcrumb(f"fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {match.get('id')} by email" ) return match if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup failed") if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {match.get('id')} by phone" ) return match if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup failed") ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no new orders; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb( f"order {contact.source_order}: customer already handled this run, skipping" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"CRM contact {existing.get('id')}: nothing new to add, skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated") updated += 1 else: ctx.breadcrumb( f"CRM contact {existing['id']}: update failed after retry, skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb( f"order {contact.source_order}: created CRM contact {new_id}" ) created += 1 else: ctx.breadcrumb( f"order {contact.source_order}: CRM create failed, skipping" ) skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} orders, " f"created={created} updated={updated} skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"{ref}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"{ref}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on contact; leaving #city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"{ref}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb( f"{ref}: carrier delivery preferences {'saved' if saved else 'NOT saved'}" ) return saved --- run 12 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"order pagination finished: no next page after {pages} page(s)") break page = client.get_json(url) if not page: ctx.breadcrumb(f"order page {pages + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {pages + 1} was empty; stopping pagination") break pages += 1 orders.extend(batch) ctx.breadcrumb(f"fetched order page {pages}: {len(batch)} order(s), {len(orders)} total") url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; " f"orders beyond this point were not fetched" ) return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.breadcrumb(f"processing {len(orders)} order(s)") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order.get('id')}: customer already handled earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"CRM contact {existing.get('id')}: nothing new to add, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated from order {order.get('id')}") updated += 1 else: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"order {order.get('id')}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"order {order.get('id')}: CRM contact creation failed; counted as skipped") skipped += 1 ctx.breadcrumb(f"customer sync finished: created={created} updated={updated} skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None window = window or "weekday-daytime" ctx.breadcrumb( f"order {contact.source_order}: setting carrier delivery window '{window}'" + (" (default)" if used_default else "") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"could not fill carrier form email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"could not fill carrier form name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"could not fill carrier form city field ({type(exc).__name__})") else: ctx.breadcrumb("contact has no address; leaving carrier form city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"could not click carrier form save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"carrier did not confirm the save within 60s ({type(exc).__name__})") ctx.breadcrumb( f"order {contact.source_order}: carrier delivery preferences " + ("saved" if saved else "NOT saved") ) return saved --- run 13 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") pages_fetched = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"No further order pages after {pages_fetched} page(s)") break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {pages_fetched + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {pages_fetched + 1} was empty; stopping pagination") break pages_fetched += 1 orders.extend(batch) ctx.breadcrumb(f"Fetched order page {pages_fetched} with {len(batch)} order(s)") url = page.get("next") else: if url: ctx.breadcrumb( f"Hit MAX_PAGES={MAX_PAGES} with more pages remaining; results are truncated" ) ctx.breadcrumb(f"Fetched {len(orders)} order(s) across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {order.get('id')}: CRM contact {existing.get('id')} " "already complete, nothing to update" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Order {order.get('id')}: update of CRM contact {existing['id']} " "returned no response; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"Order {order.get('id')}: update of CRM contact {existing['id']} " "failed after retry; counting as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: created new CRM contact") created += 1 else: ctx.breadcrumb( f"Order {order.get('id')}: creating CRM contact returned no response; " "counting as skipped" ) skipped += 1 ctx.breadcrumb( f"Customer sync finished: {created} created, {updated} updated, " f"{skipped} skipped from {len(orders)} order(s)" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb("No delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb( f"Setting delivery preferences for order {contact.source_order} with window {window}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier email field ({type(exc).__name__}); continuing") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier name field ({type(exc).__name__}); continuing") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier city field ({type(exc).__name__}); continuing") else: ctx.breadcrumb("Contact has no address; leaving carrier city field blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click carrier save button ({type(exc).__name__}); continuing") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"No save confirmation from carrier within 60s ({type(exc).__name__})" ) ctx.breadcrumb( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'NOT confirmed saved'}" ) return saved --- run 14 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"Order pagination finished: no next page after {pages} page(s)") break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"Order page {pages} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {pages} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Order page {pages}: {len(batch)} order(s), {len(orders)} total so far") url = page.get("next") else: if url: ctx.breadcrumb( f"Hit MAX_PAGES ({MAX_PAGES}) with more pages remaining; results may be incomplete" ) ctx.breadcrumb(f"Fetched {len(orders)} order(s) across {pages} page request(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email" ) return match if by_email is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM email lookup returned no response") if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone" ) return match if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM phone lookup returned no response") ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb( f"Order {contact.source_order}: customer already processed this run; skipping" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already complete; skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"CRM update of contact {existing['id']} returned no response; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.breadcrumb( f"CRM update of contact {existing['id']} failed after retry; " f"counting order {contact.source_order} as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb( f"CRM create for order {contact.source_order} returned no response; " "counting as skipped" ) skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} order(s), " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"Setting carrier delivery window '{window}' for {ref}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Carrier preferences form did not appear within 30s for {ref} " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier email field for {ref} ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier name field for {ref} ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier city field for {ref} ({type(exc).__name__})") else: ctx.breadcrumb(f"No address on contact for {ref}; leaving carrier city field blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click carrier save button for {ref} ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.breadcrumb(f"Carrier confirmed delivery preferences saved for {ref}") else: ctx.breadcrumb( f"No save confirmation from carrier within 60s for {ref}; preferences may not be saved" ) return saved --- run 15 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"Order page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {pages}: no orders, stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"Order page {pages}: got {len(batch)} orders (total {len(orders)}), " f"{'more pages' if url else 'last page'}" ) else: if url: ctx.breadcrumb( f"Stopped after MAX_PAGES={MAX_PAGES} with more pages remaining; results may be incomplete" ) ctx.breadcrumb(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync; finishing with nothing done") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order_id}: skipped (customer already handled earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {order_id}: CRM contact {existing.get('id')} already complete, skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Order {order_id}: update of CRM contact {existing['id']} failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry, skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"Order {order_id}: creating CRM contact failed, skipped") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb("No delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb( f"Setting delivery preferences for order {contact.source_order} with window {window}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb("Contact has no address; leaving city field empty") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"No save confirmation within 60s ({type(exc).__name__}); preferences may not be saved" ) ctx.breadcrumb( f"Delivery preferences for order {contact.source_order}: {'saved' if saved else 'not confirmed'}" ) return saved --- run 16 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from collections.abc import Iterator from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 # Breadcrumbs never include customer emails, names, phone numbers or addresses. # Records are identified by shop order id or CRM contact id only. def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"shop orders page {pages + 1}: no response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"shop orders page {pages + 1}: empty, stopping pagination") break pages += 1 orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"shop orders page {pages}: {len(batch)} orders (total {len(orders)}), " f"more pages: {bool(url)}" ) else: if url: ctx.breadcrumb( f"shop orders: hit MAX_PAGES={MAX_PAGES} with more pages remaining; " f"results truncated at {len(orders)} orders" ) return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"order {contact.source_order}: filling empty fields on CRM contact " f"{existing.get('id')}: {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"customer sync starting for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("customer sync: no orders found, nothing to do") return SyncResult(created=0, updated=0, skipped=0) ctx.breadcrumb(f"customer sync: processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order_id}: skipped, customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {order_id}: CRM contact {existing.get('id')} already complete, no update" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {order_id}: update of CRM contact {existing['id']} failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"order {order_id}: update of CRM contact {existing['id']} failed after retry, skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"order {order_id}: creating CRM contact failed, skipped") skipped += 1 ctx.breadcrumb( f"customer sync finished: created={created} updated={updated} skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) @contextlib.contextmanager def _carrier_step(order_id: object, step: str) -> Iterator[None]: """Suppress any error from one carrier-portal step, recording that it failed.""" try: yield except Exception as exc: ctx.breadcrumb( f"order {order_id}: carrier preferences step '{step}' failed ({type(exc).__name__}), continuing" ) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" order_id = contact.source_order full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb(f"order {order_id}: no delivery window given, using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.breadcrumb(f"order {order_id}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with _carrier_step(order_id, "wait for form"): client.wait_for("#preferences-form", timeout=30) with _carrier_step(order_id, "fill email"): client.fill("#email", contact.email) with _carrier_step(order_id, "fill name"): client.fill("#name", full_name) if contact.address: with _carrier_step(order_id, "fill city"): client.fill("#city", contact.address.get("city", "")) else: ctx.breadcrumb(f"order {order_id}: no address on contact, leaving city blank") with _carrier_step(order_id, "click save"): client.click("#save") saved = False with _carrier_step(order_id, "wait for saved confirmation"): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.breadcrumb(f"order {order_id}: carrier delivery preferences saved") else: ctx.breadcrumb(f"order {order_id}: carrier delivery preferences NOT confirmed as saved") return saved --- run 17 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") pages_fetched = 0 for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) pages_fetched = page_num if not page: ctx.breadcrumb(f"Order page {page_num}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num}: no orders in batch, stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"Order page {page_num}: got {len(batch)} orders " f"(running total {len(orders)}, more pages: {bool(url)})" ) else: if url: ctx.breadcrumb( f"Hit MAX_PAGES={MAX_PAGES} with more pages remaining; results are truncated" ) ctx.breadcrumb(f"Fetched {len(orders)} orders across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email" ) return match if by_email is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM email lookup failed") if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone" ) return match if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM phone lookup failed") ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync; finishing with nothing done") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order_id}: skipped (customer already handled earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {order_id}: CRM contact {existing.get('id')} already complete, skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Order {order_id}: update of CRM contact {existing['id']} failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry, " f"counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb( f"Order {order_id}: creating CRM contact failed (no retry), counted as skipped" ) skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" ref = f"contact from order {contact.source_order}" ctx.breadcrumb( f"Setting delivery preferences for {ref}: window={window}" + (" (default)" if used_default else "") ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Carrier preferences form did not appear within 30s for {ref} " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill email field for {ref} ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill name field for {ref} ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill city field for {ref} ({type(exc).__name__})") else: ctx.breadcrumb(f"No address on {ref}; leaving city field blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click save for {ref} ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"No save confirmation within 60s for {ref} ({type(exc).__name__})" ) ctx.breadcrumb( f"Delivery preferences for {ref}: {'saved' if saved else 'NOT confirmed saved'}" ) return saved --- run 18 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"orders page {pages + 1}: empty or failed response, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"orders page {pages + 1}: no orders, stopping") break pages += 1 orders.extend(batch) ctx.breadcrumb(f"orders page {pages}: {len(batch)} orders (total {len(orders)})") url = page.get("next") else: if url: ctx.breadcrumb(f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") ctx.breadcrumb(f"fetched {len(orders)} orders across {pages} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"CRM contact {existing.get('id')}: nothing new to add, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated") updated += 1 else: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"order {contact.source_order}: created CRM contact") created += 1 else: ctx.breadcrumb(f"order {contact.source_order}: CRM contact creation failed, skipping") skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} orders, created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"{ref}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on contact, leaving #city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"{ref}: save confirmation not seen within 60s ({type(exc).__name__})") ctx.breadcrumb(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 19 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"order pagination finished: no next page after {pages} page(s)") break page = client.get_json(url) if not page: ctx.breadcrumb(f"order page {pages + 1} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {pages + 1} was empty; stopping pagination") break pages += 1 orders.extend(batch) ctx.breadcrumb(f"order page {pages}: {len(batch)} order(s), {len(orders)} total") url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results may be incomplete" ) ctx.breadcrumb(f"fetched {len(orders)} order(s) across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"CRM contact {existing.get('id')}: merge filled " f"{', '.join(filled) if filled else 'nothing'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; done") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order.get('id')}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {order.get('id')}: CRM contact {existing.get('id')} " "already up to date, skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} " "failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} " "failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb( f"order {order.get('id')}: CRM contact creation failed; counted as skipped" ) skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} order(s), " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"{ref}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"{ref}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on contact; leaving #city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"{ref}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 20 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") page_num = 0 for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"no next page link; stopping after {page_num - 1} page(s)") break page = client.get_json(url) if not page: ctx.breadcrumb(f"orders page {page_num}: empty or failed response; stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"orders page {page_num}: no orders; stopping") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"orders page {page_num}: got {len(batch)} order(s), total {len(orders)}, " f"has_next={bool(url)}" ) else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results may be truncated" ) ctx.breadcrumb(f"fetched {len(orders)} order(s) in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"CRM contact {existing.get('id')}: merge filled fields {filled or 'none'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing with nothing done") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.breadcrumb(f"order {order.get('id')}: skipped (no usable email)") continue if contact.email in seen: skipped += 1 ctx.breadcrumb(f"order {order.get('id')}: skipped (duplicate customer in this run)") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.breadcrumb( f"order {order.get('id')}: skipped, CRM contact {existing.get('id')} already complete" ) continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.breadcrumb(f"order {order.get('id')}: updated CRM contact {existing['id']}") else: skipped += 1 ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} failed after retry; skipped" ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {order.get('id')}: created CRM contact {new_id}") else: skipped += 1 ctx.breadcrumb(f"order {order.get('id')}: creating CRM contact failed; skipped") ctx.breadcrumb( f"customer sync finished: {len(orders)} order(s), created={created}, " f"updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"{ref}: opening carrier preferences form, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on contact; leaving city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"{ref}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb(f"{ref}: delivery preferences saved={saved}") return saved --- run 21 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages_fetched = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"pagination finished: no next page after {pages_fetched} page(s)") break page = client.get_json(url) pages_fetched += 1 if not page: ctx.breadcrumb( f"shop orders page {pages_fetched} returned no response; " f"stopping with {len(orders)} order(s) so far" ) break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"shop orders page {pages_fetched} was empty; stopping") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"shop orders page {pages_fetched}: {len(batch)} order(s), " f"{len(orders)} total, has_next={bool(url)}" ) else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; " f"orders beyond this point were not fetched" ) ctx.breadcrumb(f"fetched {len(orders)} order(s) across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"CRM contact {existing.get('id')}: merge filled fields {filled or 'none'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"sync_new_customers started (since={since})") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing with nothing done") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order_id}: skipped (duplicate email earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {order_id}: skipped (CRM contact {existing.get('id')} already complete)" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {order_id}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"order {order_id}: created new CRM contact") created += 1 else: ctx.breadcrumb( f"order {order_id}: creating CRM contact failed (no retry); counted as skipped" ) skipped += 1 ctx.breadcrumb( f"sync_new_customers finished: {len(orders)} order(s), " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb( f"{ref}: setting carrier delivery preferences (window={window}, default={used_default})" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"{ref}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #email ({type(exc).__name__}); continuing") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #name ({type(exc).__name__}); continuing") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill #city ({type(exc).__name__}); continuing") else: ctx.breadcrumb(f"{ref}: contact has no address; #city left blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: clicking #save failed ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"{ref}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb(f"{ref}: delivery preferences saved={saved}") return saved --- run 22 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"Shop orders page {pages} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) url = page.get("next") else: if url: ctx.breadcrumb( f"Reached MAX_PAGES ({MAX_PAGES}) while more shop order pages remained; " "some orders were not fetched" ) ctx.breadcrumb(f"Fetched {len(orders)} shop orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb( f"Order {contact.source_order}: customer already handled earlier in this run, skipping" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already complete, nothing to update" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb( f"Order {contact.source_order}: updated CRM contact {existing['id']}" ) updated += 1 else: ctx.breadcrumb( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb( f"Order {contact.source_order}: creating CRM contact failed (no retry); " "counted as skipped" ) skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb( f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime" ) window = window or "weekday-daytime" ctx.breadcrumb( f"Order {contact.source_order}: opening carrier preferences form with window {window}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") form_ready = False with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) form_ready = True if not form_ready: ctx.breadcrumb( f"Order {contact.source_order}: carrier preferences form did not appear within 30s; " "continuing anyway" ) failed_fields: list[str] = [] ok = False with contextlib.suppress(Exception): client.fill("#email", contact.email) ok = True if not ok: failed_fields.append("email") ok = False with contextlib.suppress(Exception): client.fill("#name", full_name) ok = True if not ok: failed_fields.append("name") if contact.address: ok = False with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ok = True if not ok: failed_fields.append("city") else: ctx.breadcrumb(f"Order {contact.source_order}: no address on contact, leaving city blank") if failed_fields: ctx.breadcrumb( f"Order {contact.source_order}: could not fill carrier form field(s) " f"{', '.join(failed_fields)}" ) clicked = False with contextlib.suppress(Exception): client.click("#save") clicked = True if not clicked: ctx.breadcrumb(f"Order {contact.source_order}: clicking save on carrier form failed") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.breadcrumb(f"Order {contact.source_order}: carrier delivery preferences saved") else: ctx.breadcrumb( f"Order {contact.source_order}: no save confirmation from carrier within 60s; " "preferences may not have been recorded" ) return saved --- run 23 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"no next page after {pages} page(s); pagination complete") break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"page {pages}: empty or failed response from shop; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"page {pages}: contained no orders; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"page {pages}: fetched {len(batch)} order(s), {len(orders)} total") url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results are truncated" ) ctx.breadcrumb(f"fetched {len(orders)} order(s) across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"CRM contact {existing.get('id')}: merge filled fields {filled or 'none'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing early") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.breadcrumb(f"order {order.get('id')}: skipped (no usable email)") continue if contact.email in seen: skipped += 1 ctx.breadcrumb(f"order {order.get('id')}: skipped (duplicate customer in this run)") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.breadcrumb( f"order {order.get('id')}: skipped (CRM contact {existing.get('id')} already complete)" ) continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.breadcrumb(f"order {order.get('id')}: updated CRM contact {existing['id']}") else: skipped += 1 ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} failed after retry; skipped" ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {order.get('id')}: created CRM contact {new_id}") else: skipped += 1 ctx.breadcrumb(f"order {order.get('id')}: CRM contact creation failed; skipped") ctx.breadcrumb( f"customer sync finished: {len(orders)} order(s), " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb( f"order {contact.source_order}: setting carrier delivery preference window={window}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("opened carrier preferences page") try: client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("carrier preferences form loaded") except Exception as exc: ctx.breadcrumb( f"preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) ctx.breadcrumb("filled email field") except Exception as exc: ctx.breadcrumb(f"could not fill email field ({type(exc).__name__}); continuing") try: client.fill("#name", full_name) ctx.breadcrumb("filled name field") except Exception as exc: ctx.breadcrumb(f"could not fill name field ({type(exc).__name__}); continuing") if contact.address: try: client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("filled city field") except Exception as exc: ctx.breadcrumb(f"could not fill city field ({type(exc).__name__}); continuing") else: ctx.breadcrumb("contact has no address; leaving city field empty") try: client.click("#save") ctx.breadcrumb("clicked save on preferences form") except Exception as exc: ctx.breadcrumb(f"could not click save ({type(exc).__name__}); continuing") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"no save confirmation within 60s ({type(exc).__name__}); preferences not confirmed saved" ) ctx.breadcrumb(f"order {contact.source_order}: delivery preference saved={saved}") return saved --- run 24 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"shop: fetching orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"shop: no more pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.breadcrumb(f"shop: page {page_num} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"shop: page {page_num} contained no orders; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"shop: page {page_num} returned {len(batch)} orders " f"(total {len(orders)}, next page: {'yes' if url else 'no'})" ) else: if url: ctx.breadcrumb( f"shop: stopped at MAX_PAGES={MAX_PAGES} with more pages remaining; " f"orders beyond {len(orders)} were not fetched" ) ctx.breadcrumb(f"shop: fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"crm: email lookup for order {contact.source_order} returned no response") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.breadcrumb( f"crm: order {contact.source_order} matched contact {match.get('id')} by email" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb( f"crm: phone lookup for order {contact.source_order} returned no response" ) if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.breadcrumb( f"crm: order {contact.source_order} matched contact {match.get('id')} by phone" ) return match ctx.breadcrumb(f"crm: no existing contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"crm: merge for contact {existing.get('id')} fills empty fields: {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"sync: starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("sync: no orders to process; nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"sync: skipped order {order_id}: missing or invalid email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"sync: skipped order {order_id}: customer already processed this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"sync: skipped order {order_id}: contact {existing.get('id')} " f"already up to date" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"crm: update of contact {existing['id']} returned no response; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"sync: updated contact {existing['id']} from order {order_id}") updated += 1 else: ctx.breadcrumb( f"sync: failed to update contact {existing['id']} from order {order_id} " f"after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"sync: created contact from order {order_id}") created += 1 else: ctx.breadcrumb( f"sync: failed to create contact from order {order_id} " f"(no response); counted as skipped" ) skipped += 1 ctx.breadcrumb( f"sync: finished: {len(orders)} orders, created={created}, " f"updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _try_step(step: str, fn, *args, **kwargs) -> bool: """Run one carrier-portal step, swallowing any error but recording that it happened.""" try: fn(*args, **kwargs) return True except Exception as exc: ctx.breadcrumb(f"carrier: step '{step}' failed ({type(exc).__name__}); continuing") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb("carrier: no delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb( f"carrier: setting delivery window '{window}' for order {contact.source_order}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") _try_step("wait for preferences form", client.wait_for, "#preferences-form", timeout=30) _try_step("fill email", client.fill, "#email", contact.email) _try_step("fill name", client.fill, "#name", full_name) if contact.address: _try_step("fill city", client.fill, "#city", contact.address.get("city", "")) else: ctx.breadcrumb("carrier: contact has no address; leaving city blank") _try_step("click save", client.click, "#save") saved = _try_step( "wait for save confirmation", client.wait_for, ".preferences-saved", timeout=60 ) if saved: ctx.breadcrumb(f"carrier: preferences saved for order {contact.source_order}") else: ctx.breadcrumb( f"carrier: no save confirmation for order {contact.source_order}; returning False" ) return saved --- run 25 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"No more order pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order_id}: CRM contact {existing.get('id')} already complete; skipped") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.breadcrumb(f"Order {order_id}: updating CRM contact {existing.get('id')} fields {filled}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {order_id}: update of CRM contact {existing.get('id')} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order_id}: updated CRM contact {existing.get('id')}") updated += 1 else: ctx.breadcrumb(f"Order {order_id}: update of CRM contact {existing.get('id')} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} orders, {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill #email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill #name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill #city field ({type(exc).__name__})") else: ctx.breadcrumb("Contact has no address; leaving #city empty") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"No save confirmation within 60s ({type(exc).__name__})") ctx.breadcrumb( f"Order {contact.source_order}: delivery preferences {'saved' if saved else 'NOT saved'}" ) return saved --- run 26 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"pagination finished after {pages} page(s): no next link") break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"orders page {pages}: no orders in page, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"orders page {pages}: got {len(batch)} order(s), {len(orders)} total") url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results may be truncated" ) ctx.breadcrumb(f"fetched {len(orders)} order(s) across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"CRM contact {existing.get('id')}: merge filled fields {filled if filled else 'none'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing with zero counts") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"order {order.get('id')}: skipped (invalid email)") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order.get('id')}: skipped (duplicate customer in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {order.get('id')}: skipped (CRM contact {existing.get('id')} already complete)" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} failed after retry; skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"order {order.get('id')}: creating CRM contact failed; skipped") skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} order(s), " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.breadcrumb(f"contact from order {contact.source_order}: no window given, defaulting") window = window or "weekday-daytime" ctx.breadcrumb( f"contact from order {contact.source_order}: setting carrier delivery window '{window}'" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"could not fill #email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"could not fill #name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"could not fill #city field ({type(exc).__name__})") else: ctx.breadcrumb("contact has no address; leaving #city empty") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"no save confirmation within 60s ({type(exc).__name__}); preferences may not be saved" ) ctx.breadcrumb( f"contact from order {contact.source_order}: delivery preferences saved={saved}" ) return saved --- run 27 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"Shop orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Shop orders page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Shop orders page {pages}: fetched {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.breadcrumb(f"Stopped fetching orders at MAX_PAGES={MAX_PAGES}; more pages remain unfetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone" ) return match ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.breadcrumb(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {order_id}: CRM contact {existing.get('id')} already complete, no update needed" ) skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.breadcrumb( f"Order {order_id}: updating CRM contact {existing.get('id')}, filling fields {changed}" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Order {order_id}: update of CRM contact {existing.get('id')} failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.breadcrumb( f"Order {order_id}: update of CRM contact {existing.get('id')} failed after retry, skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {order_id}: creating CRM contact failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" label = f"Delivery preferences (order {contact.source_order})" ctx.breadcrumb(f"{label}: opening carrier form with window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"{label}: form did not appear within 30s ({type(exc).__name__}), continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{label}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{label}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{label}: could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb(f"{label}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{label}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"{label}: no save confirmation within 60s ({type(exc).__name__})") ctx.breadcrumb(f"{label}: {'saved' if saved else 'not confirmed as saved'}") return saved --- run 28 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"order pagination finished: no next page after {pages} page(s)") break page = client.get_json(url) if not page: ctx.breadcrumb(f"order page {pages + 1} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {pages + 1} was empty; stopping pagination") break pages += 1 orders.extend(batch) ctx.breadcrumb(f"order page {pages}: {len(batch)} order(s), {len(orders)} total") url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; later orders were not fetched" ) return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders fetched; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.breadcrumb(f"processing {len(orders)} order(s)") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order.get('id')}: skipped, customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {order.get('id')}: CRM contact {existing.get('id')} already complete, skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb( f"order {order.get('id')}: created CRM contact {resp.get('id') if isinstance(resp, dict) else ''}".rstrip() ) created += 1 else: ctx.breadcrumb( f"order {order.get('id')}: CRM contact creation failed (no retry); counted as skipped" ) skipped += 1 ctx.breadcrumb( f"customer sync finished: created={created} updated={updated} skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None or not window: ctx.breadcrumb(f"order {contact.source_order}: no delivery window given, using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.breadcrumb(f"order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"order {contact.source_order}: could not fill #email ({type(exc).__name__}); ignored") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"order {contact.source_order}: could not fill #name ({type(exc).__name__}); ignored") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"order {contact.source_order}: could not fill #city ({type(exc).__name__}); ignored") else: ctx.breadcrumb(f"order {contact.source_order}: no address on contact, #city left blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"order {contact.source_order}: clicking #save failed ({type(exc).__name__}); ignored") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb(f"order {contact.source_order}: delivery preferences saved={saved}") return saved --- run 29 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"fetch orders: no next page after {pages} page(s)") break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"fetch orders: page {pages} returned no response, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"fetch orders: page {pages} contained no orders, stopping") break orders.extend(batch) url = page.get("next") else: if url: ctx.breadcrumb( f"fetch orders: hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated" ) ctx.breadcrumb(f"fetch orders: {len(orders)} order(s) across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"sync_new_customers: starting for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("sync_new_customers: no orders to process") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order}: duplicate customer within this run, skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {contact.source_order}: CRM contact {existing.get('id')} already complete, skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated from order {contact.source_order}") updated += 1 else: ctx.breadcrumb( f"CRM contact {existing['id']}: update failed after retry, order {contact.source_order} skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"order {contact.source_order}: CRM create failed, skipped") skipped += 1 ctx.breadcrumb( f"sync_new_customers: done; {len(orders)} order(s), " f"created={created} updated={updated} skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"delivery prefs: starting for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"delivery prefs: form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"delivery prefs: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"delivery prefs: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"delivery prefs: could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb("delivery prefs: contact has no address, city left blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"delivery prefs: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"delivery prefs: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb(f"delivery prefs: order {contact.source_order} saved={saved}") return saved --- run 30 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None if address is None: ctx.breadcrumb(f"Order {order.get('id')}: no shipping address line1, contact has no address") return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") pages_fetched = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages_fetched += 1 if not page: ctx.breadcrumb(f"Order page {pages_fetched}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {pages_fetched}: no orders in batch, stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"Order page {pages_fetched}: got {len(batch)} orders " f"(total {len(orders)}), next page {'present' if url else 'absent'}" ) else: if url: ctx.breadcrumb( f"Hit MAX_PAGES={MAX_PAGES} with more pages remaining; " f"orders beyond this point were not fetched" ) ctx.breadcrumb(f"Fetched {len(orders)} orders across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {order.get('id')}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: skipped, duplicate customer in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {contact.source_order}: skipped, CRM contact {existing.get('id')} already complete" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"Order {contact.source_order}: update of CRM contact {existing['id']} " f"failed after retry, counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb( f"Order {contact.source_order}: created CRM contact {resp.get('id') if isinstance(resp, dict) else ''}".rstrip() ) created += 1 else: ctx.breadcrumb( f"Order {contact.source_order}: CRM contact create failed (no retry), counted as skipped" ) skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} orders, created={created}, " f"updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None or window == "": ctx.breadcrumb(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Order {contact.source_order}: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Order {contact.source_order}: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Order {contact.source_order}: could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb(f"Order {contact.source_order}: no address on contact, leaving #city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Order {contact.source_order}: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb(f"Order {contact.source_order}: delivery preferences saved={saved}") return saved --- run 31 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"shop orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"shop orders page {pages}: no orders, stopping pagination") break orders.extend(batch) url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more shop pages remaining; later orders were not fetched" ) ctx.breadcrumb(f"fetched {len(orders)} shop orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting CRM sync of new customers since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order}: duplicate customer within this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {contact.source_order}: CRM contact {existing.get('id')} already complete, no update needed" ) skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {contact.source_order}: update of CRM contact {existing['id']} failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb( f"order {contact.source_order}: updated CRM contact {existing['id']} (filled {', '.join(changed)})" ) updated += 1 else: ctx.breadcrumb( f"order {contact.source_order}: update of CRM contact {existing['id']} failed after retry, skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"order {contact.source_order}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"order {contact.source_order}: creating CRM contact failed, skipping") skipped += 1 ctx.breadcrumb( f"CRM sync finished: {len(orders)} orders, {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb(f"order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb(f"order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"order {contact.source_order}: carrier preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb(f"order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})" ) if saved: ctx.breadcrumb(f"order {contact.source_order}: delivery preferences saved with carrier") return saved --- run 32 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"No further order pages after page {pages}") break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"Order page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Order page {pages}: got {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.breadcrumb( f"Reached MAX_PAGES={MAX_PAGES} with more order pages remaining; results are truncated" ) ctx.breadcrumb(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete, skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Order {contact.source_order}: update of CRM contact {existing['id']} failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"Order {contact.source_order}: update of CRM contact {existing['id']} failed after retry, skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created CRM contact") created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: creating CRM contact failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} orders, created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb("No delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb( f"Setting carrier delivery preferences for order {contact.source_order} (window={window})" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb("Contact has no address; leaving city field blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"Save confirmation did not appear within 60s ({type(exc).__name__})" ) ctx.breadcrumb( f"Delivery preferences for order {contact.source_order}: {'saved' if saved else 'NOT saved'}" ) return saved --- run 33 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb( f"order {order.get('id')}: no usable email " f"({'missing' if not email else 'malformed'}), skipping" ) return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"no next page link after {pages} page(s); pagination complete") break page = client.get_json(url) if not page: ctx.breadcrumb(f"orders page {page_num}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"orders page {page_num}: no orders in batch, stopping pagination") break orders.extend(batch) pages = page_num url = page.get("next") ctx.breadcrumb( f"orders page {page_num}: got {len(batch)} order(s), has_next={bool(url)}" ) else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated" ) ctx.breadcrumb(f"fetched {len(orders)} order(s) total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {match.get('id')} by email " f"({len(by_email['results'])} result(s))" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {match.get('id')} by phone " f"({len(by_phone['results'])} result(s))" ) return match ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"merge into CRM contact {existing.get('id')}: filled {filled or 'nothing'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing early") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order}: duplicate email within this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {contact.source_order}: CRM contact {existing.get('id')} already complete, skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"order {contact.source_order}: update of CRM contact {existing['id']} failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"order {contact.source_order}: update of CRM contact {existing['id']} failed after retry, skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"order {contact.source_order}: CRM contact creation failed, skipping") skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} order(s), created={created}, " f"updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.breadcrumb("no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb( f"order {contact.source_order}: setting carrier delivery preferences, window={window}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"could not fill #email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"could not fill #name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"could not fill #city field ({type(exc).__name__})") else: ctx.breadcrumb("contact has no address; leaving #city empty") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"no save confirmation within 60s ({type(exc).__name__})" ) ctx.breadcrumb( f"order {contact.source_order}: delivery preferences {'saved' if saved else 'NOT saved'}" ) return saved --- run 34 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"orders page {pages + 1}: empty or failed response, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"orders page {pages + 1}: no orders, stopping") break pages += 1 orders.extend(batch) ctx.breadcrumb(f"orders page {pages}: {len(batch)} orders (total {len(orders)})") url = page.get("next") else: if url: ctx.breadcrumb(f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") ctx.breadcrumb(f"fetched {len(orders)} orders across {pages} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.breadcrumb(f"order {contact.source_order}: matched CRM contact {match.get('id')} by email") return match if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup failed") if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: matched CRM contact {match.get('id')} by phone") return match if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup failed") ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"CRM contact {existing.get('id')}: nothing new to add, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated from order {contact.source_order}") updated += 1 else: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"order {contact.source_order}: CRM create failed, skipping") skipped += 1 ctx.breadcrumb( f"customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"from {len(orders)} orders" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"{ref}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"{ref}: no save confirmation within 60s ({type(exc).__name__})") ctx.breadcrumb(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 35 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Orders page {page_num} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Orders page {page_num} was empty; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"Orders page {page_num}: {len(batch)} orders (total {len(orders)}), " f"{'more pages' if url else 'last page'}" ) else: if url: ctx.breadcrumb( f"Hit MAX_PAGES={MAX_PAGES} with more pages remaining; " f"order list is truncated at {len(orders)} orders" ) return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {order.get('id')}: skipped, missing or invalid email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: skipped, customer already processed this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete; skipped" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.breadcrumb( f"Order {contact.source_order}: updating CRM contact {existing.get('id')}, " f"filling fields {filled}" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.breadcrumb(f"CRM update of contact {existing['id']} failed after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created CRM contact {resp.get('id') if isinstance(resp, dict) else ''}".rstrip()) created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: CRM create failed; counted as skipped") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} orders, created={created}, " f"updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.breadcrumb("No delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.breadcrumb(f"Setting carrier delivery preferences for {ref}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier #email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier #name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier #city field ({type(exc).__name__})") else: ctx.breadcrumb(f"No address on {ref}; leaving carrier #city field blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click carrier #save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"No save confirmation from carrier within 60s ({type(exc).__name__})" ) ctx.breadcrumb(f"Carrier delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 36 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"Shop orders page {pages} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Shop orders page {pages}: {len(batch)} orders (running total {len(orders)})") url = page.get("next") else: if url: ctx.breadcrumb( f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results may be incomplete" ) ctx.breadcrumb(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"CRM lookup by email returned no response (order {contact.source_order})") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"CRM lookup by phone returned no response (order {contact.source_order})") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order_id}: CRM contact {existing.get('id')} already complete; skipped") skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.breadcrumb( f"Order {order_id}: updating CRM contact {existing.get('id')} (fields: {', '.join(changed)})" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of CRM contact {existing.get('id')} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing.get('id')}") updated += 1 else: ctx.breadcrumb(f"Update of CRM contact {existing.get('id')} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {len(orders)} orders, created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb( f"Setting carrier delivery preferences for order {contact.source_order} (window={window})" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill #city ({type(exc).__name__})") else: ctx.breadcrumb("Contact has no address; leaving #city blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"No save confirmation within 60s ({type(exc).__name__})") ctx.breadcrumb( f"Carrier delivery preferences for order {contact.source_order}: {'saved' if saved else 'not saved'}" ) return saved --- run 37 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')!r} skipped: missing or invalid email") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since!r}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"Shop orders page {pages} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"Fetched shop orders page {pages}: {len(batch)} orders " f"({len(orders)} total, more pages: {bool(url)})" ) else: if url: ctx.breadcrumb( f"Stopped fetching after MAX_PAGES={MAX_PAGES}; more orders remain unfetched" ) ctx.breadcrumb(f"Fetched {len(orders)} shop orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"CRM lookup by email failed for order {contact.source_order!r}") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order!r} matched CRM contact " f"{by_email['results'][0].get('id')!r} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"CRM lookup by phone failed for order {contact.source_order!r}") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order!r} matched CRM contact " f"{by_phone['results'][0].get('id')!r} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order!r}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting CRM sync of new customers since {since!r}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb( f"Order {contact.source_order!r} skipped: customer already processed in this run" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"CRM contact {existing.get('id')!r} already complete; " f"no update needed for order {contact.source_order!r}" ) skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.breadcrumb( f"Updating CRM contact {existing.get('id')!r} from order " f"{contact.source_order!r}; filling fields: {changed}" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb( f"Update of CRM contact {existing.get('id')!r} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing.get('id')!r}") updated += 1 else: ctx.breadcrumb( f"Update of CRM contact {existing.get('id')!r} failed after retry; " f"counting order {contact.source_order!r} as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb( f"Created CRM contact {new_id!r} from order {contact.source_order!r}" ) created += 1 else: ctx.breadcrumb( f"Creating CRM contact failed for order {contact.source_order!r} " f"(not retried); counting as skipped" ) skipped += 1 ctx.breadcrumb( f"CRM sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" ctx.breadcrumb( f"Setting carrier delivery preferences for order {contact.source_order!r}: " f"window={window!r}{' (default)' if used_default else ''}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb( f"Carrier preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier form field #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier form field #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill carrier form field #city ({type(exc).__name__})") else: ctx.breadcrumb("Contact has no address; leaving carrier form #city empty") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"Could not click carrier form #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb( f"Carrier save confirmation did not appear within 60s ({type(exc).__name__})" ) ctx.breadcrumb( f"Carrier delivery preferences for order {contact.source_order!r}: " f"{'saved' if saved else 'NOT saved'}" ) return saved --- run 38 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"no further pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.breadcrumb(f"order page {page_num}: empty or failed response, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {page_num}: no orders, stopping") break orders.extend(batch) url = page.get("next") ctx.breadcrumb( f"order page {page_num}: got {len(batch)} orders " f"(total {len(orders)}, has_next={bool(url)})" ) else: if url: ctx.breadcrumb(f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") ctx.breadcrumb(f"fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM email lookup returned no response") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM phone lookup returned no response") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") ctx.breadcrumb( f"CRM contact {existing.get('id')}: merge filled fields {filled if filled else 'none'}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finishing early") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: skipped += 1 ctx.breadcrumb(f"order {order_id}: skipped (invalid or missing email)") continue if contact.email in seen: skipped += 1 ctx.breadcrumb(f"order {order_id}: skipped (duplicate email already processed this run)") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: existing_id = existing.get("id") merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.breadcrumb(f"order {order_id}: skipped (CRM contact {existing_id} already complete)") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"order {order_id}: update of CRM contact {existing_id} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.breadcrumb(f"order {order_id}: updated CRM contact {existing_id}") else: skipped += 1 ctx.breadcrumb(f"order {order_id}: update of CRM contact {existing_id} failed after retry; skipped") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {order_id}: created CRM contact {new_id}") else: skipped += 1 ctx.breadcrumb(f"order {order_id}: CRM contact creation failed; skipped") ctx.breadcrumb( f"customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" ctx.breadcrumb( f"order {contact.source_order}: setting carrier delivery window '{window}'" f"{' (default)' if used_default else ''}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"could not fill #email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"could not fill #name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"could not fill #city field ({type(exc).__name__})") else: ctx.breadcrumb("contact has no address; leaving #city empty") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"save confirmation not seen within 60s ({type(exc).__name__})") ctx.breadcrumb(f"order {contact.source_order}: delivery preferences saved={saved}") return saved --- run 39 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None phone = _normalize_phone(order.get("phone", "")) ctx.breadcrumb( f"order {order.get('id')}: built contact " f"(has_name={bool(first)}, has_phone={bool(phone)}, has_address={address is not None})" ) return Contact( email=email, first_name=first, last_name=last, phone=phone, address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: ctx.breadcrumb(f"no further order pages after page {pages}") break page = client.get_json(url) pages += 1 if not page: ctx.breadcrumb(f"order page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {pages}: contained no orders, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"order page {pages}: got {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.breadcrumb( f"hit MAX_PAGES={MAX_PAGES} with more pages remaining; later orders were not fetched" ) ctx.breadcrumb(f"fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.breadcrumb(f"order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty fields {filled}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no orders to sync; finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {order.get('id')}: skipped, same customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb( f"order {order.get('id')}: CRM contact {existing.get('id')} already complete, nothing to update" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb( f"order {order.get('id')}: update of CRM contact {existing['id']} failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"order {order.get('id')}: CRM contact creation failed; counted as skipped") skipped += 1 ctx.breadcrumb( f"customer sync finished: {len(orders)} orders, created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.breadcrumb(f"order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.breadcrumb(f"order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"carrier form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"could not fill carrier email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"could not fill carrier name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"could not fill carrier city field ({type(exc).__name__})") else: ctx.breadcrumb("contact has no address; leaving carrier city field empty") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"could not click carrier save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"no save confirmation from carrier within 60s ({type(exc).__name__})") ctx.breadcrumb(f"order {contact.source_order}: carrier delivery preferences saved={saved}") return saved --- run 40 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 # Breadcrumbs never include customer emails, names, phone numbers or addresses. # Records are identified by shop order id or CRM contact id only, and failures # are reported by exception type, because exception messages can echo the # values that were being filled in. def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: skipped, no usable email") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Shop orders: page {pages + 1} returned no response, stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.breadcrumb( f"Shop orders: hit MAX_PAGES={MAX_PAGES} with more pages remaining; results are truncated" ) ctx.breadcrumb(f"Shop orders: fetched {len(orders)} order(s) across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb( f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.breadcrumb(f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Customer sync: starting for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("Customer sync: no new orders, nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: skipped, customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"CRM contact {existing.get('id')}: already complete, no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"CRM contact {existing['id']}: updated from order {order.get('id')}") updated += 1 else: ctx.breadcrumb(f"CRM contact {existing['id']}: update failed after retry, counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.breadcrumb(f"Order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: CRM create failed (no retry), counted as skipped") skipped += 1 ctx.breadcrumb( f"Customer sync: finished with {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} order(s)" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() used_default = window is None or window == "" window = window or "weekday-daytime" ref = f"Delivery preferences (order {contact.source_order})" ctx.breadcrumb(f"{ref}: opening carrier form with window={window}{' (default)' if used_default else ''}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.breadcrumb(f"{ref}: form did not appear within 30s ({type(exc).__name__}), continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.breadcrumb(f"{ref}: no address on file, city left blank") try: client.click("#save") except Exception as exc: ctx.breadcrumb(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.breadcrumb(f"{ref}: no save confirmation within 60s ({type(exc).__name__})") ctx.breadcrumb(f"{ref}: {'saved' if saved else 'NOT saved'}") return saved Claude Opus 5.5, ctx.zorp (contact sync) ======================================== --- run 1 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop returned an empty or failed response on page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {pages} contained no orders; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; results may be incomplete") ctx.zorp(f"Finished fetching orders: {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders to sync; nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Order {order.get('id')}: skipped (no usable email)") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Order {order.get('id')}: skipped (customer already processed in this run)") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Order {order.get('id')}: CRM contact {existing.get('id')} already complete; no update needed") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"CRM contact {existing['id']}: updated from order {order.get('id')}") else: skipped += 1 ctx.zorp(f"CRM contact {existing['id']}: update failed after retry; counted as skipped") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Order {order.get('id')}: created new CRM contact") else: skipped += 1 ctx.zorp(f"Order {order.get('id')}: failed to create CRM contact; counted as skipped") ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Carrier preferences form did not appear within 30s: {type(exc).__name__}: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill carrier email field: {type(exc).__name__}: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill carrier name field: {type(exc).__name__}: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill carrier city field: {type(exc).__name__}: {exc}") else: ctx.zorp(f"Order {contact.source_order}: no address on contact; leaving carrier city field blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click carrier save button: {type(exc).__name__}: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Carrier did not confirm save within 60s: {type(exc).__name__}: {exc}") if saved: ctx.zorp(f"Order {contact.source_order}: carrier delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: carrier delivery preferences NOT saved") return saved --- run 2 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages_fetched = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages_fetched += 1 if not page: ctx.zorp(f"Shop returned an empty response on page {pages_fetched}; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Stopped after reaching the {MAX_PAGES}-page limit; more orders remain unfetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"Order {contact.source_order}: no CRM match by email; matched contact " f"{match.get('id')} by phone" ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {order_id}: CRM contact {existing.get('id')} already up to date; skipped" ) skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp( f"Order {order_id}: updated CRM contact {existing['id']} " f"(filled: {', '.join(changed)})" ) updated += 1 else: ctx.zorp( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp( f"Setting carrier delivery preferences for order {contact.source_order} (window: {window})" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing") fields = [("#email", contact.email), ("#name", full_name)] if contact.address: fields.append(("#city", contact.address.get("city", ""))) for selector, value in fields: try: client.fill(selector, value) except Exception as exc: ctx.zorp(f"Could not fill {selector} ({type(exc).__name__}); continuing") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"No save confirmation within 60s ({type(exc).__name__}); " f"preferences for order {contact.source_order} may not have been recorded" ) if saved: ctx.zorp(f"Delivery preferences saved for order {contact.source_order}") return saved --- run 3 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no data for page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} total so far)") url = page.get("next") else: if url: ctx.zorp( f"Stopped after MAX_PAGES={MAX_PAGES} pages with more pages remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM email lookup returned no response") if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM phone lookup returned no response") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {order_id}: CRM contact {existing.get('id')} already complete; skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp( f"Order {order_id}: CRM update of contact {existing['id']} failed after retry; " "counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.zorp(f"Order {order_id}: CRM contact creation failed; counted as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" label = f"order {contact.source_order}" ctx.zorp(f"Setting delivery preferences for {label} with window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"{label}: preferences form did not appear within 30s ({type(exc).__name__})") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"{label}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"{label}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"{label}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"{label}: no address on contact; city field left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"{label}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"{label}: no save confirmation within 60s ({type(exc).__name__}); " "preferences may not have been recorded" ) if saved: ctx.zorp(f"{label}: delivery preferences saved") return saved --- run 4 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no response for order page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Hit MAX_PAGES ({MAX_PAGES}) while fetching orders; " "more pages remain and were not fetched" ) ctx.zorp(f"Fetched {len(orders)} order(s) across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {order.get('id')}: CRM contact {existing.get('id')} " "already up to date, skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp( f"Order {order.get('id')}: update of CRM contact {existing['id']} " "failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.zorp( f"Order {order.get('id')}: creating CRM contact failed (no retry); " "counted as skipped" ) skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} order(s), " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp(f"Order {contact.source_order}: no delivery window given, using weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: setting carrier delivery window to {window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})" ) else: ctx.zorp(f"Order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__}); delivery preferences not confirmed" ) if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved") return saved --- run 5 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop orders page {pages + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Stopped fetching orders at MAX_PAGES={MAX_PAGES}; more pages remain and were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: customer already handled earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete, no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {contact.source_order}: CRM update for contact {existing['id']} failed after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {contact.source_order}: created new CRM contact {resp.get('id') if isinstance(resp, dict) else ''}".rstrip()) created += 1 else: ctx.zorp(f"Order {contact.source_order}: CRM create failed (no retry); counted as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Order {contact.source_order}: carrier confirmed delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: no save confirmation from carrier within 60s; preferences may not be recorded") return saved --- run 6 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no response for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched orders page {pages} with {len(batch)} orders") url = page.get("next") else: if url: ctx.zorp(f"Stopped after MAX_PAGES={MAX_PAGES}; more orders may remain unfetched") ctx.zorp(f"Fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: skipped, customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order_id}: CRM contact {existing.get('id')} already complete, no update needed") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order_id}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']} (filled: {', '.join(filled)})") updated += 1 else: ctx.zorp(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.zorp(f"Order {order_id}: creating CRM contact failed; counted as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(source_order, step: str, action) -> bool: """Run one portal step, recording (but not raising) any failure.""" try: action() return True except Exception as exc: # noqa: BLE001 - portal steps are best-effort by design ctx.zorp(f"Order {source_order}: carrier portal step '{step}' failed ({type(exc).__name__})") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" order_id = contact.source_order ctx.zorp(f"Order {order_id}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") _attempt(order_id, "wait for form", lambda: client.wait_for("#preferences-form", timeout=30)) _attempt(order_id, "fill email", lambda: client.fill("#email", contact.email)) _attempt(order_id, "fill name", lambda: client.fill("#name", full_name)) if contact.address: _attempt(order_id, "fill city", lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.zorp(f"Order {order_id}: no address on contact, leaving city blank") _attempt(order_id, "click save", lambda: client.click("#save")) saved = _attempt( order_id, "wait for save confirmation", lambda: client.wait_for(".preferences-saved", timeout=60) ) if saved: ctx.zorp(f"Order {order_id}: carrier delivery preferences saved") else: ctx.zorp(f"Order {order_id}: carrier delivery preferences not confirmed as saved") return saved --- run 7 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Order page {pages} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {pages} contained no orders; stopping pagination") break orders.extend(batch) ctx.zorp(f"Order page {pages}: {len(batch)} orders (running total {len(orders)})") url = page.get("next") else: if url: ctx.zorp( f"Stopped after MAX_PAGES={MAX_PAGES} pages with more pages remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone" ) return match ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: skipped (customer already processed in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {order_id}: CRM contact {existing.get('id')} already complete; " "no update needed" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; " "counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.zorp( f"Order {order_id}: creating CRM contact failed (no retry); counted as skipped" ) skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp( f"Order {contact.source_order}: no delivery window given; " "defaulting to weekday-daytime" ) window = window or "weekday-daytime" ctx.zorp( f"Order {contact.source_order}: opening carrier preferences form (window={window})" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})" ) try: client.fill("#name", full_name) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})" ) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})" ) else: ctx.zorp(f"Order {contact.source_order}: no address on contact; city left blank") try: client.click("#save") except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not click save ({type(exc).__name__})" ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__}); preferences may not have been recorded" ) if saved: ctx.zorp( f"Order {contact.source_order}: delivery preferences saved (window={window})" ) return saved --- run 8 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')!r} has no usable email; cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since!r} (up to {MAX_PAGES} pages)") pages_read = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no data for order page {pages_read + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages_read += 1 orders.extend(batch) ctx.zorp(f"Read order page {pages_read}: {len(batch)} orders ({len(orders)} total so far)") url = page.get("next") else: if url: ctx.zorp( f"Stopped after reaching the {MAX_PAGES}-page limit; more orders remain unfetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages_read} pages") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp( f"Order {contact.source_order!r}: matched existing CRM contact " f"{match.get('id')!r} by email" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"Order {contact.source_order!r}: matched existing CRM contact " f"{match.get('id')!r} by phone" ) return match ctx.zorp(f"Order {contact.source_order!r}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp( f"CRM contact {existing.get('id')!r}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since!r}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipping order {order.get('id')!r}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp( f"Skipping order {contact.source_order!r}: customer already handled earlier in this run" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Skipping order {contact.source_order!r}: CRM contact " f"{existing.get('id')!r} already has all known details" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Update of CRM contact {existing['id']!r} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp( f"Updated CRM contact {existing['id']!r} from order {contact.source_order!r}" ) updated += 1 else: ctx.zorp( f"Could not update CRM contact {existing['id']!r} after retry; " f"counting order {contact.source_order!r} as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp( f"Created CRM contact {new_id!r} from order {contact.source_order!r}" ) created += 1 else: ctx.zorp( f"Could not create CRM contact for order {contact.source_order!r}; " f"counting it as skipped" ) skipped += 1 ctx.zorp( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped " f"out of {len(orders)} orders" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp("No delivery window given; using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.zorp( f"Setting carrier delivery preferences for order {contact.source_order!r} " f"with window {window!r}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill the email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill the name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill the city field ({type(exc).__name__})") else: ctx.zorp("Contact has no address; leaving the city field blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click the save button ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier confirmed delivery preferences saved for order {contact.source_order!r}") else: ctx.zorp( f"No save confirmation from the carrier within 60s for order " f"{contact.source_order!r}; preferences may not have been recorded" ) return saved --- run 9 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch: empty or failed response on page {pages + 1}, stopping") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Order fetch: page {pages} returned {len(batch)} orders") url = page.get("next") else: if url: ctx.zorp(f"Order fetch: hit MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") ctx.zorp(f"Order fetch: {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Customer sync starting for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("Customer sync: no orders to process") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: duplicate customer within this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"CRM contact {existing.get('id')}: nothing new to add, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry, counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: CRM create failed, counted as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__})") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: save confirmation not seen within 60s; preferences may not be saved") return saved --- run 10 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None if address is None: ctx.zorp(f"Order {order.get('id')}: no shipping address line1, contact will have no address") return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop orders page {pages} returned no response; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Hit MAX_PAGES={MAX_PAGES} while more shop orders remained; " "remaining orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} shop orders created after {since} across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): results = by_email["results"] if len(results) > 1: ctx.zorp( f"Order {contact.source_order}: {len(results)} CRM contacts matched by email; " f"using the first (id {results[0].get('id')})" ) else: ctx.zorp(f"Order {contact.source_order}: matched CRM contact {results[0].get('id')} by email") return results[0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): results = by_phone["results"] ctx.zorp( f"Order {contact.source_order}: no email match, matched CRM contact " f"{results[0].get('id')} by phone only ({len(results)} phone match(es))" ) return results[0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty field(s) {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: customer already processed earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete, no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: creating CRM contact failed (no retry); skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form for window {window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact, city field left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})") if saved: ctx.zorp(f"Order {contact.source_order}: carrier delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: carrier delivery preferences NOT confirmed saved") return saved --- run 11 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop orders page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Shop orders page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.zorp(f"Shop orders page {pages}: fetched {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order.get('id')}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: skipped (customer already processed in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete, skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated from order {contact.source_order}") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry, skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: CRM contact creation failed, skipped") skipped += 1 ctx.zorp(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact, city left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Order {contact.source_order}: save confirmation not seen within 60s ({type(exc).__name__})") if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved with carrier") else: ctx.zorp(f"Order {contact.source_order}: delivery preferences NOT confirmed as saved") return saved --- run 12 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Order page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.zorp(f"Order page {pages}: received {len(batch)} orders") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{match.get('id')} by email" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{match.get('id')} by phone" ) return match ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp( f"Order {contact.source_order}: customer already processed in this run, skipping" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"CRM contact {existing.get('id')}: nothing new to add, skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp( f"Order {contact.source_order}: created CRM contact " f"{resp.get('id') if isinstance(resp, dict) else ''}".rstrip() ) created += 1 else: ctx.zorp(f"Order {contact.source_order}: failed to create CRM contact, skipping") skipped += 1 ctx.zorp( f"Customer sync finished: {created} created, {updated} updated, " f"{skipped} skipped out of {len(orders)} orders" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.zorp(f"Setting delivery preferences for {ref} (window: {window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Delivery preferences for {ref}: form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill city ({type(exc).__name__})") else: ctx.zorp(f"Delivery preferences for {ref}: no address on file, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not click save ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Delivery preferences for {ref}: saved") else: ctx.zorp( f"Delivery preferences for {ref}: save confirmation not seen within 60s; " "preferences may not have been recorded" ) return saved --- run 13 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Order page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.zorp(f"Order page {pages}: fetched {len(batch)} orders (total {len(orders)})") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {order.get('id')}: CRM contact {existing.get('id')} " "already complete, nothing to update" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {order.get('id')}: update of CRM contact {existing['id']} " "failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp( f"Order {order.get('id')}: update of CRM contact {existing['id']} " "failed after retry, skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {order.get('id')}: created new CRM contact") created += 1 else: ctx.zorp(f"Order {order.get('id')}: creating CRM contact failed, skipping") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.zorp(f"Setting carrier delivery preferences for {ref} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") def _attempt(step: str, action) -> bool: try: action() return True except Exception as exc: # keep going, matching previous best-effort behavior ctx.zorp(f"Carrier preferences for {ref}: {step} failed ({type(exc).__name__})") return False _attempt("waiting for preferences form", lambda: client.wait_for("#preferences-form", timeout=30)) _attempt("filling email field", lambda: client.fill("#email", contact.email)) _attempt("filling name field", lambda: client.fill("#name", full_name)) if contact.address: _attempt("filling city field", lambda: client.fill("#city", contact.address.get("city", ""))) else: ctx.zorp(f"Carrier preferences for {ref}: no address on contact, leaving city blank") _attempt("clicking save", lambda: client.click("#save")) saved = _attempt( "waiting for save confirmation", lambda: client.wait_for(".preferences-saved", timeout=60), ) if saved: ctx.zorp(f"Carrier preferences for {ref}: saved") else: ctx.zorp(f"Carrier preferences for {ref}: not confirmed as saved") return saved --- run 14 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop orders page {pages + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Stopped fetching shop orders after reaching the {MAX_PAGES}-page limit; " "more orders may remain" ) ctx.zorp(f"Fetched {len(orders)} shop orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone " "(no email match)" ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting CRM sync of new shop customers since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new shop orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: skipped, no usable email address") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: skipped, customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: existing_id = existing.get("id") merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {order_id}: CRM contact {existing_id} already up to date; no changes" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing_id}", merged) if resp is None: ctx.zorp( f"Order {order_id}: update of CRM contact {existing_id} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing_id}", merged) if resp is not None: ctx.zorp( f"Order {order_id}: updated CRM contact {existing_id} " f"(filled {', '.join(filled)})" ) updated += 1 else: ctx.zorp( f"Order {order_id}: update of CRM contact {existing_id} failed after retry; " "counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.zorp( f"Order {order_id}: creating CRM contact failed (no retry); counted as skipped" ) skipped += 1 ctx.zorp( f"CRM sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" label = f"contact from order {contact.source_order}" ctx.zorp(f"Setting carrier delivery window '{window}' for {label}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Carrier preferences form did not appear within 30s for {label}; " f"continuing anyway ({type(exc).__name__})" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field on carrier form for {label} ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field on carrier form for {label} ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp( f"Could not fill city field on carrier form for {label} ({type(exc).__name__})" ) else: ctx.zorp(f"No address on file for {label}; leaving city blank on carrier form") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save on carrier form for {label} ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Carrier did not confirm saved preferences within 60s for {label} " f"({type(exc).__name__})" ) if saved: ctx.zorp(f"Carrier confirmed delivery window '{window}' saved for {label}") else: ctx.zorp(f"Delivery preferences NOT saved with carrier for {label}") return saved --- run 15 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop orders page {pages} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " f"some orders were not fetched" ) ctx.zorp(f"Finished fetching orders: {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{match.get('id')} by email" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{match.get('id')} by phone" ) return match ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order.get('id')}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.zorp( f"Order {contact.source_order}: skipped (customer already processed this run)" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {contact.source_order}: CRM contact {existing.get('id')} " f"already complete; skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {contact.source_order}: update of CRM contact " f"{existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp( f"Order {contact.source_order}: updated CRM contact {existing['id']}" ) updated += 1 else: ctx.zorp( f"Order {contact.source_order}: update of CRM contact " f"{existing['id']} failed after retry; skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp( f"Order {contact.source_order}: created CRM contact" + (f" {new_id}" if new_id is not None else "") ) created += 1 else: ctx.zorp( f"Order {contact.source_order}: creating CRM contact failed; skipped" ) skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.zorp(f"Setting carrier delivery preferences for {ref} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"{ref}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"{ref}: no address on contact; city field left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"{ref}: clicking save failed ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"{ref}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.zorp( f"{ref}: delivery preferences " + ("saved" if saved else "NOT confirmed as saved") ) return saved --- run 16 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')!r}: no usable email, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since!r}") for page_num in range(1, MAX_PAGES + 1): if not url: ctx.zorp(f"No further pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned an empty or failed response for page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {page_num} contained no orders; stopping pagination") break orders.extend(batch) ctx.zorp(f"Page {page_num}: fetched {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES={MAX_PAGES} with more pages still available; " f"remaining orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order!r}: CRM email lookup failed") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order!r}: matched existing CRM contact " f"{by_email['results'][0].get('id')!r} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order!r}: CRM phone lookup failed") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order!r}: matched existing CRM contact " f"{by_phone['results'][0].get('id')!r} by phone" ) return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order!r}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')!r}: filling empty fields {filled}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since!r}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id!r}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id!r}: skipped (customer already processed in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order_id!r}: CRM contact {existing.get('id')!r} already complete; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order_id!r}: update of CRM contact {existing['id']!r} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id!r}: updated CRM contact {existing['id']!r}") updated += 1 else: ctx.zorp(f"Order {order_id!r}: update of CRM contact {existing['id']!r} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order_id!r}: created CRM contact {new_id!r}") created += 1 else: ctx.zorp(f"Order {order_id!r}: creating CRM contact failed; skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order!r}" ctx.zorp(f"Setting delivery preferences for {ref} (window={window!r})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"{ref}: could not fill #email ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"{ref}: could not fill #name ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"{ref}: could not fill #city ({type(exc).__name__})") else: ctx.zorp(f"{ref}: no address on contact; leaving #city empty") try: client.click("#save") except Exception as exc: ctx.zorp(f"{ref}: could not click #save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"{ref}: save confirmation not seen within 60s ({type(exc).__name__})") ctx.zorp(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 17 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from typing import Any, Callable from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"fetch orders: page {pages + 1} returned no response; stopping pagination early") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"fetch orders: stopped at MAX_PAGES={MAX_PAGES} with more pages remaining; " f"orders after the first {len(orders)} were not fetched" ) ctx.zorp(f"fetch orders: {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"order {contact.source_order}: no CRM match by email; " f"matched CRM contact {match.get('id')} by phone instead" ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"sync new customers: starting, since={since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("sync new customers: no orders found; nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"order {order_id}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"order {order_id}: skipped, customer already handled earlier in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"order {order_id}: CRM contact {existing.get('id')} already complete; no update needed") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"order {order_id}: updated CRM contact {existing['id']}, filled {', '.join(filled)}") updated += 1 else: ctx.zorp( f"order {order_id}: update of CRM contact {existing['id']} failed after retry; " f"counted as skipped, changes not saved" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"order {order_id}: created new CRM contact") created += 1 else: ctx.zorp(f"order {order_id}: creating CRM contact failed; counted as skipped, contact not created") skipped += 1 ctx.zorp( f"sync new customers: done, {len(orders)} orders -> " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(order_id: Any, step: str, action: Callable[..., Any], *args: Any, **kwargs: Any) -> bool: """Run one portal step, recording (and swallowing) any failure. Returns True if it succeeded.""" try: action(*args, **kwargs) return True except Exception as exc: ctx.zorp(f"delivery preferences, order {order_id}: {step} failed ({type(exc).__name__})") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" order_id = contact.source_order full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp(f"delivery preferences, order {order_id}: no window given; using default 'weekday-daytime'") window = window or "weekday-daytime" client.open(f"{CARRIER_URL}/preferences/new?window={window}") _attempt(order_id, "waiting for preferences form", client.wait_for, "#preferences-form", timeout=30) _attempt(order_id, "filling email field", client.fill, "#email", contact.email) _attempt(order_id, "filling name field", client.fill, "#name", full_name) if contact.address: _attempt(order_id, "filling city field", client.fill, "#city", contact.address.get("city", "")) else: ctx.zorp(f"delivery preferences, order {order_id}: no address on contact; city field left blank") _attempt(order_id, "clicking save", client.click, "#save") saved = _attempt(order_id, "waiting for save confirmation", client.wait_for, ".preferences-saved", timeout=60) if saved: ctx.zorp(f"delivery preferences, order {order_id}: saved with window '{window}'") else: ctx.zorp(f"delivery preferences, order {order_id}: save not confirmed; preferences may not be recorded") return saved --- run 18 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned an empty or failed response on page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} total so far)") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; some orders were not fetched") ctx.zorp(f"Fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone") return match ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"CRM contact {existing.get('id')}: nothing new to add, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated from order {contact.source_order}") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry, counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: CRM contact creation failed, counted as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.zorp(f"Setting delivery preferences for {ref} with window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: form did not appear within 30s ({type(exc).__name__})") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Delivery preferences for {ref}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Delivery preferences for {ref}: save not confirmed within 60s ({type(exc).__name__})" ) if saved: ctx.zorp(f"Delivery preferences for {ref}: saved") return saved --- run 19 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}) with more orders remaining; results are truncated") ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact {existing['id']} already complete, no update needed") skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {contact.source_order}: updated CRM contact {existing['id']} (filled: {', '.join(changed)})") updated += 1 else: ctx.zorp(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: creating CRM contact failed; skipped") skipped += 1 ctx.zorp(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped out of {len(orders)} orders") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact; city left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})") if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: delivery preferences NOT confirmed as saved") return saved --- run 20 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned an empty or failed response on page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} total so far)") url = page.get("next") else: if url: ctx.zorp(f"Stopped after MAX_PAGES={MAX_PAGES} pages; more orders may remain unfetched") ctx.zorp(f"Fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"CRM contact {existing.get('id')}: already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated from order {order.get('id')}") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry, counting as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order.get('id')}: created new CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {order.get('id')}: creating CRM contact failed, counting as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.zorp(f"Setting delivery preferences for {ref} with window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Delivery preferences for {ref}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Delivery preferences for {ref}: no save confirmation within 60s ({type(exc).__name__})" ) ctx.zorp(f"Delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 21 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages_fetched = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages_fetched += 1 if not page: ctx.zorp(f"Shop returned no data for page {pages_fetched}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {pages_fetched} contained no orders; stopping pagination") break orders.extend(batch) ctx.zorp(f"Page {pages_fetched}: fetched {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp( f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp( f"Order {contact.source_order}: customer already processed earlier in this run; skipping" ) skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already up to date; skipping" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed after retry; skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp( f"Order {contact.source_order}: creating CRM contact failed; skipping" ) skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp( f"Setting carrier delivery preferences for order {contact.source_order} " f"(window={window})" ) client.open(f"{CARRIER_URL}/preferences/new?window={quote_plus(window)}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field ({type(exc).__name__})") else: ctx.zorp("Contact has no address; leaving city field empty") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save button ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preferences saved for order {contact.source_order}") else: ctx.zorp( f"Carrier did not confirm saving delivery preferences for order " f"{contact.source_order} within 60s" ) return saved --- run 22 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Order page {pages}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {pages}: no orders, stopping pagination") break orders.extend(batch) ctx.zorp(f"Order page {pages}: got {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Stopped after MAX_PAGES={MAX_PAGES} with more pages remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: skipped (customer already handled earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order_id}: CRM contact {existing.get('id')} already complete, skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order_id}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry, skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {order_id}: creating CRM contact failed, skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp("No delivery window given; using default 'weekday-daytime'") window = window or "weekday-daytime" ref = f"contact from order {contact.source_order}" ctx.zorp(f"Setting delivery preferences for {ref}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={quote_plus(window)}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"No address on {ref}; city field left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"No save confirmation within 60s ({type(exc).__name__})") ctx.zorp(f"Delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 23 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')!r} has no usable email; skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop returned no data for orders page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Orders page {pages} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {pages} ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"CRM email lookup failed for order {contact.source_order!r}") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order!r} matched CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"CRM phone lookup failed for order {contact.source_order!r}") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order!r} matched CRM contact by phone") return by_phone["results"][0] ctx.zorp(f"No existing CRM contact found for order {contact.source_order!r}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"Filling empty fields on CRM contact {existing.get('id')!r}: {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')!r} is for a customer already handled this run; skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"CRM contact {existing.get('id')!r} already up to date; skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']!r} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']!r} from order {order.get('id')!r}") updated += 1 else: ctx.zorp(f"Update of CRM contact {existing['id']!r} failed after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order.get('id')!r}") created += 1 else: ctx.zorp(f"Creating CRM contact from order {order.get('id')!r} failed; skipping") skipped += 1 ctx.zorp( f"Customer sync finished: {created} created, {updated} updated, " f"{skipped} skipped from {len(orders)} orders" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = contact.source_order ctx.zorp(f"Setting delivery preferences for order {ref!r} with window {window!r}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {ref!r} has no address; leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"No save confirmation within 60s ({type(exc).__name__})") ctx.zorp( f"Delivery preferences for order {ref!r} " + ("saved" if saved else "were NOT confirmed as saved") ) return saved --- run 24 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email address; skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched orders page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES ({MAX_PAGES}) while more orders remain; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders created since {since} across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by email" ) return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{match.get('id')} by phone" ) return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: customer already processed in this run; skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already up to date; skipping" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp( f"Order {contact.source_order}: updated CRM contact {existing['id']} " f"(filled fields: {', '.join(filled)})" ) updated += 1 else: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed after retry; counting as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp( f"Order {contact.source_order}: creating CRM contact failed; " "counting as skipped" ) skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp( f"Order {contact.source_order}: no delivery window given; " "defaulting to weekday-daytime" ) window = window or "weekday-daytime" ctx.zorp( f"Order {contact.source_order}: setting carrier delivery preference " f"(window={window})" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})" ) try: client.fill("#name", full_name) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})" ) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill city field " f"({type(exc).__name__})" ) else: ctx.zorp(f"Order {contact.source_order}: no address on contact; leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not click save button ({type(exc).__name__})" ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__})" ) if saved: ctx.zorp(f"Order {contact.source_order}: delivery preference saved (window={window})") else: ctx.zorp(f"Order {contact.source_order}: delivery preference was NOT confirmed as saved") return saved --- run 25 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned an empty or failed response on page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; some orders were not fetched") ctx.zorp(f"Fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone") return match ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order.get('id')}: CRM contact {existing.get('id')} already complete, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.zorp(f"CRM update for contact {existing['id']} failed after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.zorp(f"CRM create failed for order {order.get('id')}; counted as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp("No delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field ({type(exc).__name__})") else: ctx.zorp("Contact has no address; leaving city field blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"No save confirmation within 60s ({type(exc).__name__})") ctx.zorp( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'NOT confirmed as saved'}" ) return saved --- run 26 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched orders page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; " f"some orders since {since} were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {contact.source_order}: CRM contact {existing.get('id')} " f"already complete, no update needed" ) skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " f"failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp( f"Order {contact.source_order}: updated CRM contact {existing['id']} " f"(filled fields: {', '.join(changed)})" ) updated += 1 else: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " f"failed after retry; skipping" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: creating CRM contact failed; skipping") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given, using default") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={quote_plus(window)}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) for selector, value in (("#email", contact.email), ("#name", full_name)): try: client.fill(selector, value) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill {selector} " f"({type(exc).__name__}: {exc})" ) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill #city " f"({type(exc).__name__}: {exc})" ) else: ctx.zorp(f"Order {contact.source_order}: no address on contact, leaving #city empty") try: client.click("#save") except Exception as exc: ctx.zorp( f"Order {contact.source_order}: clicking #save failed " f"({type(exc).__name__}: {exc})" ) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__}); preferences may not have been recorded" ) if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved with carrier") return saved --- run 27 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None if address is None: ctx.zorp(f"Order {order.get('id')}: no shipping address line1, contact will have no address") return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched orders page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; " f"orders beyond this point were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders created since {since} across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: customer already handled earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order.get('id')}: CRM contact {existing['id']} already complete, no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order.get('id')}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {order.get('id')}: update of CRM contact {existing['id']} failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {order.get('id')}: creating CRM contact failed, skipping") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Order {contact.source_order}: no save confirmation within 60s " f"({type(exc).__name__}); preferences may not have been recorded" ) if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved with carrier (window={window})") return saved --- run 28 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no response for order page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Stopped fetching orders after reaching the {MAX_PAGES}-page limit; " "more orders may exist and were not synced" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s) created since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone") return match return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: customer already handled earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already up to date, skipping" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed, retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp( f"Order {contact.source_order}: updated CRM contact {existing['id']} " f"(filled fields: {', '.join(filled)})" ) updated += 1 else: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed after retry; counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp( f"Order {contact.source_order}: creating CRM contact failed; counted as skipped" ) skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp(f"Order {contact.source_order}: no delivery window given, using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: setting carrier delivery window to '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: carrier preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Order {contact.source_order}: carrier confirmed delivery preferences saved") else: ctx.zorp( f"Order {contact.source_order}: no save confirmation from carrier within 60s; " "delivery preferences may not have been recorded" ) return saved --- run 29 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop orders page {pages} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched page {pages} with {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; " f"later orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Order {order.get('id')}: skipped (invalid or missing email)") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Order {order.get('id')}: skipped (customer already processed in this run)") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp( f"Order {order.get('id')}: CRM contact {existing.get('id')} " f"already complete; no update needed" ) continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Order {order.get('id')}: updated CRM contact {existing['id']}") else: skipped += 1 ctx.zorp( f"Order {order.get('id')}: CRM update for contact {existing['id']} " f"failed after retry; skipped" ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order.get('id')}: created CRM contact {new_id}") else: skipped += 1 ctx.zorp(f"Order {order.get('id')}: CRM contact creation failed; skipped") ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given; using default") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Carrier preferences form did not appear within 30s: {type(exc).__name__}: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill carrier form field #email: {type(exc).__name__}: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill carrier form field #name: {type(exc).__name__}: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill carrier form field #city: {type(exc).__name__}: {exc}") else: ctx.zorp(f"Order {contact.source_order}: no address on contact; leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click carrier form save button: {type(exc).__name__}: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Carrier did not confirm preferences were saved within 60s: " f"{type(exc).__name__}: {exc}" ) if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved with carrier") else: ctx.zorp(f"Order {contact.source_order}: delivery preferences NOT confirmed as saved") return saved --- run 30 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages_fetched = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages_fetched += 1 if not page: ctx.zorp(f"Shop returned an empty or failed response on page {pages_fetched}; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") else: if url: ctx.zorp(f"Stopped fetching orders at MAX_PAGES={MAX_PAGES}; more pages remain and were not fetched") ctx.zorp(f"Fetched {len(orders)} orders since {since} across {pages_fetched} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact {existing.get('id')} already up to date, skipping") skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {contact.source_order}: updated CRM contact {existing['id']} (filled fields: {', '.join(changed)})") updated += 1 else: ctx.zorp(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: creating CRM contact failed (no retry); counted as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form with window {window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact, city field left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Order {contact.source_order}: carrier confirmed delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: no save confirmation from carrier within 60s; preferences may not be saved") return saved --- run 31 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) address = _parse_address(order) or None if address is None: ctx.zorp(f"Order {order.get('id')}: no shipping address found") return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=address, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched orders page {pages} with {len(batch)} orders") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}) with more orders remaining; results are truncated") ctx.zorp(f"Fetched {len(orders)} orders across {pages} pages since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by email") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by phone") return match ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order.get('id')}: skipped (invalid or missing email)") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: skipped (customer already processed in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact {existing.get('id')} already complete; no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {contact.source_order}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: creating CRM contact failed; skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, {created} created, " f"{updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given; using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact; city field left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})") if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved with carrier") else: ctx.zorp(f"Order {contact.source_order}: delivery preferences were NOT confirmed as saved") return saved --- run 32 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email address; cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no response for order page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Reached the {MAX_PAGES}-page limit while fetching orders; " "more orders exist and were not fetched in this run" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s) created after {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched existing CRM contact by phone, not email") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created after {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp( f"Order {contact.source_order}: updated CRM contact {existing['id']} " f"(filled fields: {', '.join(changed)})" ) else: skipped += 1 ctx.zorp( f"Order {contact.source_order}: update of CRM contact {existing['id']} " "failed after retry; contact left unchanged" ) else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") else: skipped += 1 ctx.zorp(f"Order {contact.source_order}: failed to create CRM contact; skipped") ctx.zorp( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() requested_window = window window = window or "weekday-daytime" ref = f"order {contact.source_order}" if requested_window is None: ctx.zorp(f"Carrier preferences for {ref}: no window given; using default '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Carrier preferences for {ref}: form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Carrier preferences for {ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Carrier preferences for {ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Carrier preferences for {ref}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Carrier preferences for {ref}: contact has no address; city left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Carrier preferences for {ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Carrier preferences for {ref}: no save confirmation within 60s " f"({type(exc).__name__}); preferences may not have been recorded" ) if saved: ctx.zorp(f"Carrier preferences for {ref}: saved delivery window '{window}'") return saved --- run 33 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch: page {pages + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Order fetch: hit MAX_PAGES={MAX_PAGES} with more pages remaining; " "results are truncated" ) ctx.zorp(f"Order fetch: {len(orders)} orders across {pages} page(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email failed (no response)") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone failed (no response)") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Customer sync: starting for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("Customer sync: no orders found; nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: duplicate customer within this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 continue changed = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated fields {changed} from order {contact.source_order}") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry; counted as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {contact.source_order}: created CRM contact {resp.get('id') if isinstance(resp, dict) else ''}".rstrip()) created += 1 else: ctx.zorp(f"Order {contact.source_order}: CRM contact creation failed; counted as skipped") skipped += 1 ctx.zorp( f"Customer sync: done — {len(orders)} orders, " f"created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"Delivery prefs (order {contact.source_order})" ctx.zorp(f"{ref}: opening carrier form with window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"{ref}: form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"{ref}: no address on contact; city left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"{ref}: no save confirmation within 60s ({type(exc).__name__})") ctx.zorp(f"{ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 34 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {pages + 1}: empty or failed response, stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Order page {pages}: {len(batch)} orders (total {len(orders)})") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by email") return match if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: matched CRM contact {match.get('id')} by phone") return match ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: duplicate customer within this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"CRM contact {existing['id']}: already complete, no update needed") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated from order {contact.source_order}") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {contact.source_order}: CRM contact creation failed, skipping") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.zorp(f"Setting delivery preferences for {ref} with window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: form did not appear within 30s ({type(exc).__name__}), continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Delivery preferences for {ref}: no address on file, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Delivery preferences for {ref}: no save confirmation within 60s ({type(exc).__name__})") ctx.zorp(f"Delivery preferences for {ref}: {'saved' if saved else 'NOT saved'}") return saved --- run 35 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email address, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned an empty or failed response for order page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) url = page.get("next") else: if url: ctx.zorp( f"Reached the page limit of {MAX_PAGES} while fetching orders; " "more orders exist and were not fetched in this run" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s) created since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: customer already handled earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order.get('id')}: CRM contact {existing.get('id')} already up to date, skipping") skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order.get('id')}: updating CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order.get('id')}: updated CRM contact {existing['id']} (filled: {', '.join(filled)})") updated += 1 else: ctx.zorp(f"Order {order.get('id')}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order.get('id')}: created new CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {order.get('id')}: creating CRM contact failed; skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given, using default 'weekday-daytime'") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on file, city field left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})" ) if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved with carrier (window={window})") else: ctx.zorp(f"Order {contact.source_order}: delivery preferences were NOT confirmed as saved") return saved --- run 36 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop returned an empty or failed response on page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {pages} contained no orders; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; results are truncated") ctx.zorp(f"Finished fetching orders: {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: customer already processed earlier in this run; skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"CRM contact {existing.get('id')}: already up to date; skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated from order {order.get('id')}") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry; counting as skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order.get('id')}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {order.get('id')}: CRM contact creation failed; counting as skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp("No delivery window given; defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: setting carrier delivery window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field ({type(exc).__name__})") else: ctx.zorp("Contact has no address; leaving city field blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save button ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"No save confirmation within 60s ({type(exc).__name__})") if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: delivery preferences were NOT confirmed as saved") return saved --- run 37 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build a contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop returned an empty or failed response on page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {pages} contained no orders; stopping pagination") break orders.extend(batch) ctx.zorp(f"Page {pages}: received {len(batch)} orders ({len(orders)} total so far)") url = page.get("next") else: if url: ctx.zorp( f"Reached the page limit of {MAX_PAGES} with more pages still available; " "remaining orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): match = by_email["results"][0] ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by email" ) return match if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM email lookup failed or returned nothing") if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): match = by_phone["results"][0] ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact {match.get('id')} by phone" ) return match if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM phone lookup failed or returned nothing") ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp( f"CRM contact {existing.get('id')}: filling empty fields from order " f"{contact.source_order}: {', '.join(filled)}" ) return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders to sync; finished with nothing created, updated, or skipped") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order.get('id')}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: skipped (customer already handled earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {contact.source_order}: skipped (CRM contact {existing.get('id')} " "already has all the information)" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated from order {contact.source_order}") updated += 1 else: ctx.zorp( f"CRM contact {existing['id']}: update failed after retry; " f"order {contact.source_order} counted as skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {contact.source_order}: created CRM contact {new_id}") created += 1 else: ctx.zorp( f"Order {contact.source_order}: creating CRM contact failed; counted as skipped" ) skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders processed, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp( f"Contact from order {contact.source_order}: no delivery window given, " "using default 'weekday-daytime'" ) window = window or "weekday-daytime" ctx.zorp( f"Contact from order {contact.source_order}: opening carrier preferences form " f"with window '{window}'" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Carrier preferences form did not appear within 30s ({type(exc).__name__}); " "continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill the email field on the carrier form ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill the name field on the carrier form ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill the city field on the carrier form ({type(exc).__name__})") else: ctx.zorp( f"Contact from order {contact.source_order}: no address on file, leaving city blank" ) try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click Save on the carrier form ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Carrier did not confirm the save within 60s ({type(exc).__name__})" ) if saved: ctx.zorp( f"Contact from order {contact.source_order}: delivery preference '{window}' " "saved with the carrier" ) else: ctx.zorp( f"Contact from order {contact.source_order}: delivery preference was NOT " "confirmed as saved with the carrier" ) return saved --- run 38 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Shop returned no data for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break pages += 1 orders.extend(batch) ctx.zorp(f"Fetched orders page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Stopped after MAX_PAGES={MAX_PAGES} pages with more orders remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched existing CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: customer already processed in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {contact.source_order}: CRM contact {existing.get('id')} " "already up to date, skipping" ) skipped += 1 continue filled = sorted(k for k in merged if merged.get(k) != existing.get(k)) ctx.zorp( f"Order {contact.source_order}: updating CRM contact {existing.get('id')} " f"(filling: {', '.join(filled)})" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing.get('id')} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.zorp( f"Update of CRM contact {existing.get('id')} failed after retry; " "counting as skipped" ) skipped += 1 else: ctx.zorp(f"Order {contact.source_order}: no CRM match, creating new contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.zorp( f"Order {contact.source_order}: creating CRM contact failed; " "counting as skipped" ) skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ref = f"order {contact.source_order}" ctx.zorp(f"Setting carrier delivery preferences for {ref} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"{ref}: preferences form did not appear within 30s ({type(exc).__name__}); continuing") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"{ref}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"{ref}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"{ref}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"{ref}: no address on contact; leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"{ref}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"{ref}: no save confirmation within 60s ({type(exc).__name__})") ctx.zorp(f"{ref}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 39 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop returned an empty or failed response on page {pages}; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") else: if url: ctx.zorp(f"Hit MAX_PAGES ({MAX_PAGES}) with more pages remaining; results are truncated") ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email failed") if by_email and by_email.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_email['results'][0].get('id')} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone failed") if by_phone and by_phone.get("results"): ctx.zorp(f"Order {contact.source_order}: matched CRM contact {by_phone['results'][0].get('id')} by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: customer already handled earlier in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order.get('id')}: CRM contact {existing.get('id')} already complete, nothing to update") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"CRM contact {existing['id']}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"CRM contact {existing['id']}: updated from order {order.get('id')}") updated += 1 else: ctx.zorp(f"CRM contact {existing['id']}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {order.get('id')}: created new CRM contact {resp.get('id') if isinstance(resp, dict) else ''}".rstrip()) created += 1 else: ctx.zorp(f"Order {order.get('id')}: CRM contact creation failed, skipping") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if window is None: ctx.zorp(f"Order {contact.source_order}: no delivery window given, defaulting to weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: opening carrier preferences form (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: preferences form did not appear within 30s ({type(exc).__name__}); continuing anyway") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})") else: ctx.zorp(f"Order {contact.source_order}: no address on contact, leaving city blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})") ctx.zorp(f"Order {contact.source_order}: delivery preferences {'saved' if saved else 'NOT saved'}") return saved --- run 40 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, cannot build contact") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching shop orders created after {since}") pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) pages += 1 if not page: ctx.zorp(f"Shop orders page {pages} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Shop orders page {pages} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Shop orders page {pages}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp( f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; " "some orders were not fetched" ) ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by email returned no response") if by_email and by_email.get("results"): ctx.zorp( f"Order {contact.source_order}: matched CRM contact " f"{by_email['results'][0].get('id')} by email" ) return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone is None: ctx.zorp(f"Order {contact.source_order}: CRM lookup by phone returned no response") if by_phone and by_phone.get("results"): ctx.zorp( f"Order {contact.source_order}: matched CRM contact " f"{by_phone['results'][0].get('id')} by phone" ) return by_phone["results"][0] ctx.zorp(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) filled: list[str] = [] for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) filled.append(field) if contact.address and not merged.get("address"): merged["address"] = contact.address filled.append("address") if filled: ctx.zorp(f"CRM contact {existing.get('id')}: filling empty fields {', '.join(filled)}") return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: skipped (customer already handled earlier in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp( f"Order {order_id}: CRM contact {existing.get('id')} already complete; skipped" ) skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp( f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once" ) resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp( f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped" ) skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: new_id = resp.get("id") if isinstance(resp, dict) else None ctx.zorp(f"Order {order_id}: created CRM contact {new_id}") created += 1 else: ctx.zorp(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.zorp( f"Customer sync finished: {len(orders)} orders, " f"{created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() if not window: ctx.zorp(f"Order {contact.source_order}: no delivery window given; using weekday-daytime") window = window or "weekday-daytime" ctx.zorp(f"Order {contact.source_order}: setting carrier delivery window to {window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: preferences form did not appear within 30s " f"({type(exc).__name__}); continuing anyway" ) try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill email field ({type(exc).__name__})") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not fill name field ({type(exc).__name__})") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp( f"Order {contact.source_order}: could not fill city field ({type(exc).__name__})" ) else: ctx.zorp(f"Order {contact.source_order}: no address on contact; city left blank") try: client.click("#save") except Exception as exc: ctx.zorp(f"Order {contact.source_order}: could not click save ({type(exc).__name__})") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp( f"Order {contact.source_order}: no save confirmation within 60s ({type(exc).__name__})" ) if saved: ctx.zorp(f"Order {contact.source_order}: carrier delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: carrier delivery preferences NOT confirmed saved") return saved Claude Haiku 5.5, ctx.log (contact sync) ======================================== --- run 1 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.log(f"Reached MAX_PAGES={MAX_PAGES}; more orders may exist beyond this run") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: existing CRM contact {existing['id']} already up to date") skipped += 1 continue ctx.log(f"Order {order_id}: updating existing CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: could not update CRM contact {existing['id']}; skipping") skipped += 1 else: ctx.log(f"Order {order_id}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order_id}: created CRM contact") created += 1 else: ctx.log(f"Order {order_id}: could not create CRM contact; skipping") skipped += 1 ctx.log(f"Sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference window={window} for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier saved delivery preferences for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm saved preferences for order {contact.source_order}") return saved --- run 2 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order.get('id')}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipping order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.log(f"Sync complete: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier saved delivery preference for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm delivery preference save for order {contact.source_order}") return saved --- run 3 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be incomplete") ctx.log(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Order {contact.source_order}: found existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: found existing CRM contact by phone") return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: existing CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update to CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update to CRM contact {existing['id']} failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: failed to create CRM contact, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order}: window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Order {contact.source_order}: preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Order {contact.source_order}: no save confirmation received: {exc}") if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved") else: ctx.log(f"Order {contact.source_order}: delivery preferences were not saved") return saved --- run 4 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: if url: ctx.log(f"Reached MAX_PAGES={MAX_PAGES}; remaining orders were not fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order.get('id')}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"No changes needed for existing contact from order {contact.source_order}") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.log(f"Sync complete: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery window '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier preferences saved for order {contact.source_order}") else: ctx.log(f"Carrier preferences not confirmed as saved for order {contact.source_order}") return saved --- run 5 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}), stopping pagination") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded (or wait timed out)") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier confirmed delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm delivery preference for order {contact.source_order}") return saved --- run 6 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"No response for order page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched {len(batch)} orders from page {page_num} (total {len(orders)})") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipping order {order_id}: CRM contact {existing.get('id')} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} from order {order_id}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for contact from order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}") return saved --- run 7 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched {len(batch)} orders from page {page_num}") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.log(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"No new data for existing contact (order {order_id}); skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update failed for contact {existing['id']} (order {order_id}); retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} (order {order_id})") updated += 1 else: ctx.log(f"Update failed again for contact {existing['id']} (order {order_id}); skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}; skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preference to '{window}' (order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save button: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Save confirmation not received: {exc}") if saved: ctx.log(f"Delivery preference saved (order {contact.source_order})") else: ctx.log(f"Delivery preference was not confirmed as saved (order {contact.source_order})") return saved --- run 8 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_number} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_number} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_number} with {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be incomplete") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact for order {contact.source_order} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact for order {contact.source_order} by phone") return by_phone["results"][0] ctx.log(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Order {contact.source_order}: preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Order {contact.source_order}: save confirmation not seen: {exc}") ctx.log(f"Order {contact.source_order}: delivery preferences saved={saved}") return saved --- run 9 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.log(f"Fetching orders page {page_num + 1}") page = client.get_json(url) if not page: ctx.log(f"No response for orders page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Orders page {page_num + 1} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched {len(batch)} orders from page {page_num + 1} (total {len(orders)})") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched order {contact.source_order} to existing contact by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.log(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipped order {order.get('id')}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order.get('id')}: existing CRM contact {existing['id']} already up to date") skipped += 1 continue ctx.log(f"Order {order.get('id')}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: ctx.log(f"Order {order.get('id')}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order.get('id')}") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Preferences form did not appear for order {contact.source_order}: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field for order {contact.source_order}: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field for order {contact.source_order}: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field for order {contact.source_order}: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save for order {contact.source_order}: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Save confirmation not seen for order {contact.source_order}: {exc}") if saved: ctx.log(f"Delivery preferences saved for order {contact.source_order}") else: ctx.log(f"Delivery preferences NOT saved for order {contact.source_order}") return saved --- run 10 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order fetch returned no data on page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Page {page_num} contained no orders; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.log(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results are truncated") ctx.log(f"Finished fetching orders: {len(orders)} total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipping order {order_id}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} from order {order_id}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.log(f"Customer sync complete: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form load step finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Carrier preferences form submitted") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}") return saved --- run 11 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders were not fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipping order {order_id}: existing CRM contact {existing['id']} is already up to date") skipped += 1 continue ctx.log(f"Updating CRM contact {existing['id']} from order {order_id}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: ctx.log(f"Creating CRM contact from order {order_id}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.log(f"Sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier saved delivery preference for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm delivery preference save for order {contact.source_order}") return saved --- run 12 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched {len(batch)} orders from page {page_num}") url = page.get("next") if url and len(orders) > 0: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order.get('id')}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"No changes needed for existing contact {existing['id']} (order {contact.source_order})") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated contact {existing['id']} (order {contact.source_order})") updated += 1 else: ctx.log(f"Failed to update contact {existing['id']} after retry (order {contact.source_order})") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created contact for order {contact.source_order}") created += 1 else: ctx.log(f"Failed to create contact for order {contact.source_order}") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences (window={window}) for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Preferences form wait finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Delivery preferences saved for order {contact.source_order}") else: ctx.log(f"Delivery preferences were not confirmed as saved for order {contact.source_order}") return saved --- run 13 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders were not fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.log(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.log(f"Skipped order {order.get('id')}: contact already handled in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.log(f"Skipped order {order.get('id')}: existing CRM contact {existing.get('id')} already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.log(f"Updated CRM contact {existing['id']} from order {order.get('id')}") else: skipped += 1 ctx.log(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.log(f"Created CRM contact from order {order.get('id')}") else: skipped += 1 ctx.log(f"Failed to create CRM contact from order {order.get('id')}") ctx.log(f"Sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier saved delivery preferences for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm delivery preferences for order {contact.source_order}") return saved --- run 14 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}), some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preference '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Delivery preference saved for order {contact.source_order}") else: ctx.log(f"Delivery preference not confirmed as saved for order {contact.source_order}") return saved --- run 15 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order fetch returned no data on page {page_num}; stopping") break batch = page.get("orders") or [] if not batch: ctx.log(f"Page {page_num} had no orders; pagination complete") break orders.extend(batch) ctx.log(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.log(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipping order {order_id}: existing CRM contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} from order {order_id}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences (window={window}) for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Delivery preferences saved for order {contact.source_order}") else: ctx.log(f"Delivery preferences not confirmed as saved for order {contact.source_order}") return saved --- run 16 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue ctx.log(f"Order {contact.source_order}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update of contact {existing['id']} failed, retrying") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update of contact {existing['id']} failed after retry") skipped += 1 else: ctx.log(f"Order {contact.source_order}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: failed to create CRM contact") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference for order {contact.source_order} to window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference not confirmed as saved for order {contact.source_order}") return saved --- run 17 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"No response for order page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched contact from order {contact.source_order} by phone, not email") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: existing CRM contact {existing.get('id')} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of contact {existing['id']} failed after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.log(f"Order {order_id}: failed to create CRM contact") skipped += 1 ctx.log(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for contact from order {contact.source_order} (window: {window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save button: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Preferences were not confirmed as saved: {exc}") if saved: ctx.log(f"Delivery preferences saved for contact from order {contact.source_order}") return saved --- run 18 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: if url: ctx.log(f"Reached MAX_PAGES={MAX_PAGES} limit; some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: no usable email; skipped") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: contact already handled in this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: existing CRM contact {existing['id']} is up to date; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.log(f"Order {order_id}: failed to create CRM contact; skipped") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Order {contact.source_order}: setting carrier delivery window to '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Order {contact.source_order}: preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Order {contact.source_order}: saved confirmation not seen: {exc}") if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved") else: ctx.log(f"Order {contact.source_order}: delivery preferences were not saved") return saved --- run 19 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"No response for orders page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.log(f"Fetched {len(batch)} orders from page {page_num}") url = page.get("next") if url: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) with more orders remaining; results are truncated") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched order {contact.source_order} to an existing contact by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipping order {order_id}: existing contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of contact {existing['id']} failed for order {order_id}; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated contact {existing['id']} from order {order_id}") updated += 1 else: ctx.log(f"Failed to update contact {existing['id']} from order {order_id}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created contact from order {order_id}") created += 1 else: ctx.log(f"Failed to create contact from order {order_id}") skipped += 1 ctx.log(f"CRM sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery window to {window} for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier saved delivery preferences for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm saved preferences for order {contact.source_order}") return saved --- run 20 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching orders created after {since}") for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num + 1} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num + 1} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES - 1: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Matched existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.log(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.log(f"Skipped order {order.get('id')}: duplicate customer in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.log(f"Skipped order {order.get('id')}: existing CRM contact already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.log(f"Updated CRM contact {existing['id']} from order {order.get('id')}") else: skipped += 1 ctx.log(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.log(f"Created CRM contact from order {order.get('id')}") else: skipped += 1 ctx.log(f"Failed to create CRM contact from order {order.get('id')}") ctx.log(f"Sync complete: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preference window '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier saved delivery preference for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm delivery preference for order {contact.source_order}") return saved --- run 21 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) > 0: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) with more pages remaining; results may be incomplete") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact for order {contact.source_order} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact for order {contact.source_order} by phone") return by_phone["results"][0] ctx.log(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Order {contact.source_order}: preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Order {contact.source_order}: could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Order {contact.source_order}: could not click save: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Order {contact.source_order}: save confirmation not seen: {exc}") if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved") else: ctx.log(f"Order {contact.source_order}: delivery preferences were not saved") return saved --- run 22 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"No response for order page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched {len(batch)} orders from page {page_num}") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order_id}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipping order {order_id}: existing CRM contact {existing['id']} already up to date") skipped += 1 continue ctx.log(f"Updating CRM contact {existing['id']} from order {order_id}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: ctx.log(f"Creating CRM contact from order {order_id}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order_id}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preference window '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier saved delivery preferences for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm saved preferences for order {contact.source_order}") return saved --- run 23 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); more orders may exist beyond this limit") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched order {contact.source_order} to existing contact by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipped order {order.get('id')}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipped order {order.get('id')}: existing contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.log(f"Failed to update contact {existing['id']} from order {contact.source_order}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created contact from order {contact.source_order}") created += 1 else: ctx.log(f"Failed to create contact from order {contact.source_order}") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Preferences form did not appear for order {contact.source_order}: {exc}") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Preferences not confirmed as saved for order {contact.source_order}: {exc}") if saved: ctx.log(f"Delivery preferences saved for order {contact.source_order}") return saved --- run 24 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be incomplete") ctx.log(f"Total orders fetched: {len(orders)}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {contact.source_order}; skipping") skipped += 1 ctx.log(f"Customer sync complete: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference (window={window}) for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.log(f"Carrier delivery preference saved: {saved} (order {contact.source_order})") return saved --- run 25 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES={MAX_PAGES} while paginating orders; results may be incomplete") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Order {contact.source_order}: matched existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] ctx.log(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update of contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update of contact {existing['id']} failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: failed to create CRM contact, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log(f"Order {contact.source_order}: preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log(f"Order {contact.source_order}: clicked save on preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Order {contact.source_order}: delivery preferences saved") else: ctx.log(f"Order {contact.source_order}: delivery preferences were not confirmed as saved") return saved --- run 26 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Matched existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order.get('id')}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Skipping order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.log("Carrier preferences form loaded") if not contextlib.suppress.__class__: pass with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.log( f"Carrier preference for order {contact.source_order} " + ("saved" if saved else "was not confirmed as saved") ) return saved --- run 27 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"No response for orders page {page_number}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Orders page {page_number} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched orders page {page_number}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: no usable email; skipped") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: contact already handled in this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing['id']} already up to date; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order_id}: created CRM contact") created += 1 else: ctx.log(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' (source order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save button: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Preferences were not confirmed as saved: {exc}") ctx.log(f"Carrier delivery preference saved: {saved}") return saved --- run 28 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}), some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order.get('id')}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order.get('id')}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order.get('id')}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order.get('id')}: created CRM contact") created += 1 else: ctx.log(f"Order {order.get('id')}: create failed, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference not confirmed for order {contact.source_order}") return saved --- run 29 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be incomplete") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.log(f"Carrier preferences for order {contact.source_order} saved={saved}") return saved --- run 30 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be incomplete") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order.get('id')}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order.get('id')}: existing CRM contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order.get('id')}: update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order.get('id')}: update of CRM contact {existing['id']} failed after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order.get('id')}: created new CRM contact") created += 1 else: ctx.log(f"Order {order.get('id')}: failed to create CRM contact") skipped += 1 ctx.log(f"Sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference for order {contact.source_order} to window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form load step finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Carrier preferences form submitted") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference NOT confirmed as saved for order {contact.source_order}") return saved --- run 31 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") ctx.log(f"Total orders fetched: {len(orders)}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Matched existing CRM contact by email (source order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone (source order {contact.source_order})") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order.get('id')}: existing contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order.get('id')}: update of contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order.get('id')}: update of contact {existing['id']} failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order.get('id')}: created new CRM contact") created += 1 else: ctx.log(f"Order {order.get('id')}: failed to create CRM contact, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(step: str, fn) -> bool: """Run one browser step. Log and swallow any failure, returning whether it succeeded.""" try: fn() return True except Exception as exc: ctx.log(f"Carrier form step '{step}' failed: {exc!r}") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences (window={window}) for source order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") if not _attempt("wait for form", lambda: client.wait_for("#preferences-form", timeout=30)): ctx.log("Preferences form did not appear; continuing with field entry anyway") _attempt("fill email", lambda: client.fill("#email", contact.email)) _attempt("fill name", lambda: client.fill("#name", full_name)) if contact.address: _attempt("fill city", lambda: client.fill("#city", contact.address.get("city", ""))) _attempt("click save", lambda: client.click("#save")) saved = _attempt("wait for saved confirmation", lambda: client.wait_for(".preferences-saved", timeout=60)) if saved: ctx.log(f"Delivery preferences saved for source order {contact.source_order}") else: ctx.log(f"Delivery preferences NOT confirmed as saved for source order {contact.source_order}") return saved --- run 32 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be incomplete") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order.get('id')}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order.get('id')}: CRM contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order.get('id')}, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") if not contextlib.suppress: pass with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}") return saved --- run 33 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.log(f"Requesting order page {page_num}") page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Order page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES={MAX_PAGES} limit; some orders may not have been fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.log(f"No existing CRM contact found (order {contact.source_order})") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: existing contact already up to date, skipping") skipped += 1 continue ctx.log(f"Order {contact.source_order}: updating existing contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.log(f"Order {contact.source_order}: contact {existing['id']} updated") else: skipped += 1 ctx.log(f"Order {contact.source_order}: update failed after retry, skipping") else: ctx.log(f"Order {contact.source_order}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.log(f"Order {contact.source_order}: contact created") else: skipped += 1 ctx.log(f"Order {contact.source_order}: create failed, skipping") ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preference window '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Save clicked") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Delivery preferences saved for order {contact.source_order}") else: ctx.log(f"Delivery preferences not confirmed as saved for order {contact.source_order}") return saved --- run 34 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES={MAX_PAGES} while fetching orders; results may be incomplete") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.log(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {order.get('id')}: customer already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"No changes for existing contact {existing['id']} (order {order.get('id')})") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update failed for contact {existing['id']}; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated contact {existing['id']} (order {order.get('id')})") updated += 1 else: ctx.log(f"Update failed for contact {existing['id']} after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created contact from order {order.get('id')}") created += 1 else: ctx.log(f"Create failed for order {order.get('id')}; skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}") return saved --- run 35 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"No response for order page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched {len(batch)} orders from page {page_num}") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: no usable email; skipped") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: contact already handled in this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing['id']} already up to date; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of CRM contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order_id}: created CRM contact") created += 1 else: ctx.log(f"Order {order_id}: failed to create CRM contact; skipped") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preferences (window={window}) for contact from order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log("Carrier confirmed delivery preferences saved") else: ctx.log("Carrier did not confirm delivery preferences were saved") return saved --- run 36 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be incomplete") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order.get('id')}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order.get('id')}: CRM contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {order.get('id')}; skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.log(f"Preferences form did not appear for order {contact.source_order}: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.log(f"Could not fill email field for order {contact.source_order}: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.log(f"Could not fill name field for order {contact.source_order}: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.log(f"Could not fill city field for order {contact.source_order}: {exc}") try: client.click("#save") except Exception as exc: ctx.log(f"Could not click save for order {contact.source_order}: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.log(f"Save confirmation not seen for order {contact.source_order}: {exc}") if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference NOT saved for order {contact.source_order}") return saved --- run 37 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.log(f"Fetching orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order fetch returned no data on page {page_num}; stopping") break batch = page.get("orders") or [] if not batch: ctx.log(f"Page {page_num} contained no orders; stopping") break orders.extend(batch) ctx.log(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders were not fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log("Starting new-customer sync") orders = _fetch_orders(client, since) if not orders: ctx.log("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.log(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.log(f"Order {order_id}: no usable email; skipped") skipped += 1 continue if contact.email in seen: ctx.log(f"Order {order_id}: duplicate customer in this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {order_id}: CRM contact {existing.get('id')} already up to date; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {order_id}: update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {order_id}: update of contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.log(f"Order {order_id}: failed to create CRM contact; skipped") skipped += 1 ctx.log(f"Sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.log("Carrier preferences form loaded") if not _form_loaded_flag(client): ctx.log("Carrier preferences form did not load within timeout; continuing") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier confirmed preferences saved for order {contact.source_order}") else: ctx.log(f"Carrier did not confirm preferences saved for order {contact.source_order}") return saved --- run 38 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES={MAX_PAGES} while paginating orders; results may be incomplete") ctx.log(f"Total orders fetched: {len(orders)}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Matched existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference not confirmed as saved for order {contact.source_order}") return saved --- run 39 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.log(f"Fetched {len(batch)} orders from page {page_num}") url = page.get("next") if url and len(orders) > 0: ctx.log(f"Reached MAX_PAGES={MAX_PAGES} before the last page; some orders may be missing") ctx.log(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Matched existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.log(f"Skipping order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.log(f"Skipping order {contact.source_order}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"CRM contact {existing['id']} already up to date; skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.log(f"Failed to update CRM contact {existing['id']} after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.log(f"Failed to create CRM contact from order {contact.source_order}; skipping") skipped += 1 ctx.log(f"Sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting delivery preference '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Preferences form wait finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Submitted delivery preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Delivery preferences saved for order {contact.source_order}") else: ctx.log(f"Delivery preferences were not confirmed as saved for order {contact.source_order}") return saved --- run 40 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.log(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.log(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.log(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.log(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.log(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.log(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be incomplete") ctx.log(f"Total orders fetched: {len(orders)}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.log(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.log(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.log(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.log(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.log("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.log(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.log(f"Order {contact.source_order}: CRM contact {existing['id']} already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.log(f"Order {contact.source_order}: update of contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.log(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.log(f"Order {contact.source_order}: update of contact {existing['id']} failed after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.log(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.log(f"Order {contact.source_order}: failed to create CRM contact") skipped += 1 ctx.log(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.log(f"Setting carrier delivery preference (window={window}) for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.log("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.log("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.log(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.log(f"Carrier delivery preference not confirmed as saved for order {contact.source_order}") return saved Claude Haiku 5.5, ctx.narrate (contact sync) ============================================ --- run 1 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num + 1} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num + 1} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_num + 1} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate("Matched an existing CRM contact by phone number rather than email.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Processing {len(orders)} orders for CRM sync.") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipped order {order_id}: contact already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: existing CRM contact already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order_id}.") updated += 1 else: ctx.narrate(f"Failed to update CRM contact {existing['id']} from order {order_id}.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.narrate(f"Failed to create CRM contact from order {order_id}.") skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for contact {contact.email}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm delivery preferences were saved.") return saved --- run 2 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting orders page {page_num}.") page = client.get_json(url) if not page: ctx.narrate(f"No response for orders page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Orders page {page_num} is empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Received {len(batch)} orders on page {page_num} ({len(orders)} total so far).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate(f"Matched an existing CRM contact by phone for order {contact.source_order}.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Syncing contacts from {len(orders)} orders.") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: contact already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Contact for order {order.get('id')} is already up to date.") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} from order {order.get('id')}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Creating a CRM contact from order {order.get('id')}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order.get('id')}.") created += 1 else: ctx.narrate(f"Could not create a CRM contact from order {order.get('id')}; skipping.") skipped += 1 ctx.narrate(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for delivery window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Waited for the carrier preferences form.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Filled in the carrier preferences form.") with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted the carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 3 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order request for page {page_num} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total).") url = page.get("next") if url and len(orders) > 0: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Finished fetching orders: {len(orders)} found.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync for customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for index, order in enumerate(orders, start=1): contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {index}: no usable email address; skipping.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {index}: customer already handled in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {index}: existing CRM contact is already up to date; skipping.") skipped += 1 continue ctx.narrate(f"Order {index}: updating existing CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {index}: update failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Order {index}: contact {existing['id']} updated.") else: skipped += 1 ctx.narrate(f"Order {index}: update failed after retry; skipping.") else: ctx.narrate(f"Order {index}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Order {index}: new contact created.") else: skipped += 1 ctx.narrate(f"Order {index}: contact creation failed; skipping.") ctx.narrate( f"CRM sync complete: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting carrier preferences form.") with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 4 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_number} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_number} is empty; pagination complete") break orders.extend(batch) ctx.narrate(f"Fetched order page {page_number} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_number == MAX_PAGES: ctx.narrate(f"Reached the {MAX_PAGES}-page limit; some orders may not have been fetched") ctx.narrate(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to CRM") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipped order {order.get('id')}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipped order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue ctx.narrate(f"Updating existing CRM contact {existing['id']} from order {order.get('id')}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 else: ctx.narrate(f"Update for CRM contact {existing['id']} failed after retry; skipping") skipped += 1 else: ctx.narrate(f"Creating new CRM contact from order {order.get('id')}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 else: ctx.narrate(f"Creating CRM contact from order {order.get('id')} failed; skipping") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") form_ready = True with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) form_ready = True if not form_ready: ctx.narrate("Carrier preferences form did not load in time") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences were saved") else: ctx.narrate("Carrier did not confirm delivery preferences were saved") return saved --- run 5 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.narrate(f"Fetching order page {page_num + 1}.") page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num + 1} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num + 1} is empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Loaded {len(batch)} orders from page {page_num + 1} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders created since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Processing {len(orders)} orders.") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order.get('id')}: existing CRM contact is already up to date.") skipped += 1 continue ctx.narrate(f"Order {order.get('id')}: updating existing CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Order {order.get('id')}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact for order {order.get('id')}.") created += 1 else: ctx.narrate(f"Could not create CRM contact for order {order.get('id')}; skipping.") skipped += 1 ctx.narrate(f"Sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier confirmed delivery preference for order {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm delivery preference for order {contact.source_order}.") return saved --- run 6 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Fetching order page {page_num} since {since}") page = client.get_json(url) if not page: ctx.narrate(f"No response for order page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; pagination complete") break orders.extend(batch) ctx.narrate(f"Retrieved {len(batch)} orders on page {page_num} ({len(orders)} total)") url = page.get("next") else: ctx.narrate(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: skipped (duplicate customer in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing['id']} already up to date; skipped") skipped += 1 continue ctx.narrate(f"Order {order_id}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {order_id}: update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.narrate(f"Order {order_id}: update of contact {existing['id']} failed after retry; skipped") skipped += 1 else: ctx.narrate(f"Order {order_id}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created CRM contact") created += 1 else: ctx.narrate(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting delivery preferences (window: {window}) with carrier") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences saved") else: ctx.narrate("Carrier did not confirm delivery preferences were saved") return saved --- run 7 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; stopping pagination.") break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_num} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Finished fetching orders: {len(orders)} total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting CRM sync for customers since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order_id}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing['id']} already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order_id}.") updated += 1 else: ctx.narrate(f"Failed to update CRM contact {existing['id']} from order {order_id}.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.narrate(f"Failed to create CRM contact from order {order_id}.") skipped += 1 ctx.narrate( f"CRM sync complete: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm delivery preferences were saved.") return saved --- run 8 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order fetch returned no data on page {page_num}; stopping.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the {MAX_PAGES}-page limit; some orders may not have been fetched.") ctx.narrate(f"Finished fetching orders: {len(orders)} total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order_id}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing['id']} is already up to date.") skipped += 1 continue ctx.narrate(f"Order {order_id}: updating CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Order {order_id}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact for order {order_id}.") created += 1 else: ctx.narrate(f"Could not create CRM contact for order {order_id}; skipping.") skipped += 1 ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form; waiting for confirmation.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 9 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting order page {page_num}.") page = client.get_json(url) if not page: ctx.narrate(f"No response for order page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Collected {len(batch)} orders from page {page_num} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the {MAX_PAGES}-page limit; some orders may not have been fetched.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: ctx.narrate("No CRM match by email; trying lookup by phone.") by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Processing {len(orders)} orders.") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"CRM contact {existing['id']} is already up to date; skipping.") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} with missing details.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Creating new CRM contact for order {order.get('id')}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact for order {order.get('id')}.") created += 1 else: ctx.narrate(f"Could not create CRM contact for order {order.get('id')}; skipping.") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for delivery window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.narrate("Waiting for the preferences form to load.") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Filling in the carrier preferences form.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting carrier preferences.") with contextlib.suppress(Exception): client.click("#save") saved = False ctx.narrate("Waiting for the carrier to confirm the preferences were saved.") with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 10 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order fetch stopped on page {page_num}: no response.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num} with {len(batch)} orders.") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order.get('id')}: no usable email.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipped order {order.get('id')}: contact already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipped order {order.get('id')}: existing CRM contact is already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") updated += 1 else: ctx.narrate(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order.get('id')}.") created += 1 else: ctx.narrate(f"Failed to create CRM contact from order {order.get('id')}.") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier saved delivery preference for order {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm saving delivery preference for order {contact.source_order}.") return saved --- run 11 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched order page {page_num} with {len(batch)} orders.") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id} skipped: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id} skipped: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id} skipped: CRM contact {existing.get('id')} is already up to date.") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} from order {order_id}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']} after retry; skipping.") skipped += 1 else: ctx.narrate(f"Creating CRM contact from order {order_id}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.narrate(f"Could not create CRM contact from order {order_id}; skipping.") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 12 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_number} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_number} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_number}.") url = page.get("next") else: ctx.narrate(f"Reached the {MAX_PAGES}-page limit; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting CRM sync of new customers.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for index, order in enumerate(orders, start=1): contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {index}/{len(orders)}: no usable email; skipped.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {index}/{len(orders)}: customer already handled in this run; skipped.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {index}/{len(orders)}: CRM contact already up to date; skipped.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {index}/{len(orders)}: update failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Order {index}/{len(orders)}: updated existing CRM contact.") updated += 1 else: ctx.narrate(f"Order {index}/{len(orders)}: update failed after retry; skipped.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {index}/{len(orders)}: created new CRM contact.") created += 1 else: ctx.narrate(f"Order {index}/{len(orders)}: create failed; skipped.") skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for delivery window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Preferences form loaded.") if not contextlib.suppress: # placeholder removed below pass with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Clicked save on the preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm that delivery preferences were saved.") return saved --- run 13 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting order page {page_number}.") page = client.get_json(url) if not page: ctx.narrate(f"No response for order page {page_number}; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_number} is empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Collected {len(batch)} orders from page {page_number} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate(f"Found existing CRM contact by email for order {contact.source_order}.") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate(f"Found existing CRM contact by phone for order {contact.source_order}.") return by_phone["results"][0] ctx.narrate(f"No existing CRM contact found for order {contact.source_order}.") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipping order {order.get('id')}: existing contact has no new data.") skipped += 1 continue ctx.narrate(f"Updating existing CRM contact {existing['id']} from order {order.get('id')}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Creating CRM contact from order {order.get('id')}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order.get('id')}.") created += 1 else: ctx.narrate(f"Could not create CRM contact from order {order.get('id')}; skipping.") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier confirmed delivery preferences saved for order {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm a saved preference for order {contact.source_order}.") return saved --- run 14 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Fetching order page {page_num}") page = client.get_json(url) if not page: ctx.narrate(f"No response for order page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_num} ({len(orders)} total)") url = page.get("next") else: ctx.narrate(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: no usable email; skipped") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: duplicate customer in this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing['id']} already up to date; skipped") skipped += 1 continue ctx.narrate(f"Order {order_id}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {order_id}: update of contact {existing['id']} failed; retrying") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.narrate(f"Order {order_id}: update of contact {existing['id']} failed after retry; skipped") skipped += 1 else: ctx.narrate(f"Order {order_id}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created CRM contact") created += 1 else: ctx.narrate(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting delivery preferences (window: {window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.narrate("Preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Clicked save on preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.narrate("Delivery preferences saved" if saved else "Delivery preferences were not confirmed as saved") return saved --- run 15 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_number} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_number} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched order page {page_number} with {len(batch)} orders ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Finished fetching orders: {len(orders)} total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to the CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipped order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipped order {order.get('id')}: CRM contact {existing['id']} already up to date.") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} from order {order.get('id')}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Creating CRM contact from order {order.get('id')}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order.get('id')}.") created += 1 else: ctx.narrate(f"Could not create CRM contact from order {order.get('id')}; skipping.") skipped += 1 ctx.narrate(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier saved delivery preference for order {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm the delivery preference for order {contact.source_order}.") return saved --- run 16 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting order page {page_num}.") page = client.get_json(url) if not page: ctx.narrate(f"No response for order page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Page {page_num} returned {len(batch)} orders ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: ctx.narrate(f"No CRM match by email for order {contact.source_order}; trying phone.") by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"CRM contact {existing['id']} is already up to date; skipping.") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} with missing details.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Creating a CRM contact for order {contact.source_order}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact for order {contact.source_order}.") created += 1 else: ctx.narrate(f"Could not create CRM contact for order {contact.source_order}; skipping.") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.narrate("Waiting for the carrier preferences form to load.") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Filling in the carrier preferences form.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting the carrier preferences form.") with contextlib.suppress(Exception): client.click("#save") saved = False ctx.narrate("Waiting for the carrier to confirm the save.") with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier preferences saved for order {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm the save for order {contact.source_order}.") return saved --- run 17 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order fetch returned no data on page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total so far).") url = page.get("next") if url and len(orders) > 0: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.narrate(f"Order {order.get('id')}: skipped, no usable email address.") continue if contact.email in seen: skipped += 1 ctx.narrate(f"Order {order.get('id')}: skipped, customer already handled in this run.") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.narrate(f"Order {order.get('id')}: CRM contact {existing['id']} already up to date.") continue ctx.narrate(f"Order {order.get('id')}: updating CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Updated CRM contact {existing['id']}.") else: skipped += 1 ctx.narrate(f"Could not update CRM contact {existing['id']}; skipped.") else: ctx.narrate(f"Order {order.get('id')}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created CRM contact for order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Could not create CRM contact for order {order.get('id')}; skipped.") ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier confirmed delivery preferences saved for order {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm a save for order {contact.source_order}.") return saved --- run 18 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"No response for order page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total).") url = page.get("next") if url and page_num == MAX_PAGES: ctx.narrate(f"Reached the {MAX_PAGES}-page limit; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting new-customer sync to the CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.narrate(f"Skipped order {order.get('id')}: no usable email address.") continue if contact.email in seen: skipped += 1 ctx.narrate(f"Skipped order {order.get('id')}: customer already handled in this run.") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.narrate(f"Skipped order {order.get('id')}: CRM contact already up to date.") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created CRM contact from order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Could not create CRM contact from order {order.get('id')}; skipping.") ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 19 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_number} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_number} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched order page {page_number} with {len(batch)} orders.") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to the CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: skipped += 1 ctx.narrate(f"Skipped order {order_id}: no usable email address.") continue if contact.email in seen: skipped += 1 ctx.narrate(f"Skipped order {order_id}: customer already handled in this run.") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.narrate(f"Skipped order {order_id}: CRM contact {existing['id']} is already up to date.") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Updated CRM contact {existing['id']} from order {order_id}.") else: skipped += 1 ctx.narrate(f"Could not update CRM contact {existing['id']} from order {order_id}.") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created CRM contact from order {order_id}.") else: skipped += 1 ctx.narrate(f"Could not create CRM contact from order {order_id}.") ctx.narrate(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for contact from order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier delivery preference saved for order {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm the delivery preference for order {contact.source_order}.") return saved --- run 20 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting orders page {page_num}") page = client.get_json(url) if not page: ctx.narrate(f"No response for orders page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Orders page {page_num} is empty; stopping pagination") break orders.extend(batch) url = page.get("next") else: ctx.narrate(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") ctx.narrate(f"Fetched {len(orders)} orders") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"CRM contact {existing.get('id')} already up to date; skipping") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} from order {order.get('id')}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Updated CRM contact {existing['id']}") else: skipped += 1 ctx.narrate(f"Failed to update CRM contact {existing['id']}; skipping") else: ctx.narrate(f"Creating CRM contact from order {order.get('id')}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created CRM contact from order {order.get('id')}") else: skipped += 1 ctx.narrate(f"Failed to create CRM contact from order {order.get('id')}; skipping") ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for contact from order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.narrate(f"Carrier delivery preference not confirmed as saved for order {contact.source_order}") return saved --- run 21 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting orders page {page_num}.") page = client.get_json(url) if not page: ctx.narrate(f"No response for orders page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Orders page {page_num} is empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Received {len(batch)} orders on page {page_num} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: ctx.narrate("No CRM match by email; trying lookup by phone.") by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Processing {len(orders)} orders.") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: no usable email; skipping.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: customer already handled in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing['id']} is already up to date; skipping.") skipped += 1 continue ctx.narrate(f"Order {order_id}: updating CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Order {order_id}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact for order {order_id}.") created += 1 else: ctx.narrate(f"Could not create CRM contact for order {order_id}; skipping.") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for delivery window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.narrate("Waiting for the carrier preferences form to load.") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Filling in carrier preferences form fields.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting carrier preferences form.") with contextlib.suppress(Exception): client.click("#save") saved = False ctx.narrate("Waiting for carrier to confirm preferences were saved.") with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm delivery preferences were saved.") return saved --- run 22 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order fetch returned no data on page {page_number}; stopping.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_number} with {len(batch)} orders.") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting CRM sync for new shop customers.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order.get('id')}: CRM contact {existing.get('id')} is already up to date.") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} from order {order.get('id')}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Updated CRM contact {existing['id']}.") else: skipped += 1 ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") else: ctx.narrate(f"Creating CRM contact from order {order.get('id')}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created CRM contact from order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Could not create CRM contact from order {order.get('id')}; skipping.") ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier delivery preferences saved.") else: ctx.narrate("Carrier did not confirm that delivery preferences were saved.") return saved --- run 23 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; pagination complete") break orders.extend(batch) ctx.narrate(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.narrate(f"Reached MAX_PAGES limit ({MAX_PAGES}); some orders may not have been fetched") ctx.narrate(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate(f"Matched order {contact.source_order} to an existing CRM contact by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Syncing {len(orders)} orders into the CRM") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipped order {order.get('id')}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipped order {order.get('id')}: CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for order {order.get('id')} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact for order {order.get('id')}") updated += 1 else: ctx.narrate(f"Failed to update CRM contact for order {order.get('id')}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact for order {order.get('id')}") created += 1 else: ctx.narrate(f"Failed to create CRM contact for order {order.get('id')}") skipped += 1 ctx.narrate(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery window to {window} for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier delivery preferences saved for order {contact.source_order}") else: ctx.narrate(f"Carrier delivery preferences were not confirmed as saved for order {contact.source_order}") return saved --- run 24 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_number} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_number} with {len(batch)} order(s).") url = page.get("next") else: if url: ctx.narrate(f"Reached the {MAX_PAGES}-page limit; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} order(s) in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to the CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order_id}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing['id']} is already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order_id}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']} from order {order_id}.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.narrate(f"Could not create CRM contact from order {order_id}.") skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier delivery preferences saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 25 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_number} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_number} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_number} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Finished fetching orders: {len(orders)} total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for index, order in enumerate(orders, start=1): contact = _to_contact(order) if contact is None: skipped += 1 ctx.narrate(f"Order {index}/{len(orders)}: skipped, no usable email address.") continue if contact.email in seen: skipped += 1 ctx.narrate(f"Order {index}/{len(orders)}: skipped, customer already handled in this run.") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.narrate(f"Order {index}/{len(orders)}: skipped, CRM contact already up to date.") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {index}/{len(orders)}: CRM update failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Order {index}/{len(orders)}: updated existing CRM contact.") else: skipped += 1 ctx.narrate(f"Order {index}/{len(orders)}: CRM update failed after retry; skipped.") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Order {index}/{len(orders)}: created new CRM contact.") else: skipped += 1 ctx.narrate(f"Order {index}/{len(orders)}: CRM create failed; skipped.") ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm delivery preferences were saved.") return saved --- run 26 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_number} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_number} with {len(batch)} orders.") url = page.get("next") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order_id}: contact already processed in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: existing CRM contact {existing['id']} is already up to date.") skipped += 1 continue ctx.narrate(f"Order {order_id}: updating CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Order {order_id}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact for order {order_id}.") created += 1 else: ctx.narrate(f"Could not create CRM contact for order {order_id}; skipping.") skipped += 1 ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Waited for the carrier preferences form to load.") with contextlib.suppress(Exception): client.fill("#email", contact.email) ctx.narrate("Filled in the contact email on the carrier form.") with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.narrate("Filled in the contact name on the carrier form.") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Filled in the city on the carrier form.") with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted the carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 27 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num} with {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched") ctx.narrate(f"Finished fetching orders: {len(orders)} total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to CRM") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipped order {order.get('id')}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipped order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.narrate(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.narrate(f"Failed to create CRM contact from order {order.get('id')}") skipped += 1 ctx.narrate(f"CRM sync complete: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form; waiting for confirmation") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences were saved") else: ctx.narrate("Carrier did not confirm delivery preferences were saved") return saved --- run 28 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_num} (running total: {len(orders)}).") url = page.get("next") if url and len(orders) > 0: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Finished fetching orders: {len(orders)} total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate("Matched an existing CRM contact by phone number rather than email.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Syncing contacts from {len(orders)} orders.") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.narrate(f"Skipped order {order.get('id')}: no usable email address.") continue if contact.email in seen: skipped += 1 ctx.narrate(f"Skipped order {order.get('id')}: contact already handled in this run.") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.narrate(f"Order {order.get('id')}: existing CRM contact already up to date.") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Could not update CRM contact {existing['id']} after retry; skipped.") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created CRM contact from order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Could not create CRM contact from order {order.get('id')}; skipped.") ctx.narrate(f"CRM sync complete: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for delivery window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting carrier delivery preferences.") with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the preferences were saved.") return saved --- run 29 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.narrate(f"Fetching shop orders created after {since}.") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order fetch stopped on page {page_num}: no response.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipped order {order_id}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipped order {order_id}: CRM contact {existing['id']} is already up to date.") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} from order {order_id}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']} after retry.") skipped += 1 else: ctx.narrate(f"Creating CRM contact from order {order_id}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.narrate(f"Could not create CRM contact from order {order_id}.") skipped += 1 ctx.narrate(f"Sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting carrier preferences.") with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier preferences saved.") else: ctx.narrate("Carrier preferences were not confirmed as saved.") return saved --- run 30 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched order page {page_num} with {len(batch)} orders.") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not be fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.narrate(f"Skipped order {order.get('id')}: no usable email address.") continue if contact.email in seen: skipped += 1 ctx.narrate(f"Skipped order {order.get('id')}: contact already handled in this run.") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.narrate(f"Skipped order {order.get('id')}: existing CRM contact already up to date.") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}.") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created CRM contact from order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Failed to create CRM contact from order {order.get('id')}.") ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 31 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_num} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order.get('id')}: CRM contact {existing['id']} is already up to date.") skipped += 1 continue ctx.narrate(f"Order {order.get('id')}: updating CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']}; skipping.") skipped += 1 else: ctx.narrate(f"Order {order.get('id')}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact for order {order.get('id')}.") created += 1 else: ctx.narrate(f"Could not create CRM contact for order {order.get('id')}; skipping.") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 32 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting order page {page_num}.") page = client.get_json(url) if not page: ctx.narrate(f"No response for order page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Page {page_num} returned {len(batch)} orders ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: no usable email; skipping.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: customer already handled in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing.get('id')} is already up to date; skipping.") skipped += 1 continue ctx.narrate(f"Order {order_id}: updating CRM contact {existing.get('id')}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {order_id}: update of contact {existing.get('id')} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Order {order_id}: updated CRM contact {existing.get('id')}.") updated += 1 else: ctx.narrate(f"Order {order_id}: could not update CRM contact {existing.get('id')}; skipping.") skipped += 1 else: ctx.narrate(f"Order {order_id}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created CRM contact.") created += 1 else: ctx.narrate(f"Order {order_id}: could not create CRM contact; skipping.") skipped += 1 ctx.narrate(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 33 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_num} ({len(orders)} total).") url = page.get("next") else: ctx.narrate(f"Reached the {MAX_PAGES}-page limit; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting CRM sync of new shop customers.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order.get('id')}: existing CRM contact {existing['id']} is already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']} after retry; skipping.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order.get('id')}.") created += 1 else: ctx.narrate(f"Could not create CRM contact from order {order.get('id')}; skipping.") skipped += 1 ctx.narrate(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for contact from order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier delivery preferences saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 34 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; no more orders.") break orders.extend(batch) ctx.narrate(f"Fetched {len(batch)} orders from page {page_num} ({len(orders)} total).") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Finished fetching orders: {len(orders)} total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) ctx.narrate(f"Processing {len(orders)} orders.") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: no usable email; skipped.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: contact already handled in this run; skipped.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: matching CRM contact {existing.get('id')} is already up to date; skipped.") skipped += 1 continue ctx.narrate(f"Order {order_id}: updating CRM contact {existing.get('id')} with missing fields.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {order_id}: update of contact {existing.get('id')} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Order {order_id}: updated CRM contact {existing.get('id')}.") updated += 1 else: ctx.narrate(f"Order {order_id}: update of contact {existing.get('id')} failed after retry; skipped.") skipped += 1 else: ctx.narrate(f"Order {order_id}: no matching CRM contact; creating one.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: created new CRM contact.") created += 1 else: ctx.narrate(f"Order {order_id}: failed to create CRM contact; skipped.") skipped += 1 ctx.narrate(f"Customer sync complete: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for contact {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.narrate("Waiting for the carrier preferences form to load.") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Filling in the carrier preferences form.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting carrier preferences.") with contextlib.suppress(Exception): client.click("#save") saved = False ctx.narrate("Waiting for the carrier to confirm the preferences were saved.") with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier delivery preference saved for contact {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm a saved preference for contact {contact.source_order}.") return saved --- run 35 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_no in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_no} returned no data; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_no} was empty; pagination complete.") break orders.extend(batch) ctx.narrate(f"Fetched order page {page_no} with {len(batch)} orders.") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate("Matched an existing CRM contact by phone number rather than email.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting customer sync to the CRM.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipped order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipped order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipped order {order.get('id')}: existing CRM contact already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") updated += 1 else: ctx.narrate(f"Could not update CRM contact {existing['id']} after retry.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order.get('id')}.") created += 1 else: ctx.narrate(f"Could not create CRM contact from order {order.get('id')}.") skipped += 1 ctx.narrate( f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.narrate("Opened the carrier preferences form.") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.narrate("Preferences form is ready.") for selector, value in (("#email", contact.email), ("#name", full_name)): try: client.fill(selector, value) except Exception: ctx.narrate(f"Could not fill field {selector}; continuing.") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception: ctx.narrate("Could not fill the city field; continuing.") try: client.click("#save") ctx.narrate("Clicked save on the carrier preferences form.") except Exception: ctx.narrate("Could not click save on the carrier preferences form.") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True ctx.narrate("Carrier confirmed the delivery preferences were saved.") except Exception: ctx.narrate("No save confirmation from the carrier; preferences may not have been saved.") return saved --- run 36 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting orders page {page_num}.") page = client.get_json(url) if not page: ctx.narrate(f"No response for orders page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Orders page {page_num} is empty; no more orders.") break orders.extend(batch) ctx.narrate(f"Got {len(batch)} orders on page {page_num} ({len(orders)} total so far).") url = page.get("next") else: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate(f"Matched an existing CRM contact by email (order {contact.source_order}).") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate(f"Matched an existing CRM contact by phone (order {contact.source_order}).") return by_phone["results"][0] ctx.narrate(f"No existing CRM contact found for order {contact.source_order}.") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Existing contact for order {order.get('id')} is already up to date.") skipped += 1 continue ctx.narrate(f"Updating existing contact for order {order.get('id')}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for order {order.get('id')} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.narrate(f"Updated contact for order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Update for order {order.get('id')} failed after retry; skipping.") else: ctx.narrate(f"Creating new CRM contact for order {order.get('id')}.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.narrate(f"Created contact for order {order.get('id')}.") else: skipped += 1 ctx.narrate(f"Failed to create contact for order {order.get('id')}; skipping.") ctx.narrate( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate(f"Carrier confirmed delivery preferences saved for order {contact.source_order}.") else: ctx.narrate(f"Carrier did not confirm saved preferences for order {contact.source_order}.") return saved --- run 37 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created since {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.narrate(f"Requesting order page {page_num}.") page = client.get_json(url) if not page: ctx.narrate(f"No response for order page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Order page {page_num} is empty; no more orders.") break orders.extend(batch) ctx.narrate(f"Received {len(batch)} orders on page {page_num} ({len(orders)} total so far).") url = page.get("next") else: ctx.narrate(f"Reached the {MAX_PAGES}-page limit; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate("Starting CRM sync of new shop customers.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for index, order in enumerate(orders, start=1): contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {index}/{len(orders)}: no usable email; skipping.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {index}/{len(orders)}: customer already handled in this run; skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {index}/{len(orders)}: CRM record is already up to date; skipping.") skipped += 1 continue ctx.narrate(f"Order {index}/{len(orders)}: updating existing CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated contact {existing['id']}.") updated += 1 else: ctx.narrate(f"Update for contact {existing['id']} failed after retry; skipping.") skipped += 1 else: ctx.narrate(f"Order {index}/{len(orders)}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate("Created new CRM contact.") created += 1 else: ctx.narrate(f"Creating CRM contact for order {index}/{len(orders)} failed; skipping.") skipped += 1 ctx.narrate(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting carrier preferences form.") with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier confirmed the delivery preferences were saved.") else: ctx.narrate("Carrier did not confirm the delivery preferences were saved.") return saved --- run 38 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order fetch returned no data on page {page_num}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total).") url = page.get("next") if url and len(orders) > 0: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; more orders may exist beyond this run.") ctx.narrate(f"Order fetch complete: {len(orders)} orders found.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.narrate(f"Order {order_id}: no usable email address; skipped.") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order_id}: customer already handled in this run; skipped.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order_id}: CRM contact {existing['id']} already up to date; skipped.") skipped += 1 continue ctx.narrate(f"Order {order_id}: updating CRM contact {existing['id']}.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {order_id}: update of contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Order {order_id}: contact {existing['id']} updated.") updated += 1 else: ctx.narrate(f"Order {order_id}: update of contact {existing['id']} failed after retry; skipped.") skipped += 1 else: ctx.narrate(f"Order {order_id}: creating new CRM contact.") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order_id}: new CRM contact created.") created += 1 else: ctx.narrate(f"Order {order_id}: creating CRM contact failed; skipped.") skipped += 1 ctx.narrate( f"Customer sync complete: {created} created, {updated} updated, {skipped} skipped." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.narrate("Carrier preferences form submitted.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier delivery preferences saved.") else: ctx.narrate("Carrier delivery preferences were not confirmed as saved.") return saved --- run 39 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_number in range(MAX_PAGES): if not url: break ctx.narrate(f"Requesting orders page {page_number + 1}") page = client.get_json(url) if not page: ctx.narrate(f"No response for orders page {page_number + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.narrate(f"Orders page {page_number + 1} is empty; stopping pagination") break orders.extend(batch) ctx.narrate(f"Collected {len(batch)} orders from page {page_number + 1} ({len(orders)} total)") url = page.get("next") if url and len(orders) and page_number == MAX_PAGES - 1: ctx.narrate(f"Reached MAX_PAGES limit ({MAX_PAGES}); some orders may not have been fetched") ctx.narrate(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.narrate(f"Matched existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.narrate(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.narrate(f"Skipping order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.narrate(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Skipping order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue ctx.narrate(f"Updating CRM contact {existing['id']} from order {order.get('id')}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.narrate(f"Failed to update CRM contact {existing['id']} after retry; skipping") skipped += 1 else: ctx.narrate(f"Creating CRM contact from order {order.get('id')}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.narrate(f"Failed to create CRM contact from order {order.get('id')}; skipping") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Opening carrier preferences form for window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.narrate("Waiting for carrier preferences form to load") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.narrate("Filling in carrier preferences form") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.narrate("Submitting carrier preferences form") with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier delivery preferences saved") else: ctx.narrate("Carrier delivery preferences were not confirmed as saved") return saved --- run 40 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.narrate(f"Order {order.get('id')}: no usable email, skipping.") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.narrate(f"Fetching shop orders created after {since}.") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.narrate(f"Order page {page_num} returned no data, stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.narrate(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total).") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.narrate(f"Reached the page limit of {MAX_PAGES}; some orders may not have been fetched.") ctx.narrate(f"Fetched {len(orders)} orders in total.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.narrate("Matched an existing CRM contact by phone number.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.narrate(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.narrate("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.narrate(f"Order {order.get('id')}: duplicate customer in this run, skipping.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.narrate(f"Order {order.get('id')}: CRM contact already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.narrate(f"Order {order.get('id')}: update failed, retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.narrate(f"Order {order.get('id')}: updated existing CRM contact.") updated += 1 else: ctx.narrate(f"Order {order.get('id')}: update failed after retry, skipping.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.narrate(f"Order {order.get('id')}: created new CRM contact.") created += 1 else: ctx.narrate(f"Order {order.get('id')}: create failed, skipping.") skipped += 1 ctx.narrate(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.narrate(f"Setting carrier delivery preference to '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.narrate("Carrier delivery preferences saved.") else: ctx.narrate("Carrier delivery preferences were not confirmed as saved.") return saved Claude Haiku 5.5, ctx.breadcrumb (contact sync) =============================================== --- run 1 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results may be truncated") ctx.breadcrumb(f"Total orders fetched: {len(orders)}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: existing contact already up to date, skipping") skipped += 1 continue ctx.breadcrumb(f"Order {order.get('id')}: updating existing CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.breadcrumb(f"Updated CRM contact {existing['id']}") else: skipped += 1 ctx.breadcrumb(f"Update for contact {existing['id']} failed after retry, skipping") else: ctx.breadcrumb(f"Order {order.get('id')}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.breadcrumb(f"Created CRM contact for order {order.get('id')}") else: skipped += 1 ctx.breadcrumb(f"Create for order {order.get('id')} failed, skipping") ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Waited for carrier preferences form (or timed out)") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled carrier preferences form fields") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Delivery preferences saved={saved} for order {contact.source_order}") return saved --- run 2 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) contact = Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) ctx.breadcrumb(f"Order {order.get('id')}: built contact candidate") return contact def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") ctx.breadcrumb(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: existing contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {order.get('id')}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: create failed, skipping") skipped += 1 ctx.breadcrumb(f"Sync finished: created={created} updated={updated} skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form is ready") if "ready" not in locals(): pass with contextlib.suppress(Exception): client.fill("#email", contact.email) ctx.breadcrumb("Filled email field") with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.breadcrumb("Filled name field") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled city field") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Delivery preferences saved: {saved}") return saved --- run 3 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits ctx.breadcrumb(f"normalized phone to {len(digits)} digits") return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): ctx.breadcrumb(f"order {order.get('id')} has no shipping address") return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"order {order.get('id')} skipped: no usable email") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"order page {page_num} returned no data, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"order page {page_num} is empty, stopping") break orders.extend(batch) ctx.breadcrumb(f"fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.breadcrumb(f"reached MAX_PAGES={MAX_PAGES} while fetching orders") ctx.breadcrumb(f"fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"order {contact.source_order} matched existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"order {contact.source_order} matched existing CRM contact by phone") return by_phone["results"][0] ctx.breadcrumb(f"order {contact.source_order} has no existing CRM contact") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("no new orders, sync finished") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"order {contact.source_order} skipped: duplicate email in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"order {contact.source_order} skipped: CRM already up to date") skipped += 1 continue ctx.breadcrumb(f"updating CRM contact {existing['id']} from order {contact.source_order}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"update of contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"updated contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"update of contact {existing['id']} failed after retry, skipping") skipped += 1 else: ctx.breadcrumb(f"creating CRM contact from order {contact.source_order}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"create for order {contact.source_order} failed, skipping") skipped += 1 ctx.breadcrumb( f"customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"setting delivery preference window={window} for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("opened carrier preferences form") try: client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("carrier preferences form is ready") except Exception: ctx.breadcrumb("preferences form did not appear within timeout, continuing") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("filled carrier preferences fields") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("clicked save on carrier preferences form") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"carrier confirmed saved preferences for order {contact.source_order}") except Exception: ctx.breadcrumb(f"no save confirmation from carrier for order {contact.source_order}") return saved --- run 4 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"fetch_orders: starting fetch for orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"fetch_orders: no next page after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.breadcrumb(f"fetch_orders: empty or failed response on page {page_num}, stopping") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"fetch_orders: page {page_num} had no orders, stopping") break orders.extend(batch) ctx.breadcrumb(f"fetch_orders: page {page_num} returned {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.breadcrumb(f"fetch_orders: reached MAX_PAGES={MAX_PAGES} limit, results may be incomplete") ctx.breadcrumb(f"fetch_orders: done, {len(orders)} orders fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"find_existing: matched contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"find_existing: matched contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"find_existing: no match for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"sync_new_customers: starting sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("sync_new_customers: no orders to process") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.breadcrumb(f"sync_new_customers: skipped order {order.get('id')}, no usable email") continue if contact.email in seen: skipped += 1 ctx.breadcrumb(f"sync_new_customers: skipped order {order.get('id')}, duplicate in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.breadcrumb(f"sync_new_customers: skipped order {order.get('id')}, nothing to update") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"sync_new_customers: update failed for contact {existing['id']}, retrying") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.breadcrumb(f"sync_new_customers: updated contact {existing['id']} from order {order.get('id')}") else: skipped += 1 ctx.breadcrumb(f"sync_new_customers: update failed twice for contact {existing['id']}, skipped") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.breadcrumb(f"sync_new_customers: created contact from order {order.get('id')}") else: skipped += 1 ctx.breadcrumb(f"sync_new_customers: create failed for order {order.get('id')}, skipped") ctx.breadcrumb( f"sync_new_customers: done, created={created} updated={updated} skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"set_delivery_preferences: starting for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("set_delivery_preferences: opened carrier preferences page") try: client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("set_delivery_preferences: preferences form loaded") except Exception: ctx.breadcrumb("set_delivery_preferences: preferences form did not load within 30s, continuing") try: client.fill("#email", contact.email) ctx.breadcrumb("set_delivery_preferences: filled email field") except Exception: ctx.breadcrumb("set_delivery_preferences: could not fill email field") try: client.fill("#name", full_name) ctx.breadcrumb("set_delivery_preferences: filled name field") except Exception: ctx.breadcrumb("set_delivery_preferences: could not fill name field") if contact.address: try: client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("set_delivery_preferences: filled city field") except Exception: ctx.breadcrumb("set_delivery_preferences: could not fill city field") try: client.click("#save") ctx.breadcrumb("set_delivery_preferences: clicked save") except Exception: ctx.breadcrumb("set_delivery_preferences: could not click save") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"set_delivery_preferences: confirmed saved for order {contact.source_order}") except Exception: ctx.breadcrumb(f"set_delivery_preferences: no save confirmation for order {contact.source_order}") return saved --- run 5 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {contact.source_order}: existing contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form is ready") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier delivery preference for order {contact.source_order}: " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 6 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.breadcrumb(f"Fetching order page {page_num}") page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Order page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.breadcrumb(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {contact.source_order}: existing contact already up to date") skipped += 1 continue ctx.breadcrumb(f"Order {contact.source_order}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update for contact {existing['id']} failed after retry, skipping") skipped += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact for order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Create for order {contact.source_order} failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form is ready") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled city from shipping address") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 7 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found (order {contact.source_order})") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate contact in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: existing contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {order.get('id')}: CRM update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: CRM update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: CRM create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' (order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form load wait finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Carrier preferences form fields filled") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Carrier preferences save clicked") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( "Carrier preferences saved" if saved else "Carrier preferences save confirmation not seen" ) return saved --- run 8 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.breadcrumb(f"Requesting orders page {page_num}") page = client.get_json(url) if not page: ctx.breadcrumb(f"Orders page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Orders page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Orders page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.breadcrumb(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: existing contact already up to date") skipped += 1 continue ctx.breadcrumb(f"Order {order.get('id')}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {order.get('id')}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: update failed after retry, skipping") skipped += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: created CRM contact") created += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form loaded") if "preferences form loaded" not in ctx_state_placeholder(): pass with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled carrier form fields") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Delivery preferences for order {contact.source_order}: " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 9 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"No further pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.breadcrumb(f"Empty or failed response for order page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} contained no orders; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}); remaining order pages were not fetched") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting new-customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.breadcrumb(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.breadcrumb(f"Skipped order {contact.source_order}: duplicate email in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.breadcrumb(f"Skipped order {contact.source_order}: existing CRM contact already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"First update attempt failed for CRM contact {existing['id']}; retrying") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {contact.source_order}") else: skipped += 1 ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry; skipped") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") else: skipped += 1 ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}; skipped") ctx.breadcrumb(f"Sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form is ready") else: ctx.breadcrumb("Carrier preferences form did not appear within timeout; continuing anyway") with contextlib.suppress(Exception): client.fill("#email", contact.email) ctx.breadcrumb("Filled carrier form email field") with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.breadcrumb("Filled carrier form name field") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled carrier form city field") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked carrier form save button") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier delivery preference {'saved' if saved else 'not confirmed'} for order {contact.source_order}" ) return saved --- run 10 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES}; more orders may remain") ctx.breadcrumb(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: email already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipping order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form is ready") with contextlib.suppress(Exception): client.fill("#email", contact.email) ctx.breadcrumb("Filled email field on carrier form") with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.breadcrumb("Filled name field on carrier form") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled city field on carrier form") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 11 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.breadcrumb(f"Requesting orders page {page_num + 1}") page = client.get_json(url) if not page: ctx.breadcrumb(f"No response for orders page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Orders page {page_num + 1} is empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Received {len(batch)} orders on page {page_num + 1} ({len(orders)} total)") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES - 1: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}); more orders may remain") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; sync complete with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order_id}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"No new data for existing contact {existing['id']}; skipping update") skipped += 1 continue ctx.breadcrumb(f"Updating CRM contact {existing['id']} from order {order_id}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of contact {existing['id']} failed after retry; skipping") skipped += 1 else: ctx.breadcrumb(f"Creating CRM contact from order {order_id}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {order_id}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {order_id}; skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form is ready") if not contextlib.suppress is None: # placeholder removed below pass with contextlib.suppress(Exception): client.fill("#email", contact.email) ctx.breadcrumb("Filled email field on carrier form") with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.breadcrumb("Filled name field on carrier form") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled city field on carrier form") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier delivery preference {'saved' if saved else 'not confirmed as saved'} " f"for order {contact.source_order}" ) return saved --- run 12 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}), stopping pagination") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact for order {contact.source_order} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact for order {contact.source_order} by phone") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: existing contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {order.get('id')}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 13 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} while fetching orders; results may be incomplete") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact for order {contact.source_order} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact for order {contact.source_order} by phone") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"No changes needed for CRM contact {existing['id']}") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") if not _form_loaded_flag(client): ctx.breadcrumb("Carrier preferences form did not appear within timeout; continuing anyway") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.breadcrumb(f"Carrier confirmed saved preferences for order {contact.source_order}") else: ctx.breadcrumb(f"Carrier did not confirm saved preferences for order {contact.source_order}") return saved --- run 14 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") ctx.breadcrumb(f"Total orders fetched: {len(orders)}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb("CRM match found by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb("CRM match found by phone") return by_phone["results"][0] ctx.breadcrumb("No existing CRM match found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for index, order in enumerate(orders, start=1): contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Order {index}: skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {index}: skipped, duplicate email in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {index}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {index}: CRM update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {index}: updated existing CRM contact") updated += 1 else: ctx.breadcrumb(f"Order {index}: CRM update failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {index}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {index}: CRM create failed; skipped") skipped += 1 ctx.breadcrumb( f"Sync complete: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Opening carrier preferences form for window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form loaded") if not _form_loaded_flag(client): ctx.breadcrumb("Preferences form did not load within timeout; continuing") with contextlib.suppress(Exception): client.fill("#email", contact.email) ctx.breadcrumb("Filled email field") with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.breadcrumb("Filled name field") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled city field") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Delivery preferences saved: {saved}") return saved --- run 15 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact for order {contact.source_order} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact for order {contact.source_order} by phone") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {contact.source_order}: existing contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: CRM update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: CRM create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference for order {contact.source_order} to {window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier preference for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 16 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: if url: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}) with more orders remaining") ctx.breadcrumb(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipping order {order.get('id')}: existing CRM contact is already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}; skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 17 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.breadcrumb(f"Requesting orders page {page_num}") page = client.get_json(url) if not page: ctx.breadcrumb(f"No response for orders page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Orders page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Orders page {page_num} returned {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found (order {contact.source_order})") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.breadcrumb(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: email already seen in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipping order {order.get('id')}: existing contact already up to date") skipped += 1 continue ctx.breadcrumb(f"Updating CRM contact {existing['id']} from order {order.get('id')}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of contact {existing['id']} failed after retry; skipping") skipped += 1 else: ctx.breadcrumb(f"Creating CRM contact from order {order.get('id')}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.breadcrumb(f"Create for order {order.get('id')} failed; skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Opening carrier preferences form for window '{window}' (order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Waiting for carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Filling carrier preferences form") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Submitting carrier preferences form") with contextlib.suppress(Exception): client.click("#save") saved = False ctx.breadcrumb("Waiting for carrier save confirmation") with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Carrier preferences {'saved' if saved else 'not confirmed as saved'} (order {contact.source_order})") return saved --- run 18 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") for page_num in range(MAX_PAGES): if not url: break ctx.breadcrumb(f"Requesting order page {page_num + 1}") page = client.get_json(url) if not page: ctx.breadcrumb(f"No response for order page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num + 1} is empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Received {len(batch)} orders on page {page_num + 1} ({len(orders)} total)") url = page.get("next") ctx.breadcrumb(f"Finished fetching orders: {len(orders)} total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; sync complete with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"No changes needed for existing contact from order {order.get('id')}") skipped += 1 continue ctx.breadcrumb(f"Updating existing contact from order {order.get('id')}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update failed for order {order.get('id')}; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated contact from order {order.get('id')}") updated += 1 else: ctx.breadcrumb(f"Update failed again for order {order.get('id')}; skipping") skipped += 1 else: ctx.breadcrumb(f"Creating CRM contact from order {order.get('id')}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created contact from order {order.get('id')}") created += 1 else: ctx.breadcrumb(f"Create failed for order {order.get('id')}; skipping") skipped += 1 ctx.breadcrumb( f"Customer sync complete: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Waited for carrier preferences form") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled carrier preferences form fields") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.breadcrumb(f"Carrier confirmed delivery preferences saved for order {contact.source_order}") else: ctx.breadcrumb(f"Carrier did not confirm save for order {contact.source_order}") return saved --- run 19 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.breadcrumb(f"Requesting orders page {page_num}") page = client.get_json(url) if not page: ctx.breadcrumb(f"No response for orders page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Orders page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Received {len(batch)} orders on page {page_num} ({len(orders)} total)") url = page.get("next") if url and len(orders) > 0: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results may be incomplete") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync; finishing with empty result") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: email already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipping order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue ctx.breadcrumb(f"Updating CRM contact {existing['id']} from order {order.get('id')}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed after retry; skipping") skipped += 1 else: ctx.breadcrumb(f"Creating CRM contact from order {order.get('id')}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.breadcrumb(f"Creating CRM contact from order {order.get('id')} failed; skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Opening carrier preferences form for window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Waiting for carrier preferences form to load") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Filling carrier preferences form fields") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Submitting carrier preferences form") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Waiting for carrier confirmation of saved preferences") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Carrier preferences saved: {saved}") return saved --- run 20 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES}; more orders may remain unfetched") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found (order {contact.source_order})") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; sync complete with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipped order {order.get('id')}: email already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipped order {order.get('id')}: existing contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}; skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created} updated={updated} skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery window '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form load wait finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled carrier preferences form fields") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.breadcrumb(f"Carrier confirmed saved preferences for order {contact.source_order}") else: ctx.breadcrumb(f"Carrier did not confirm save for order {contact.source_order}") return saved --- run 21 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} limit; more orders may exist") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: found existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: found existing CRM contact by phone") return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {contact.source_order}: existing contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form loaded") if "preferences-form" not in locals(): pass with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled contact fields and city in preferences form") else: ctx.breadcrumb("Filled contact fields in preferences form; no address on file") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 22 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") ctx.breadcrumb(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found (order {contact.source_order})") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipped order {order.get('id')}: duplicate customer in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"No changes for existing contact {existing['id']}; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}; skipped") skipped += 1 ctx.breadcrumb(f"CRM sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' (order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded (or wait timed out)") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier preference save {'confirmed' if saved else 'not confirmed'} (order {contact.source_order})" ) return saved --- run 23 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num + 1} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num + 1} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES - 1: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync; finishing with empty result") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipping order {order.get('id')}: existing contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form is ready") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier preference for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 24 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") ctx.breadcrumb(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {contact.source_order}: CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact") updated += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created CRM contact") created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier preference for order {contact.source_order}: " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 25 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders") ctx.breadcrumb(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"CRM match by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"CRM match by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No CRM match for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {order.get('id')}: CRM update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: CRM update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {order.get('id')}: created CRM contact") created += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: CRM create failed, skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 26 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES}; further orders were not fetched") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found (order {contact.source_order})") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.breadcrumb(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.breadcrumb(f"Skipped order {order.get('id')}: contact already handled in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.breadcrumb(f"Skipped order {order.get('id')}: existing contact already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {order.get('id')}") else: skipped += 1 ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.breadcrumb(f"Created CRM contact from order {order.get('id')}") else: skipped += 1 ctx.breadcrumb(f"Failed to create CRM contact from order {order.get('id')}") ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' (order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") try: client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") except Exception: ctx.breadcrumb("Carrier preferences form did not load within 30s; continuing anyway") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Submitted carrier preferences form") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb("Carrier confirmed delivery preferences were saved") except Exception: ctx.breadcrumb("Carrier did not confirm save within 60s") return saved --- run 27 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: if url: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} with more orders remaining; results truncated") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"No changes needed for existing contact {existing['id']}") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of contact {existing['id']} failed after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}; skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences (window={window}) for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier preferences {'saved' if saved else 'not confirmed as saved'} for order {contact.source_order}" ) return saved --- run 28 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping fetch") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping fetch") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num}: {len(batch)} orders") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders") ctx.breadcrumb(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {contact.source_order}: CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created CRM contact") created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created} updated={updated} skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order}, window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Delivery preferences for order {contact.source_order} saved={saved}") return saved --- run 29 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: if url: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting new-customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; sync complete with no changes") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"No changes needed for existing contact {existing['id']}") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.breadcrumb(f"Sync complete: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Waited for preferences form (or continued after timeout)") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled preferences form fields") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.breadcrumb(f"Carrier confirmed delivery preferences saved for order {contact.source_order}") else: ctx.breadcrumb(f"Carrier did not confirm save for order {contact.source_order}") return saved --- run 30 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES ({MAX_PAGES}) while fetching orders; results may be truncated") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, sync complete") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {contact.source_order}: existing contact has no new data, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync complete: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Waited for carrier preferences form (or timed out)") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled carrier preferences form fields") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier delivery preference for order {contact.source_order}: " f"{'saved' if saved else 'not confirmed'}" ) return saved --- run 31 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: if url: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} with more orders remaining; results truncated") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipping order {order.get('id')}: existing contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form is ready") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Delivery preferences for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 32 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Order {contact.source_order}: CRM update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: CRM update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.breadcrumb(f"Order {contact.source_order}: CRM create failed, skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") if "#preferences-form" not in locals() or True: pass with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled carrier form fields from order address") else: ctx.breadcrumb("No address on order, filled carrier form without city") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.breadcrumb(f"Carrier confirmed saved preference for order {contact.source_order}") else: ctx.breadcrumb(f"Carrier did not confirm save for order {contact.source_order}") return saved --- run 33 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if not url: ctx.breadcrumb("No next page link; pagination complete") else: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} limit; some orders may not have been fetched") ctx.breadcrumb(f"Total orders fetched: {len(orders)}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting new-customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"No changes needed for existing contact {existing['id']}") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of contact {existing['id']} failed after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.breadcrumb( f"Sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier preferences for order {contact.source_order} " f"{'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 34 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.breadcrumb(f"Requesting order page {page_num}") page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Page {page_num}: {len(batch)} orders (total {len(orders)})") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES}, stopping pagination") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found (order {contact.source_order})") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: CRM contact already up to date") skipped += 1 continue ctx.breadcrumb(f"Order {order.get('id')}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed after retry, skipping") skipped += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact for order {order.get('id')}") created += 1 else: ctx.breadcrumb(f"Creating CRM contact for order {order.get('id')} failed, skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' (order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form is ready") if "preferences form is ready" not in [] : pass with contextlib.suppress(Exception): client.fill("#email", contact.email) ctx.breadcrumb("Filled email field") with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.breadcrumb("Filled name field") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled city field") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Delivery preference saved: {saved} (order {contact.source_order})") return saved --- run 35 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.breadcrumb(f"Requesting orders page {page_num}") page = client.get_json(url) if not page: ctx.breadcrumb(f"No response for orders page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Orders page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Orders page {page_num} returned {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES}; more orders may exist") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"CRM match found by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"CRM match found by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No CRM match for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found; sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"No changes needed for existing contact from order {order.get('id')}") skipped += 1 continue ctx.breadcrumb(f"Updating existing CRM contact {existing['id']} from order {order.get('id')}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update for contact {existing['id']} failed after retry; skipping") skipped += 1 else: ctx.breadcrumb(f"Creating CRM contact from order {order.get('id')}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.breadcrumb(f"Create for order {order.get('id')} failed; skipping") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form is ready") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier preference for order {contact.source_order} {'saved' if saved else 'not confirmed as saved'}" ) return saved --- run 36 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits ctx.breadcrumb("Phone number missing country code; prepended '1'") return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: ctx.breadcrumb("Customer name is empty; no first or last name set") return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): ctx.breadcrumb(f"Order {order.get('id')} has no shipping address line1") return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')} has no usable email; skipped") return None first, last = _split_name(order.get("customer_name", "")) contact = Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) ctx.breadcrumb(f"Built contact from order {order.get('id')}") return contact def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched {len(batch)} orders from page {page_num}") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES}; remaining orders not fetched") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders; sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')} repeats an email already processed this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Existing contact for order {contact.source_order} has no new data; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.breadcrumb(f"Update of contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Create failed for order {contact.source_order}; skipped") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Carrier preference save for order {contact.source_order}: {'confirmed' if saved else 'not confirmed'}") return saved --- run 37 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.breadcrumb(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES}; further orders may be missing") ctx.breadcrumb(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Found existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Found existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders to sync; finishing with empty result") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipping order {order.get('id')}: existing contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.breadcrumb( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form is ready") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb( f"Carrier preferences for order {contact.source_order} " + ("saved" if saved else "not confirmed as saved") ) return saved --- run 38 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.breadcrumb(f"Requesting orders page {page_num + 1}") page = client.get_json(url) if not page: ctx.breadcrumb(f"Orders page {page_num + 1} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Orders page {page_num + 1} was empty, stopping pagination") break orders.extend(batch) url = page.get("next") ctx.breadcrumb(f"Fetched {len(orders)} orders total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Order {contact.source_order}: matched existing CRM contact by phone") return by_phone["results"][0] ctx.breadcrumb(f"Order {contact.source_order}: no existing CRM contact found") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: existing contact already up to date, skipping") skipped += 1 continue ctx.breadcrumb(f"Order {order.get('id')}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update of CRM contact {existing['id']} failed after retry, skipping") skipped += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact for order {order.get('id')}") created += 1 else: ctx.breadcrumb(f"Creating CRM contact for order {order.get('id')} failed, skipping") skipped += 1 ctx.breadcrumb(f"Sync complete: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Opening carrier preferences form for window '{window}'") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Waited for carrier preferences form") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.breadcrumb("Filled carrier form email and name fields") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled carrier form city field") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Carrier preferences saved: {saved}") return saved --- run 39 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.breadcrumb(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) contact = Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) ctx.breadcrumb(f"Order {order.get('id')}: built contact candidate") return contact def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.breadcrumb(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break ctx.breadcrumb(f"Requesting orders page {page_num}") page = client.get_json(url) if not page: ctx.breadcrumb(f"Orders page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Orders page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Orders page {page_num}: {len(batch)} orders (total {len(orders)})") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} while fetching orders; results may be incomplete") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.breadcrumb(f"Contact matched existing CRM record by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Contact matched existing CRM record by phone (order {contact.source_order})") return by_phone["results"][0] ctx.breadcrumb(f"No existing CRM record for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.breadcrumb(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Order {order.get('id')}: duplicate customer in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Order {order.get('id')}: existing record already up to date, skipping") skipped += 1 continue ctx.breadcrumb(f"Order {order.get('id')}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.breadcrumb(f"Update for contact {existing['id']} failed after retry, skipping") skipped += 1 else: ctx.breadcrumb(f"Order {order.get('id')}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact for order {order.get('id')}") created += 1 else: ctx.breadcrumb(f"Create for order {order.get('id')} failed, skipping") skipped += 1 ctx.breadcrumb(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Preferences form is present") with contextlib.suppress(Exception): client.fill("#email", contact.email) ctx.breadcrumb("Filled email field") with contextlib.suppress(Exception): client.fill("#name", full_name) ctx.breadcrumb("Filled name field") if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) ctx.breadcrumb("Filled city field") with contextlib.suppress(Exception): client.click("#save") ctx.breadcrumb("Clicked save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Delivery preferences saved={saved} for order {contact.source_order}") return saved --- run 40 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.breadcrumb(f"Fetching shop orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: ctx.breadcrumb(f"No further pages after page {page_num - 1}") break page = client.get_json(url) if not page: ctx.breadcrumb(f"Empty response for page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.breadcrumb(f"Page {page_num} contained no orders; stopping pagination") break orders.extend(batch) ctx.breadcrumb(f"Fetched page {page_num} with {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.breadcrumb(f"Reached MAX_PAGES={MAX_PAGES} limit; some orders may not have been fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.breadcrumb(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.breadcrumb(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.breadcrumb("No orders found; sync complete with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.breadcrumb(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.breadcrumb(f"Skipped order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.breadcrumb(f"Skipped order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.breadcrumb(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.breadcrumb(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.breadcrumb(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.breadcrumb(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.breadcrumb(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.breadcrumb( f"Customer sync complete: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.breadcrumb( f"Setting carrier delivery preference to '{window}' for order {contact.source_order}" ) client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.breadcrumb("Opened carrier preferences form") try: client.wait_for("#preferences-form", timeout=30) ctx.breadcrumb("Carrier preferences form loaded") except Exception as exc: ctx.breadcrumb(f"Preferences form did not load: {type(exc).__name__}") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.breadcrumb(f"Could not fill city field: {type(exc).__name__}") try: client.click("#save") ctx.breadcrumb("Clicked save on carrier preferences form") except Exception as exc: ctx.breadcrumb(f"Could not click save: {type(exc).__name__}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True ctx.breadcrumb(f"Carrier confirmed saved preferences for order {contact.source_order}") except Exception as exc: ctx.breadcrumb( f"No save confirmation for order {contact.source_order}: {type(exc).__name__}" ) return saved Claude Haiku 5.5, ctx.zorp (contact sync) ========================================= --- run 1 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching orders page {page_num + 1} created after {since}") page = client.get_json(url) if not page: ctx.zorp(f"No response for orders page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Orders page {page_num + 1} is empty; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.zorp(f"Fetched {len(orders)} orders since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipping order {order.get('id')}: existing CRM contact {existing['id']} has nothing to add") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preference window '{window}' for contact {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded or wait timed out") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier saved delivery preference for contact {contact.source_order}") else: ctx.zorp(f"Carrier did not confirm delivery preference for contact {contact.source_order}") return saved --- run 2 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no page {page_num + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched page {page_num + 1} with {len(batch)} orders.") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Stopped at MAX_PAGES={MAX_PAGES}; more orders may exist beyond this page limit.") ctx.zorp(f"Fetched {len(orders)} orders created since {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; sync complete with nothing to do.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order.get('id')}: duplicate email within this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"First update attempt failed for CRM contact {existing['id']}; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {contact.source_order}.") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {contact.source_order}.") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}.") skipped += 1 ctx.zorp( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}." ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference for order {contact.source_order} to window '{window}'.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear for order {contact.source_order}: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field for order {contact.source_order}: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field for order {contact.source_order}: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field for order {contact.source_order}: {exc}") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save for order {contact.source_order}: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True ctx.zorp(f"Carrier delivery preference saved for order {contact.source_order}.") except Exception as exc: ctx.zorp(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}: {exc}") return saved --- run 3 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no page for url={url}; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Order pagination hit MAX_PAGES={MAX_PAGES}; some orders may be missing") ctx.zorp(f"Fetched {len(orders)} orders created since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; sync complete") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Skipped order {contact.source_order}: duplicate email in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Skipped order {contact.source_order}: CRM contact {existing.get('id')} already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"First update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Updated CRM contact {existing['id']} from order {contact.source_order}") else: skipped += 1 ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {contact.source_order}") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Created CRM contact from order {contact.source_order}") else: skipped += 1 ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}") ctx.zorp(f"Customer sync finished: created={created} updated={updated} skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery window '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preferences saved for order {contact.source_order}") else: ctx.zorp(f"Carrier delivery preferences not confirmed as saved for order {contact.source_order}") return saved --- run 4 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num}; stopping") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {page_num} contained no orders; stopping") break orders.extend(batch) ctx.zorp(f"Fetched page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; sync complete with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order_id}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order_id}: existing CRM contact {existing['id']} has no new data") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.zorp(f"Customer sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preference window '{window}' for contact from order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preferences saved for order {contact.source_order}") else: ctx.zorp(f"Carrier delivery preferences not confirmed as saved for order {contact.source_order}") return saved --- run 5 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching order page {page_num + 1} (since={since})") page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num + 1} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Order page {page_num + 1} yielded {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} limit; some orders may not have been fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync (since={since})") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.zorp(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order_id}: duplicate contact in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order_id}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update for order {order_id} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created} updated={updated} skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences (window={window}, source_order={contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Preferences form load wait finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Delivery preferences saved (source_order={contact.source_order})") else: ctx.zorp(f"Delivery preferences not confirmed as saved (source_order={contact.source_order})") return saved --- run 6 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"No response for order page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched order page {page_num + 1} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num + 1 >= MAX_PAGES: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES}; more orders may remain") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Skipped order {order_id}: no usable email") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Skipped order {order_id}: contact already processed in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Skipped order {order_id}: existing CRM contact {existing['id']} already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"First update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}") else: skipped += 1 ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id}") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Created CRM contact from order {order_id}") else: skipped += 1 ctx.zorp(f"Failed to create CRM contact from order {order_id}") ctx.zorp(f"Sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for source order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save button: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Preferences were not confirmed as saved: {exc}") if saved: ctx.zorp(f"Carrier delivery preference saved for source order {contact.source_order}") else: ctx.zorp(f"Carrier delivery preference NOT saved for source order {contact.source_order}") return saved --- run 7 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num + 1} (total so far: {len(orders)}).") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} limit; more orders may exist beyond this run.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; sync complete with nothing to do.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order.get('id')}: duplicate email within this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact {existing['id']} already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {contact.source_order}.") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry; skipping.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {contact.source_order}.") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}; skipping.") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences for order {contact.source_order} (window={window}).") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier confirmed delivery preferences saved for order {contact.source_order}.") else: ctx.zorp(f"Carrier did not confirm delivery preferences for order {contact.source_order}.") return saved --- run 8 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching orders page {page_num + 1} (created_after={since})") page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {page_num + 1} contained no orders; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.zorp(f"Fetched {len(orders)} order(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync (since={since})") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: no usable email; skipped") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: duplicate customer in this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order_id}: CRM contact {existing['id']} already up to date; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order_id}: update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {order_id}: update of contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.zorp(f"Order {order_id}: failed to create CRM contact; skipped") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference (window={window}) for contact source order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp("Carrier delivery preference saved") else: ctx.zorp("Carrier delivery preference was not confirmed as saved") return saved --- run 9 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched page {page_num + 1} with {len(batch)} orders") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES}; some orders may not have been fetched") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched order {contact.source_order} to an existing contact by phone") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order.get('id')}: duplicate customer in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update for order {order.get('id')} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {contact.source_order}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.zorp(f"CRM sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences (window={window}) for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier preferences saved for order {contact.source_order}") else: ctx.zorp(f"Carrier preferences not confirmed as saved for order {contact.source_order}") return saved --- run 10 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: break batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"sync_new_customers: starting, since={since}") orders = _fetch_orders(client, since) ctx.zorp(f"sync_new_customers: fetched {len(orders)} order(s)") if not orders: ctx.zorp("sync_new_customers: no new orders, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"sync_new_customers: order {order_id} skipped, no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"sync_new_customers: order {order_id} skipped, duplicate in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"sync_new_customers: order {order_id} skipped, CRM record already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"sync_new_customers: order {order_id} update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"sync_new_customers: order {order_id} updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"sync_new_customers: order {order_id} update failed after retry, skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"sync_new_customers: order {order_id} created CRM contact") created += 1 else: ctx.zorp(f"sync_new_customers: order {order_id} create failed, skipped") skipped += 1 ctx.zorp( f"sync_new_customers: done, created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"set_delivery_preferences: starting, window={window}, source_order={contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("set_delivery_preferences: preferences form load step finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("set_delivery_preferences: save clicked") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"set_delivery_preferences: saved for source_order={contact.source_order}") else: ctx.zorp( f"set_delivery_preferences: no save confirmation for source_order={contact.source_order}" ) return saved --- run 11 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.zorp(f"Order page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}), some orders may not have been fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found, nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.zorp(f"Syncing {len(orders)} orders into the CRM") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.zorp(f"CRM sync finished: {created} created, {updated} updated, {skipped} skipped") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier saved delivery preference for order {contact.source_order}") else: ctx.zorp(f"Carrier did not confirm delivery preference for order {contact.source_order}") return saved --- run 12 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no page after {pages} page(s); stopping pagination.") break pages += 1 batch = page.get("orders") or [] if not batch: break orders.extend(batch) url = page.get("next") if url and pages >= MAX_PAGES: ctx.zorp(f"Order pagination hit MAX_PAGES={MAX_PAGES}; some orders may not have been fetched.") ctx.zorp(f"Fetched {len(orders)} order(s) across {pages} page(s) since {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order.get('id')}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order.get('id')}: duplicate customer within this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry; skipping.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order.get('id')}.") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}; skipping.") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preference saved for order {contact.source_order}.") else: ctx.zorp(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}.") return saved --- run 13 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num + 1} (running total: {len(orders)}).") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more orders available; results may be incomplete.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order_id}: contact already processed in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order_id}: CRM contact {existing['id']} already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed for order {order_id}; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}.") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id}.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}.") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for contact {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form load wait finished.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Carrier preferences form submitted.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp("Carrier confirmed delivery preferences were saved.") else: ctx.zorp("Carrier did not confirm delivery preferences were saved.") return saved --- run 14 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num + 1} (running total: {len(orders)}).") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more orders available; results may be incomplete.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) ctx.zorp(f"Processing {len(orders)} orders.") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order_id}: contact already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order_id}: existing CRM contact {existing['id']} already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}.") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id} after retry.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}.") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for contact from order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form load wait finished.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Carrier preferences form submitted.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preference saved for order {contact.source_order}.") else: ctx.zorp(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}.") return saved --- run 15 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num} is empty, stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} while fetching orders; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Matched existing CRM contact for order {contact.source_order} by email") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact for order {contact.source_order} by phone") return by_phone["results"][0] ctx.zorp(f"No existing CRM contact found for order {contact.source_order}") return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact already up to date, skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {contact.source_order}: update failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {contact.source_order}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {contact.source_order}: update failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {contact.source_order}: created new CRM contact") created += 1 else: ctx.zorp(f"Order {contact.source_order}: create failed, skipping") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp(f"Order {contact.source_order}: preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp(f"Order {contact.source_order}: save clicked") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Order {contact.source_order}: delivery preferences saved") else: ctx.zorp(f"Order {contact.source_order}: delivery preferences were not confirmed as saved") return saved --- run 16 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num + 1}.") url = page.get("next") if url: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more orders remaining; results may be incomplete.") ctx.zorp(f"Fetched {len(orders)} orders created since {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}.") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: no usable email address.") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: duplicate customer within this run.") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact already up to date.") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}.") else: skipped += 1 ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}.") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Created CRM contact from order {order.get('id')}.") else: skipped += 1 ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}.") ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: pass with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preference saved for order {contact.source_order}.") else: ctx.zorp(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}.") return saved --- run 17 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} while paginating orders; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched contact for order {contact.source_order} by phone, not email") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting new-customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: customer already handled in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") else: skipped += 1 ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Created CRM contact from order {order.get('id')}") else: skipped += 1 ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}") ctx.zorp( f"Sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.zorp(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}") return saved --- run 18 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num + 1} (running total: {len(orders)}).") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more orders available; results may be incomplete.") ctx.zorp(f"Order fetch complete: {len(orders)} orders since {since}.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order_id}: contact already handled earlier in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order_id}: existing CRM contact {existing['id']} already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}.") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id} after retry.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}.") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for contact from order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: pass form_ready = True try: client.wait_for("#preferences-form", timeout=30) except Exception: form_ready = False ctx.zorp("Carrier preferences form did not appear within timeout; continuing anyway.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preference saved for order {contact.source_order}.") else: ctx.zorp(f"Carrier delivery preference was not confirmed as saved for order {contact.source_order}.") return saved --- run 19 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES}; more orders may remain unfetched") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Matched existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipping order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipping order {order.get('id')}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"No new data for existing contact from order {order.get('id')}; skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update failed for CRM contact {existing['id']}; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}") skipped += 1 ctx.zorp(f"CRM sync complete: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.zorp( f"Carrier preferences {'saved' if saved else 'not confirmed as saved'} " f"for order {contact.source_order}" ) return saved --- run 20 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch stopped on page {page_num + 1}: no response") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched page {page_num + 1} with {len(batch)} orders") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} while fetching orders; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: duplicate email within this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: CRM contact already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"First update attempt failed for order {order.get('id')}; retrying") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") else: skipped += 1 ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Created CRM contact from order {contact.source_order}") else: skipped += 1 ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}") ctx.zorp( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Waited for carrier preferences form (or timed out and continued)") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier confirmed delivery preferences saved for order {contact.source_order}") else: ctx.zorp(f"Carrier did not confirm delivery preferences for order {contact.source_order}") return saved --- run 21 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination.") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num + 1} (running total: {len(orders)}).") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Stopped order pagination at MAX_PAGES={MAX_PAGES}; more orders may remain.") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}.") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync.") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order_id}: no usable email address.") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order_id}: duplicate customer already handled in this run.") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order_id}: existing CRM contact already up to date.") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update for CRM contact {existing['id']} failed; retrying once.") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}.") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id}.") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}.") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}.") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}.") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for source order {contact.source_order}.") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded.") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form.") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preference saved for source order {contact.source_order}.") else: ctx.zorp(f"Carrier delivery preference was not confirmed as saved for source order {contact.source_order}.") return saved --- run 22 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num}; stopping") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {page_num} had no orders; pagination complete") break orders.extend(batch) ctx.zorp(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES}; some orders may not have been fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.zorp(f"Starting CRM sync for {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Order {order_id}: skipped (no usable email)") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Order {order_id}: skipped (duplicate email in this run)") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Order {order_id}: skipped (CRM contact {existing['id']} already up to date)") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order_id}: update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") else: skipped += 1 ctx.zorp(f"Order {order_id}: update of contact {existing['id']} failed after retry; skipped") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Order {order_id}: created new CRM contact") else: skipped += 1 ctx.zorp(f"Order {order_id}: failed to create CRM contact; skipped") ctx.zorp(f"CRM sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference (window={window}) for contact from order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Save confirmation not seen: {exc}") ctx.zorp(f"Delivery preference {'saved' if saved else 'NOT saved'} for contact from order {contact.source_order}") return saved --- run 23 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching order page {page_num + 1} since {since}") page = client.get_json(url) if not page: ctx.zorp(f"No response for order page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num + 1} is empty; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.zorp(f"Fetched {len(orders)} order(s) since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipping order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipping order {order_id}: duplicate customer in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipping order {order_id}: CRM contact {existing.get('id')} already up to date") skipped += 1 continue ctx.zorp(f"Updating CRM contact {existing.get('id')} from order {order_id}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing.get('id')} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing.get('id')}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing.get('id')} after retry; skipping") skipped += 1 else: ctx.zorp(f"Creating CRM contact from order {order_id}") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}; skipping") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Preferences form wait finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted delivery preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp("Delivery preferences saved") else: ctx.zorp("Delivery preferences were not confirmed as saved") return saved --- run 24 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" pages = 0 for _ in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching orders page {pages + 1}") page = client.get_json(url) if not page: ctx.zorp(f"No response for orders page {pages + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Orders page {pages + 1} is empty; stopping pagination") break orders.extend(batch) pages += 1 url = page.get("next") if url and pages >= MAX_PAGES: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} while fetching orders; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders across {pages} page(s)") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipping order {order_id}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order_id}: existing CRM contact {existing['id']} already up to date") skipped += 1 continue ctx.zorp(f"Order {order_id}: updating CRM contact {existing['id']}") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: ctx.zorp(f"Order {order_id}: creating new CRM contact") resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact for order {order_id}") created += 1 else: ctx.zorp(f"Failed to create CRM contact for order {order_id}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences (window={window}) for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Delivery preferences saved for order {contact.source_order}") else: ctx.zorp(f"Delivery preferences not confirmed as saved for order {contact.source_order}") return saved --- run 25 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more orders remaining; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order.get('id')}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update for CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created} updated={updated} skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") if not _form_loaded_flag(client): ctx.zorp("Carrier preferences form did not load within timeout; attempting to fill anyway") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.zorp(f"Carrier delivery preference not confirmed as saved for order {contact.source_order}") return saved --- run 26 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching orders page {page_num + 1} created after {since}") page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {page_num + 1} contained no orders; stopping pagination") break orders.extend(batch) url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more order pages remaining; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} order(s) in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order.get('id')}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order.get('id')}: duplicate email within this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}; skipping") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form load wait completed (or timed out)") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier confirmed saved preferences for order {contact.source_order}") else: ctx.zorp(f"Carrier did not confirm saved preferences for order {contact.source_order}") return saved --- run 27 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"Fetching orders created after {since}") for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch stopped: no response on page {page_num + 1}") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched page {page_num + 1} with {len(batch)} orders") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES - 1: ctx.zorp(f"Order fetch hit MAX_PAGES={MAX_PAGES}; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Matched existing CRM contact by email for order {contact.source_order}") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: duplicate customer in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: CRM contact already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update failed for CRM contact {existing['id']}; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") else: skipped += 1 ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Created CRM contact from order {order.get('id')}") else: skipped += 1 ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}") ctx.zorp( f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Waited for carrier preferences form") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier confirmed delivery preference saved for order {contact.source_order}") else: ctx.zorp(f"Carrier did not confirm delivery preference for order {contact.source_order}") return saved --- run 28 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for _ in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no page; stopping with {len(orders)} orders so far") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders (running total {len(orders)})") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more orders available; results are truncated") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: no usable email") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: duplicate customer in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Skipped order {order.get('id')}: CRM contact {existing['id']} already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") else: skipped += 1 ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Created CRM contact from order {order.get('id')}") else: skipped += 1 ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}") ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery window to '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preferences saved for order {contact.source_order}") else: ctx.zorp(f"Carrier delivery preferences not confirmed as saved for order {contact.source_order}") return saved --- run 29 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching orders page {page_num + 1} since {since}") page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num + 1} was empty; stopping pagination") break orders.extend(batch) url = page.get("next") ctx.zorp(f"Fetched {len(orders)} orders since {since}") if url and len(orders) and page_num + 1 >= MAX_PAGES: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES}; more orders may exist beyond this run") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order_id}: duplicate customer in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order_id}: CRM contact {existing.get('id')} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preference window '{window}' for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Waited for carrier preferences form") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier saved delivery preferences for order {contact.source_order}") else: ctx.zorp(f"Carrier did not confirm saved delivery preferences for order {contact.source_order}") return saved --- run 30 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num + 1}") url = page.get("next") if url: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more orders available; results may be incomplete") ctx.zorp(f"Fetched {len(orders)} orders created since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders created since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; sync complete with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipping order {order_id}: no usable email address") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipping order {order_id}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order_id}: CRM contact {existing.get('id')} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order_id}: update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {order_id}: failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.zorp(f"Order {order_id}: failed to create CRM contact") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preference for order {contact.source_order}: window={window}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier delivery preference saved for order {contact.source_order}") else: ctx.zorp(f"Carrier delivery preference not confirmed as saved for order {contact.source_order}") return saved --- run 31 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching orders page {page_num + 1} since {since}") page = client.get_json(url) if not page: ctx.zorp(f"Orders page {page_num + 1} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Orders page {page_num + 1} is empty, stopping pagination") break orders.extend(batch) url = page.get("next") ctx.zorp(f"Fetched {len(orders)} orders since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found, sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {contact.source_order}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {contact.source_order}: CRM contact {existing['id']} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form load wait finished") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Carrier preferences form submitted") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Delivery preferences saved for order {contact.source_order}") else: ctx.zorp(f"Delivery preferences not confirmed as saved for order {contact.source_order}") return saved --- run 32 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order fetch returned no data on page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Page {page_num} contained no orders; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: if url: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results truncated") ctx.zorp(f"Order fetch complete: {len(orders)} orders") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipping order {order.get('id')}: contact already processed in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipping order {order.get('id')}: existing CRM contact {existing['id']} has no new data") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order.get('id')}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order.get('id')}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order.get('id')}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order.get('id')}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier preferences saved for order {contact.source_order}") else: ctx.zorp(f"Carrier preferences not confirmed as saved for order {contact.source_order}") return saved --- run 33 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching orders page {page_num + 1} (since={since})") page = client.get_json(url) if not page: ctx.zorp(f"No response for orders page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Orders page {page_num + 1} is empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Orders page {page_num + 1} returned {len(batch)} order(s)") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES - 1: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more pages remaining; results may be truncated") ctx.zorp(f"Fetched {len(orders)} order(s) in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync (since={since})") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Order {order_id}: no usable email; skipped") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order_id}: duplicate customer in this run; skipped") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order_id}: CRM contact {existing.get('id')} already up to date; skipped") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order_id}: update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {order_id}: update of contact {existing['id']} failed after retry; skipped") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {order_id}: created new CRM contact") created += 1 else: ctx.zorp(f"Order {order_id}: creating CRM contact failed; skipped") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences (window={window}, source_order={contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Preferences were not confirmed as saved: {exc}") ctx.zorp(f"Delivery preferences saved={saved} (source_order={contact.source_order})") return saved --- run 34 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" ctx.zorp(f"fetch_orders: starting fetch for orders created after {since}") for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"fetch_orders: no response on page {page_num}, stopping") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"fetch_orders: page {page_num} empty, stopping") break orders.extend(batch) ctx.zorp(f"fetch_orders: page {page_num} returned {len(batch)} orders ({len(orders)} total)") url = page.get("next") else: ctx.zorp(f"fetch_orders: reached MAX_PAGES={MAX_PAGES} limit; results may be incomplete") ctx.zorp(f"fetch_orders: finished with {len(orders)} orders") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"sync_new_customers: starting sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("sync_new_customers: no orders to process") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"sync_new_customers: order {order_id} skipped (no usable email)") skipped += 1 continue if contact.email in seen: ctx.zorp(f"sync_new_customers: order {order_id} skipped (duplicate email in this run)") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"sync_new_customers: order {order_id} skipped (CRM record already up to date)") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"sync_new_customers: update for order {order_id} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"sync_new_customers: updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.zorp(f"sync_new_customers: update for order {order_id} failed after retry, skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"sync_new_customers: created CRM contact from order {order_id}") created += 1 else: ctx.zorp(f"sync_new_customers: create for order {order_id} failed, skipping") skipped += 1 ctx.zorp( f"sync_new_customers: finished (created={created}, updated={updated}, skipped={skipped})" ) return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"set_delivery_preferences: starting for contact {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("set_delivery_preferences: preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("set_delivery_preferences: save clicked") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True ctx.zorp(f"set_delivery_preferences: finished for contact {contact.source_order} (saved={saved})") return saved --- run 35 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched order page {page_num} with {len(batch)} orders") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}); some orders may not have been fetched") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: skipped += 1 ctx.zorp(f"Order {order_id}: skipped, no usable email") continue if contact.email in seen: skipped += 1 ctx.zorp(f"Order {order_id}: skipped, customer already handled in this run") continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: skipped += 1 ctx.zorp(f"Order {order_id}: skipped, CRM contact {existing.get('id')} already up to date") continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order_id}: update of contact {existing['id']} failed, retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: updated += 1 ctx.zorp(f"Order {order_id}: updated CRM contact {existing['id']}") else: skipped += 1 ctx.zorp(f"Order {order_id}: update of CRM contact {existing['id']} failed; skipped") else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: created += 1 ctx.zorp(f"Order {order_id}: created CRM contact") else: skipped += 1 ctx.zorp(f"Order {order_id}: creating CRM contact failed; skipped") ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def _attempt(step: str, fn) -> bool: """Run one browser step, record any failure, and keep going.""" try: fn() return True except Exception as exc: ctx.zorp(f"Carrier form step '{step}' failed: {type(exc).__name__}: {exc}") return False def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery preferences (window={window})") _attempt("open preferences page", lambda: client.open(f"{CARRIER_URL}/preferences/new?window={window}")) _attempt("wait for form", lambda: client.wait_for("#preferences-form", timeout=30)) _attempt("fill email", lambda: client.fill("#email", contact.email)) _attempt("fill name", lambda: client.fill("#name", full_name)) if contact.address: _attempt("fill city", lambda: client.fill("#city", contact.address.get("city", ""))) _attempt("click save", lambda: client.click("#save")) saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True except Exception as exc: ctx.zorp(f"Carrier preferences were not confirmed as saved: {type(exc).__name__}: {exc}") if saved: ctx.zorp("Carrier delivery preferences saved") else: ctx.zorp("Carrier delivery preferences could not be confirmed") return saved --- run 36 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching order page {page_num + 1} since {since}") page = client.get_json(url) if not page: ctx.zorp(f"No response for order page {page_num + 1}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num + 1} is empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num + 1} ({len(orders)} total)") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}) with more orders remaining; results may be incomplete") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.zorp(f"Processing {len(orders)} orders") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order.get('id')}: duplicate customer in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order.get('id')}: existing CRM contact already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update failed for CRM contact {existing['id']}; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {contact.source_order}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences (window={window}) for order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Clicked save on carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier preferences saved for order {contact.source_order}") else: ctx.zorp(f"Carrier preferences not confirmed as saved for order {contact.source_order}") return saved --- run 37 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num + 1} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: break orders.extend(batch) ctx.zorp(f"Fetched order page {page_num + 1} with {len(batch)} orders") url = page.get("next") if url and len(orders) > 0: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES} with more orders available; results are truncated") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync for orders since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No orders found; sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: order_id = order.get("id") contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order_id}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order_id}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Skipped order {order_id}: existing CRM contact {existing.get('id')} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']} from order {order_id}") updated += 1 else: ctx.zorp(f"Failed to update CRM contact {existing['id']} from order {order_id}") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {order_id}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {order_id}") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences (window={window}) for contact from order {contact.source_order}") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.zorp("Carrier preferences form loaded") if not contextlib.suppress: pass with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Delivery preferences saved for order {contact.source_order}") else: ctx.zorp(f"Delivery preferences not confirmed as saved for order {contact.source_order}") return saved --- run 38 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: ctx.zorp(f"Order {order.get('id')}: no usable email, skipping") return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(MAX_PAGES): if not url: break ctx.zorp(f"Fetching orders page {page_num + 1} since {since}") page = client.get_json(url) if not page: ctx.zorp(f"Orders page {page_num + 1} returned no data, stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Orders page {page_num + 1} is empty, stopping pagination") break orders.extend(batch) url = page.get("next") ctx.zorp(f"Fetched {len(orders)} orders since {since}") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone for order {contact.source_order}") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" ctx.zorp(f"Starting customer sync since {since}") orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found, sync finished with nothing to do") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: skipped += 1 continue if contact.email in seen: ctx.zorp(f"Order {order.get('id')}: duplicate email in this run, skipping") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Order {order.get('id')}: CRM contact {existing.get('id')} already up to date") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Order {order.get('id')}: update of contact {existing['id']} failed, retrying") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Order {order.get('id')}: updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Order {order.get('id')}: update of contact {existing['id']} failed after retry") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Order {order.get('id')}: created new CRM contact") created += 1 else: ctx.zorp(f"Order {order.get('id')}: failed to create CRM contact") skipped += 1 ctx.zorp(f"Customer sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences for order {contact.source_order} (window={window})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") ctx.zorp("Opened carrier preferences form") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) ctx.zorp("Waited for carrier preferences form") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") ctx.zorp("Submitted carrier preferences form") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Carrier saved delivery preferences for order {contact.source_order}") else: ctx.zorp(f"Carrier did not confirm saved delivery preferences for order {contact.source_order}") return saved --- run 39 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import contextlib import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching orders created after {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"Order page {page_num} returned no data; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Order page {page_num} was empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched {len(batch)} orders from page {page_num}") url = page.get("next") else: ctx.zorp(f"Reached MAX_PAGES ({MAX_PAGES}); remaining orders not fetched") ctx.zorp(f"Fetched {len(orders)} orders in total") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipped order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipped order {order.get('id')}: customer already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"No changes for existing contact {existing['id']} (order {contact.source_order})") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated contact {existing['id']} (order {contact.source_order})") updated += 1 else: ctx.zorp(f"Failed to update contact {existing['id']} after retry (order {contact.source_order})") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact from order {contact.source_order}") created += 1 else: ctx.zorp(f"Failed to create CRM contact from order {contact.source_order}") skipped += 1 ctx.zorp(f"CRM sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting delivery preferences (window={window}, order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") with contextlib.suppress(Exception): client.wait_for("#preferences-form", timeout=30) else: ctx.zorp("Carrier preferences form loaded") with contextlib.suppress(Exception): client.fill("#email", contact.email) with contextlib.suppress(Exception): client.fill("#name", full_name) if contact.address: with contextlib.suppress(Exception): client.fill("#city", contact.address.get("city", "")) with contextlib.suppress(Exception): client.click("#save") saved = False with contextlib.suppress(Exception): client.wait_for(".preferences-saved", timeout=60) saved = True if saved: ctx.zorp(f"Saved delivery preferences (order {contact.source_order})") else: ctx.zorp(f"Delivery preferences not confirmed as saved (order {contact.source_order})") return saved --- run 40 --- """Sync a shop's new customers into the CRM, and set their delivery preferences with the carrier.""" import re from urllib.parse import quote_plus from integrations.context import ctx from integrations.http import Client from integrations.models import Contact, SyncResult CRM_URL = "https://crm.example.com/api" SHOP_URL = "https://shop.example.com/admin" CARRIER_URL = "https://carrier.example.com" MAX_PAGES = 20 def _normalize_phone(raw: str) -> str: """Keep digits only, and add the country code when it's missing.""" digits = re.sub(r"\D", "", raw or "") if len(digits) == 10: digits = "1" + digits return digits def _split_name(full_name: str) -> tuple[str, str]: """Split a display name into first and last.""" parts = (full_name or "").strip().split() if not parts: return "", "" if len(parts) == 1: return parts[0], "" return parts[0], " ".join(parts[1:]) def _parse_address(order: dict) -> dict[str, str]: """Pull a mailing address out of an order's shipping block.""" ship = order.get("shipping") or {} if not ship.get("line1"): return {} return { "line1": ship.get("line1", ""), "city": ship.get("city", ""), "state": ship.get("state", ""), "zip": ship.get("zip", ""), } def _to_contact(order: dict) -> Contact | None: """Turn one shop order into a CRM contact, or None if it has no usable email.""" email = (order.get("email") or "").strip().lower() if not email or "@" not in email: return None first, last = _split_name(order.get("customer_name", "")) return Contact( email=email, first_name=first, last_name=last, phone=_normalize_phone(order.get("phone", "")), address=_parse_address(order) or None, source_order=order.get("id"), ) def _fetch_orders(client: Client, since: str) -> list[dict]: """Fetch every order created since a timestamp, following the shop's pagination.""" ctx.zorp(f"Fetching shop orders created since {since}") orders: list[dict] = [] url: str | None = f"{SHOP_URL}/orders?created_after={quote_plus(since)}" for page_num in range(1, MAX_PAGES + 1): if not url: break page = client.get_json(url) if not page: ctx.zorp(f"No response for orders page {page_num}; stopping pagination") break batch = page.get("orders") or [] if not batch: ctx.zorp(f"Orders page {page_num} is empty; stopping pagination") break orders.extend(batch) ctx.zorp(f"Fetched orders page {page_num}: {len(batch)} orders ({len(orders)} total)") url = page.get("next") if url and len(orders) and page_num == MAX_PAGES: ctx.zorp(f"Reached MAX_PAGES={MAX_PAGES}; further orders may not have been fetched") return orders def _find_existing(client: Client, contact: Contact) -> dict | None: """Look the contact up in the CRM by email, then by phone.""" by_email = client.get_json(f"{CRM_URL}/contacts?email={quote_plus(contact.email)}") if by_email and by_email.get("results"): ctx.zorp(f"Matched existing CRM contact by email (order {contact.source_order})") return by_email["results"][0] if contact.phone: by_phone = client.get_json(f"{CRM_URL}/contacts?phone={contact.phone}") if by_phone and by_phone.get("results"): ctx.zorp(f"Matched existing CRM contact by phone (order {contact.source_order})") return by_phone["results"][0] return None def _merge(existing: dict, contact: Contact) -> dict: """Fill gaps in an existing CRM record without overwriting what's there.""" merged = dict(existing) for field in ("first_name", "last_name", "phone"): if not merged.get(field) and getattr(contact, field): merged[field] = getattr(contact, field) if contact.address and not merged.get("address"): merged["address"] = contact.address return merged def sync_new_customers(client: Client, since: str) -> SyncResult: """Create or update a CRM contact for every new shop customer since a timestamp.""" orders = _fetch_orders(client, since) if not orders: ctx.zorp("No new orders found; nothing to sync") return SyncResult(created=0, updated=0, skipped=0) ctx.zorp(f"Syncing {len(orders)} orders into the CRM") seen: set[str] = set() created = updated = skipped = 0 for order in orders: contact = _to_contact(order) if contact is None: ctx.zorp(f"Skipping order {order.get('id')}: no usable email") skipped += 1 continue if contact.email in seen: ctx.zorp(f"Skipping order {order.get('id')}: contact already handled in this run") skipped += 1 continue seen.add(contact.email) existing = _find_existing(client, contact) if existing: merged = _merge(existing, contact) if merged == existing: ctx.zorp(f"Existing CRM contact {existing['id']} already up to date; skipping") skipped += 1 continue resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is None: ctx.zorp(f"Update of CRM contact {existing['id']} failed; retrying once") resp = client.put_json(f"{CRM_URL}/contacts/{existing['id']}", merged) if resp is not None: ctx.zorp(f"Updated CRM contact {existing['id']}") updated += 1 else: ctx.zorp(f"Update of CRM contact {existing['id']} failed after retry; skipping") skipped += 1 else: resp = client.post_json(f"{CRM_URL}/contacts", contact.as_dict()) if resp is not None: ctx.zorp(f"Created CRM contact for order {contact.source_order}") created += 1 else: ctx.zorp(f"Creating CRM contact for order {contact.source_order} failed; skipping") skipped += 1 ctx.zorp(f"CRM sync finished: created={created}, updated={updated}, skipped={skipped}") return SyncResult(created=created, updated=updated, skipped=skipped) def set_delivery_preferences(client: Client, contact: Contact, window: str | None = None) -> bool: """Record a contact's preferred delivery window in the carrier's portal form.""" full_name = f"{contact.first_name} {contact.last_name}".strip() window = window or "weekday-daytime" ctx.zorp(f"Setting carrier delivery window to '{window}' (order {contact.source_order})") client.open(f"{CARRIER_URL}/preferences/new?window={window}") try: client.wait_for("#preferences-form", timeout=30) except Exception as exc: ctx.zorp(f"Preferences form did not appear: {exc}") try: client.fill("#email", contact.email) except Exception as exc: ctx.zorp(f"Could not fill email field: {exc}") try: client.fill("#name", full_name) except Exception as exc: ctx.zorp(f"Could not fill name field: {exc}") if contact.address: try: client.fill("#city", contact.address.get("city", "")) except Exception as exc: ctx.zorp(f"Could not fill city field: {exc}") try: client.click("#save") except Exception as exc: ctx.zorp(f"Could not click save: {exc}") saved = False try: client.wait_for(".preferences-saved", timeout=60) saved = True ctx.zorp(f"Carrier delivery preferences saved (order {contact.source_order})") except Exception as exc: ctx.zorp(f"Carrier delivery preferences not confirmed as saved (order {contact.source_order}): {exc}") return saved