Changes between Initial Version and Version 1 of Transactions


Ignore:
Timestamp:
09/11/25 03:15:33 (13 hours ago)
Author:
141515
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Transactions

    v1 v1  
     1== Страна за трансакции
     2
     3Првенствено, за креирање на договор имавме
     4{{{
     5pool.query(
     6            "INSERT INTO agreement (A_Id, Price, Status, Datum, Tax_Nr, VIN, EMBG) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",
     7            [A_Id, Price, Status, Datum, Tax_Nr, VIN, EMBG],
     8            (error, results) => {
     9                if (error) {
     10                    reject(new Error("Not able to create agreement."));
     11                }
     12                if (results && results.rows) {
     13                    // Update vehicle status to sold
     14                    pool.query(
     15                        "UPDATE vehicle SET status = false WHERE vin = $1",
     16                        [VIN],
     17                        (updateError, updateResults) => {
     18                            if (updateError) {
     19                                console.error("Error updating vehicle status:", updateError);
     20                            }
     21                        }
     22                    );
     23                    resolve(`Agreement created successfully.`);
     24                } else {
     25                    reject(new Error("Not able to create agreement."));
     26                }
     27            }
     28        );
     29}}}
     30
     31Меѓутоа сега со трансакции за да се осигураме дека возилото постои, возилото е достапно, и да се постави како продадено и тргне од продажба доколку е креиран договорот успешно имаме:
     32{{{
     33pool.connect((err, client, done) => {
     34            if (err) {
     35                console.error('Error getting client from pool:', err);
     36                reject(err);
     37                return;
     38            }
     39
     40            client.query('BEGIN', (beginError) => {
     41                if (beginError) {
     42                    console.error('Begin transaction error:', beginError);
     43                    done();
     44                    reject(beginError);
     45                    return;
     46                }
     47
     48                // First, validate that the vehicle exists and is available
     49                client.query(
     50                    "SELECT vin, status, price FROM vehicle WHERE vin = $1 AND tax_nr = $2",
     51                    [VIN, Tax_Nr],
     52                    (validateError, validateResults) => {
     53                        if (validateError) {
     54                            console.error('Vehicle validation error:', validateError);
     55                            client.query('ROLLBACK', () => {
     56                                done();
     57                            });
     58                            reject(new Error("Error validating vehicle."));
     59                            return;
     60                        }
     61
     62                        if (!validateResults.rows || validateResults.rows.length === 0) {
     63                            console.error('Vehicle not found or not owned by dealership');
     64                            client.query('ROLLBACK', () => {
     65                                done();
     66                            });
     67                            reject(new Error("Vehicle not found or you don't have permission to sell it."));
     68                            return;
     69                        }
     70
     71                        const vehicle = validateResults.rows[0];
     72                        if (vehicle.status === false) {
     73                            console.error('Vehicle is already sold');
     74                            client.query('ROLLBACK', () => {
     75                                done();
     76                            });
     77                            reject(new Error("Vehicle is already sold."));
     78                            return;
     79                        }
     80
     81                        // Validate that the agreement price matches vehicle price
     82                        if (parseFloat(Price) !== parseFloat(vehicle.price)) {
     83                            console.error('Agreement price does not match vehicle price');
     84                            client.query('ROLLBACK', () => {
     85                                done();
     86                            });
     87                            reject(new Error("Agreement price must match vehicle price."));
     88                            return;
     89                        }
     90
     91                        // Insert agreement
     92                        client.query(
     93                            "INSERT INTO agreement (A_Id, Price, Status, Datum, Tax_Nr, VIN, EMBG) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",
     94                            [A_Id, Price, Status, Datum, Tax_Nr, VIN, EMBG],
     95                            (error, results) => {
     96                                if (error) {
     97                                    console.error('Agreement insert error:', error);
     98                                    client.query('ROLLBACK', () => {
     99                                        done();
     100                                    });
     101                                    reject(new Error("Not able to create agreement."));
     102                                    return;
     103                                }
     104
     105                                if (results && results.rows) {
     106                                    console.log('Agreement inserted successfully');
     107                                   
     108                                    // Update vehicle status to sold
     109                                    client.query(
     110                                        "UPDATE vehicle SET status = false WHERE vin = $1",
     111                                        [VIN],
     112                                        (updateError, updateResults) => {
     113                                            if (updateError) {
     114                                                console.error('Vehicle update error:', updateError);
     115                                                client.query('ROLLBACK', () => {
     116                                                    done();
     117                                                });
     118                                                reject(new Error("Error updating vehicle status."));
     119                                                return;
     120                                            }
     121
     122                                            console.log('Vehicle status updated successfully');
     123                                           
     124                                            // Commit the transaction
     125                                            client.query('COMMIT', (commitError) => {
     126                                                done();
     127                                                if (commitError) {
     128                                                    console.error('Commit error:', commitError);
     129                                                    reject(commitError);
     130                                                } else {
     131                                                    console.log('Agreement transaction committed successfully');
     132                                                    resolve(`Agreement created successfully.`);
     133                                                }
     134                                            });
     135                                        }
     136                                    );
     137                                } else {
     138                                    client.query('ROLLBACK', () => {
     139                                        done();
     140                                    });
     141                                    reject(new Error("Not able to create agreement."));
     142                                }
     143                            }
     144                        );
     145                    }
     146                );
     147            });
     148        });
     149}}}
     150
     151
     152Исто и за Договор, претходно имавме:
     153{{{
     154pool.query(
     155            "INSERT INTO payment (Bank, IBAN, Amount, EMBG, A_Id) VALUES ($1, $2, $3, $4, $5) RETURNING *",
     156            [Bank, IBAN, Amount, EMBG, A_Id],
     157            (error, results) => {
     158                if (error) {
     159                    reject(new Error("Not able to create payment."));
     160                }
     161                if (results && results.rows) {
     162                    resolve(`Payment created successfully.`);
     163                } else {
     164                    reject(new Error("Not able to create payment."));
     165                }
     166            }
     167        );
     168}}}
     169
     170Сега со трансакции се осигуруваме дали постои договор и дали точниот клиент е асоциран со него, дали е валиден договорот, проверуваме да не случано веќе е извршено уплаќање за него, и се означува како платен доколку е успешно извршена уплата.
     171{{{
     172pool.connect((err, client, done) => {
     173            if (err) {
     174                console.error('Error getting client from pool:', err);
     175                reject(err);
     176                return;
     177            }
     178
     179            client.query('BEGIN', (beginError) => {
     180                if (beginError) {
     181                    console.error('Begin transaction error:', beginError);
     182                    done();
     183                    reject(beginError);
     184                    return;
     185                }
     186
     187                // First, validate that the agreement exists and belongs to the client
     188                client.query(
     189                    `SELECT a.a_id, a.price as agreement_price, a.status as agreement_status,
     190                            v.vin, v.make, v.model, v.p_year, v.color,
     191                            c.c_name, c.embg
     192                     FROM agreement a
     193                     JOIN vehicle v ON a.vin = v.vin
     194                     JOIN client c ON a.embg = c.embg
     195                     WHERE a.a_id = $1 AND a.embg = $2`,
     196                    [A_Id, EMBG],
     197                    (validateError, validateResults) => {
     198                        if (validateError) {
     199                            console.error('Agreement validation error:', validateError);
     200                            client.query('ROLLBACK', () => {
     201                                done();
     202                            });
     203                            reject(new Error("Error validating agreement."));
     204                            return;
     205                        }
     206
     207                        if (!validateResults.rows || validateResults.rows.length === 0) {
     208                            console.error('Agreement not found or not owned by client');
     209                            client.query('ROLLBACK', () => {
     210                                done();
     211                            });
     212                            reject(new Error("Agreement not found or you don't have permission to pay for it."));
     213                            return;
     214                        }
     215
     216                        const agreement = validateResults.rows[0];
     217                       
     218                        // Validate that the agreement is active
     219                        if (agreement.agreement_status !== true) {
     220                            console.error('Agreement is not active');
     221                            client.query('ROLLBACK', () => {
     222                                done();
     223                            });
     224                            reject(new Error("Agreement is not active."));
     225                            return;
     226                        }
     227
     228                        // Validate that the payment amount matches agreement price
     229                        if (parseFloat(Amount) !== parseFloat(agreement.agreement_price)) {
     230                            console.error('Payment amount does not match agreement price');
     231                            client.query('ROLLBACK', () => {
     232                                done();
     233                            });
     234                            reject(new Error("Payment amount must match agreement price."));
     235                            return;
     236                        }
     237
     238                        // Check if payment already exists for this agreement
     239                        client.query(
     240                            "SELECT p_id FROM payment WHERE a_id = $1",
     241                            [A_Id],
     242                            (checkError, checkResults) => {
     243                                if (checkError) {
     244                                    console.error('Payment check error:', checkError);
     245                                    client.query('ROLLBACK', () => {
     246                                        done();
     247                                    });
     248                                    reject(new Error("Error checking existing payments."));
     249                                    return;
     250                                }
     251
     252                                if (checkResults.rows && checkResults.rows.length > 0) {
     253                                    console.error('Payment already exists for this agreement');
     254                                    client.query('ROLLBACK', () => {
     255                                        done();
     256                                    });
     257                                    reject(new Error("Payment already exists for this agreement."));
     258                                    return;
     259                                }
     260
     261                                // Insert payment
     262                                client.query(
     263                                    "INSERT INTO payment (Bank, IBAN, Amount, EMBG, A_Id) VALUES ($1, $2, $3, $4, $5) RETURNING *",
     264                                    [Bank, IBAN, Amount, EMBG, A_Id],
     265                                    (error, results) => {
     266                                        if (error) {
     267                                            console.error('Payment insert error:', error);
     268                                            client.query('ROLLBACK', () => {
     269                                                done();
     270                                            });
     271                                            reject(new Error("Not able to create payment."));
     272                                            return;
     273                                        }
     274
     275                                        if (results && results.rows) {
     276                                            console.log('Payment inserted successfully');
     277                                           
     278                                            // Optionally update agreement status to paid
     279                                            client.query(
     280                                                "UPDATE agreement SET status = false WHERE a_id = $1",
     281                                                [A_Id],
     282                                                (updateError, updateResults) => {
     283                                                    if (updateError) {
     284                                                        console.error('Agreement status update error:', updateError);
     285                                                        // Don't fail the transaction for this, just log it
     286                                                        console.log('Payment created but agreement status not updated');
     287                                                    } else {
     288                                                        console.log('Agreement status updated to paid');
     289                                                    }
     290
     291                                                    // Commit the transaction
     292                                                    client.query('COMMIT', (commitError) => {
     293                                                        done();
     294                                                        if (commitError) {
     295                                                            console.error('Commit error:', commitError);
     296                                                            reject(commitError);
     297                                                        } else {
     298                                                            console.log('Payment transaction committed successfully');
     299                                                            resolve(`Payment created successfully.`);
     300                                                        }
     301                                                    });
     302                                                }
     303                                            );
     304                                        } else {
     305                                            client.query('ROLLBACK', () => {
     306                                                done();
     307                                            });
     308                                            reject(new Error("Not able to create payment."));
     309                                        }
     310                                    }
     311                                );
     312                            }
     313                        );
     314                    }
     315                );
     316            });
     317        });
     318}}}