# Order

In the <mark style="color:blue;">`Order`</mark> logic, what is similar to its respective part in the **Core module**:

* Create the <mark style="color:blue;">`OrderItemDto`</mark>

```typescript
export class OrderItemDto {
  @IsEntity()
  readonly product: IdDto;

  @IsCardinal()
  readonly quantity: number;
}
```

* Implement the <mark style="color:blue;">`CreateOrderDto`</mark>

```typescript
export class CreateOrderDto {
  @IsEntity()
  readonly customer: IdDto;

  @ArrayNotEmpty()
  @ValidateNested()
  @Type(() => OrderItemDto)
  readonly items: OrderItemDto[];
}
```

* Delete the <mark style="color:blue;">`UpdateOrderDto`</mark>, and the <mark style="color:blue;">`update()`</mark> method in the **controller** and **service**

Now what's new: in the **service**, we should, both in <mark style="color:blue;">`findAll()`</mark> and <mark style="color:blue;">`findOne()`</mark>, fetch the relations. Note that we need to use <mark style="color:blue;">`include`</mark> whenever fetching an entity with relations.

```typescript
include: {
  items: {
    include: {
      product: true,
    },
  },
  customer: true,
  payment: true,
},
```

And the aux method to create **items with price**. What should be noticed is, when creating the <mark style="color:blue;">`orderItem`</mark>, the Prisma **dynamic type**, which allows for robust type safety.

```typescript
private async createOrderItemWithPrice(orderItemDto: OrderItemDto) {
  const { id } = orderItemDto.product;

  const { price } = await this.prisma.product.findUniqueOrThrow({
    where: { id },
  });

  const orderItem: Prisma.OrderItemCreateManyOrderInput = {
    ...orderItemDto,
    productId: id,
    price,
  };
  return orderItem;
}
```

And finally the <mark style="color:blue;">`create()`</mark> method. Note that we <mark style="color:blue;">`connect`</mark> the <mark style="color:blue;">`order`</mark> with an existing <mark style="color:blue;">`user`</mark> but also create <mark style="color:blue;">`orderItems`</mark> when creating the <mark style="color:blue;">`order`</mark>.

```typescript
async create(createOrderDto: CreateOrderDto) {
  const { customer, items } = createOrderDto;

  const itemsWithPrice = await Promise.all(
    items.map((item) => this.createOrderItemWithPrice(item)),
  );

  return this.prisma.order.create({
    data: {
      customer: { connect: customer },
      items: { createMany: { data: itemsWithPrice } },
    },
  });
}
```

<mark style="color:green;">**Commit**</mark> - Implementing order logic
