I think I understand what you want. The following query extends what we did earlier, but incorporates the sequence code to generate a single order number for all merchant orders and a derived set of indexes for assigning the subOrderNo for each merchant order. To calculate the indexes using the range method, I had to collect all the merchant orders into a list, generate the sequence, then unwind the merchant list of orders.
The following query does execute without error. It is getting complicated to test without some good test data, so give it a good shakeout. I think it should work. Let me know if you uncover anything and we can try to address it.
The query is for one specific cart. Change the cart criteria in the first MATCH to meet your needs.
MATCH (cart:Cart{id: 100})
CALL {
MERGE (id:UniqueId {name:"orderNo"})
ON CREATE SET id.id = 1
ON MATCH SET id.id = id.id+1
RETURN id.id as orderNo
}
MATCH (cart)-[contains:CONTAINS]->(product:Product)-[sold:IS_SOLD_BY]->(merchant:Merchant)
WITH orderNo, merchant, collect({c: contains, p: product}) as merchantProducts, count(product) as noOfItems, sum(product.price*contains.quantity) as orderTotalPrice
WITH orderNo, collect({m: merchant, p: merchantProducts, n: noOfItems, t: orderTotalPrice}) as merchantOrders
WITH orderNo, merchantOrders, range(1,size(merchantOrders)) as indexes
UNWIND indexes as index
WITH orderNo, index as subOrderNo, merchantOrders[index] as merchantOrder
WITH orderNo, subOrderNo, merchantOrder.m as merchant, merchantOrder.p as merchantProducts, merchantOrder.n as noOfItems, merchantOrder.t as orderTotalPrice
CREATE (order:Order)-[b:BELONGS_TO]->(merchant)
SET order.number = orderNo,
order.subOrder = subOrderNo,
order.itemsAmount = orderTotalPrice,
order.itemsNumber = noOfItems,
order.transportAmount = noOfItems + 9,
order.totalAmount = orderTotalPrice + noOfItems + 9,
order.uuid = apoc.create.uuid(),
order.created_at = dateTime(),
order.status = "created"
WITH order, merchantProducts
UNWIND merchantProducts as merchantProduct
WITH order, merchantProduct.c as contains, merchantProduct.p as product
MERGE (order)-[c:CONTAINS]->(product)
set c=contains,
c.price = product.price
RETURN distinct(order) as order