1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use crate::cents::Cents;
use chrono::{DateTime, Utc};
use serde_json::Value as JsonValue;
use sqlx::executor::{Executor, RefExecutor};
use sqlx::postgres::PgQueryAs;
use sqlx::Postgres;
use uuid::Uuid;

#[derive(Debug, Clone, Copy, PartialEq, sqlx::Type)]
#[sqlx(rename = "order_state")]
pub enum OrderState {
    Created,
    Payed,
    Failed,
    Canceled,
}

#[derive(Debug, PartialEq, sqlx::FromRow)]
pub struct Order {
    pub id: i64,
    pub uuid: Uuid,
    pub origin: String,
    pub locale: String,
    pub state: OrderState,
    pub custom_status: String,
    pub date: DateTime<Utc>,
    pub payment_method: String,
    pub payment_id: String,
    pub payment_meta: JsonValue,
    pub currency: String,
    pub shipping_method: String,
    pub shipping_method_name: String,
    pub shipping: Cents,
    pub tax: Cents,
    pub total: Cents,
    pub email: String,
    pub token: String,
    pub shipment: Option<JsonValue>,
    pub invoice_address_id: i64,
    pub shipping_address_id: i64,
}

pub async fn fetch<'e>(
    id: i64,
    conn: impl RefExecutor<'e, Database = Postgres> + Send + 'e,
) -> Result<Option<Order>, sqlx::Error> {
    sqlx::query_as("SELECT * FROM orders WHERE id = $1")
        .bind(id)
        .fetch_optional(conn)
        .await
}

pub async fn fetch_for_update<'e>(
    id: i64,
    conn: impl RefExecutor<'e, Database = Postgres> + Send + 'e,
) -> Result<Option<Order>, sqlx::Error> {
    sqlx::query_as("SELECT * FROM orders WHERE id = $1 FOR UPDATE")
        .bind(id)
        .fetch_optional(conn)
        .await
}

pub async fn by_payment_for_update<'e>(
    payment_method: &str,
    payment_id: &str,
    conn: impl RefExecutor<'e, Database = Postgres> + Send + 'e,
) -> Result<Option<Order>, sqlx::Error> {
    sqlx::query_as("SELECT * FROM orders WHERE payment_method = $1 AND payment_id = $2 FOR UPDATE")
        .bind(payment_method)
        .bind(payment_id)
        .fetch_optional(conn)
        .await
}

#[derive(Debug)]
pub struct NewOrder<'a> {
    pub uuid: Uuid,
    pub origin: &'a str,
    pub locale: &'a str,
    pub state: OrderState,
    pub custom_status: &'a str,
    pub date: DateTime<Utc>,
    pub payment_method: &'a str,
    pub payment_id: &'a str,
    pub payment_meta: &'a JsonValue,
    pub currency: &'a str,
    pub shipping_method: &'a str,
    pub shipping_method_name: &'a str,
    pub shipping: Cents,
    pub tax: Cents,
    pub total: Cents,
    pub email: &'a str,
    pub token: &'a str,
    pub shipment: Option<&'a JsonValue>,
    pub invoice_address_id: i64,
    pub shipping_address_id: i64,
}

pub async fn insert<'e>(
    order: &NewOrder<'_>,
    conn: impl RefExecutor<'e, Database = Postgres> + Send + 'e,
) -> Result<Order, sqlx::Error> {
    // deconstruct to not miss new properties in the future
    let NewOrder {
        uuid,
        origin,
        locale,
        state,
        custom_status,
        date,
        payment_method,
        payment_id,
        payment_meta,
        currency,
        shipping_method,
        shipping_method_name,
        shipping,
        tax,
        total,
        email,
        token,
        shipment,
        invoice_address_id,
        shipping_address_id,
    } = order;

    sqlx::query_as(
        "
            INSERT INTO orders (
                uuid,
                origin,
                locale,
                state,
                custom_status,
                date,
                payment_method,
                payment_id,
                payment_meta,
                currency,
                shipping_method,
                shipping_method_name,
                shipping,
                tax,
                total,
                email,
                token,
                shipment,
                invoice_address_id,
                shipping_address_id
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18,
                $19, $20
            )
            ON CONFLICT(payment_method, payment_id) DO NOTHING
            RETURNING *
        ",
    )
    .bind(uuid)
    .bind(origin)
    .bind(locale)
    .bind(state)
    .bind(custom_status)
    .bind(date)
    .bind(payment_method)
    .bind(payment_id)
    .bind(payment_meta)
    .bind(currency)
    .bind(shipping_method)
    .bind(shipping_method_name)
    .bind(shipping)
    .bind(tax)
    .bind(total)
    .bind(email)
    .bind(token)
    .bind(shipment)
    .bind(invoice_address_id)
    .bind(shipping_address_id)
    .fetch_one(conn)
    .await
}

impl Order {
    pub async fn update_state(
        &mut self,
        new_state: OrderState,
        conn: impl Executor<Database = Postgres> + Send,
    ) -> Result<(), sqlx::Error> {
        update_order_state(self.id, new_state, conn).await?;
        self.state = new_state;
        Ok(())
    }

    pub async fn update_payment(
        &mut self,
        new_payment_id: &str,
        new_payment_meta: JsonValue,
        conn: impl Executor<Database = Postgres> + Send,
    ) -> Result<(), sqlx::Error> {
        sqlx::query("UPDATE orders SET payment_id = $2, payment_meta = $3 WHERE id = $1")
            .bind(self.id)
            .bind(new_payment_id)
            .bind(&new_payment_meta)
            .execute(conn)
            .await?;
        self.payment_id = new_payment_id.to_string();
        self.payment_meta = new_payment_meta;
        Ok(())
    }

    pub async fn update_custom_status(
        &mut self,
        new_status: &str,
        conn: impl Executor<Database = Postgres> + Send,
    ) -> Result<(), sqlx::Error> {
        sqlx::query("UPDATE invoices SET custom_status = $2 WHERE id = $1")
            .bind(self.id)
            .bind(new_status)
            .execute(conn)
            .await?;
        self.custom_status = new_status.to_string();
        Ok(())
    }
}

pub(crate) async fn update_order_state(
    order_id: i64,
    new_state: OrderState,
    conn: impl Executor<Database = Postgres> + Send,
) -> Result<(), sqlx::Error> {
    sqlx::query("UPDATE orders SET state = $2 WHERE id = $1")
        .bind(order_id)
        .bind(new_state)
        .execute(conn)
        .await?;
    Ok(())
}