Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rent fix #228

Merged
merged 5 commits into from
Apr 25, 2024
Merged

Rent fix #228

merged 5 commits into from
Apr 25, 2024

Conversation

nsavinda
Copy link
Member

@nsavinda nsavinda commented Apr 25, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive payment processing capability across multiple controllers and views, including authorization and data retrieval.
    • Added a new payment interface for customers, enabling direct payment functionalities with detailed order information.
    • Implemented a stored procedure to automate payment creation and management for rent orders.
  • Enhancements

    • Updated views to reflect payment information more accurately, such as displaying paid amounts instead of total amounts.
    • Enhanced the payment process with a new trigger that updates payment statuses automatically in the database.
  • Documentation

    • Added comments and updated documentation across various files to reflect changes in payment processing and data handling.

Copy link
Contributor

coderabbitai bot commented Apr 25, 2024

Walkthrough

This update introduces comprehensive enhancements across the application, focusing on payment processing and order management. New functionalities include a method for full payment processing, updates to order views, and the integration of payment-related database procedures and triggers. These changes aim to streamline transactions and improve the user interface for payment handling.

Changes

File Path Change Summary
app/controllers/API/Pay.php
app/controllers/MyOrders.php
Added fullPay method for handling full payment processes.
app/models/Payment.php
database/procedures/CreatePaymentForRent.sql
Introduced functions and procedures for creating payment entries and handling rent payments.
app/views/.../fullpay.view.php
app/views/.../orderlist.view.php
app/views/customer/orders.view.php
app/views/rental/components/orderlist.view.php
Enhanced views to support new payment functionalities and display updates.
database/procedures/ProcessCartToRentOrders.sql
database/wanderlust nir.sql
Modified and added SQL procedures and triggers for payment processing and data management.
public/assets/scss/wl/dashboard/index.scss Added import statement for Google Fonts.

Poem

🐇💻✨
In the land of code where the bits align,
A rabbit hopped through, making changes fine.
With a click and a clack, the payments flow,
Orders update, and the databases grow.
Celebrate we do, for progress is made,
In this digital burrow where plans are laid.
🌟🎉🐰


Recent Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 52abb82 and 6dde6f9.
Files ignored due to path filters (2)
  • public/reports/income_report_6628f5e8b432b.pdf is excluded by !**/*.pdf
  • public/reports/income_report_662a0b180f830.pdf is excluded by !**/*.pdf
Files selected for processing (13)
  • app/controllers/API/Pay.php (1 hunks)
  • app/controllers/MyOrders.php (1 hunks)
  • app/models/Payment.php (1 hunks)
  • app/views/customer/components/fullpay.view.php (1 hunks)
  • app/views/customer/components/orderlist.view.php (2 hunks)
  • app/views/customer/orders.view.php (1 hunks)
  • app/views/customer/rent.view.php (1 hunks)
  • app/views/rental/components/orderlist.view.php (1 hunks)
  • database/procedures/ ProcessCartToRentOrders .sql (1 hunks)
  • database/procedures/CreatePaymentForRent.sql (1 hunks)
  • database/triggers/AfterPaymentStatusCompleted.sql (1 hunks)
  • database/wanderlust nir.sql (14 hunks)
  • public/assets/scss/wl/dashboard/index.scss (1 hunks)
Files not reviewed due to errors (1)
  • database/procedures/ ProcessCartToRentOrders .sql (no review received)
Additional comments not posted (16)
app/views/customer/components/orderlist.view.php (1)

37-39: The addition of the 'Pay' button for orders with 'rented' status aligns well with the PR objectives to enhance the payment process.

public/assets/scss/wl/dashboard/index.scss (1)

260-260: Verify the usage of the imported Google Fonts to ensure they do not significantly impact page load times.

app/views/rental/components/orderlist.view.php (1)

93-95: Replace total amount display with paid amount.

This change aligns with the PR's objective to enhance the payment processing system by providing clearer information on what has been paid per order.

app/views/customer/orders.view.php (1)

286-338: Implement full payment functionality using PayHere.

The integration with PayHere for handling full payments is a significant enhancement in line with the PR's objectives. Ensure thorough testing, especially around the AJAX calls and payment gateway interactions, to prevent any issues during payment processing.

app/views/customer/rent.view.php (1)

379-380: Simplify setting of type variable to 'all'.

This change simplifies the code by directly setting the type variable, reducing unnecessary DOM interactions. Ensure that this change does not affect other parts of the application that might rely on the type variable being dynamically set.

database/wanderlust nir.sql (11)

102-127: The CreatePaymentForRent procedure is well-structured. However, consider adding error handling for SQL operations to ensure robustness.


839-839: Ensure that the data inserted into the cart table is consistent with the application's requirements and validate the dates for logical correctness.


3934-3944: Adding new payment entries is fine, but ensure that negative amounts (as seen in line 3941) are handled correctly in the application logic.


4084-4084: When updating the rent table, ensure that the status and payment amounts are consistent and correctly reflect the transaction's state.


4217-4257: The rent_complaint table and its trigger generate_complaint_no are correctly set up. Ensure that the complaint number generation logic uniquely identifies each complaint.


4460-4469: Ensure that the data inserted into the rent_item table is accurate and that the relationships between tables are maintained.


4540-4568: The trigger AfterPaymentInsert should ensure that the total paid amount calculation is accurate and that updates to the rent table are transactionally safe.


4619-4624: Verify that the status updates in the rent_request table are triggered correctly and reflect the actual rental status.


5115-5119: Adding a primary key to the rent_complaint table is crucial for database integrity. Ensure that all necessary indexes are created to optimize query performance.


5173-5173: The AUTO_INCREMENT change for the cart table is noted. Ensure that this change is reflected in the application logic where IDs are assumed or pre-calculated.


5215-5251: AUTO_INCREMENT adjustments across multiple tables are noted. Ensure these changes are synchronized with any data import or migration scripts to avoid conflicts.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Out of diff range and nitpick comments (2)
database/wanderlust nir.sql (2)

6-6: Ensure the generation time is updated dynamically if this script is auto-generated.


3946-3986: The trigger AfterPaymentStatusCompleted is well-implemented. Ensure that the cursor and loop operations are optimized for performance, especially if the rent_pay table grows significantly.

@@ -713,6 +740,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ProcessCartToRentOrders` (IN `customerID` I
) AND equipment.rentalservice_id = currentRentalServiceID;


SET rentAmount = rentAmount * 0.20; -- 20% booking fee
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The calculation of the booking fee is hardcoded as 20%. Consider making this configurable through a parameter or a settings table to enhance flexibility.

Comment on lines +23 to +27
public function fullPayRent(array $data) {

$q = 'CALL CreatePaymentForRent(:rent_id)';
return $this->query($q, $data);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider implementing error handling and transaction management for the fullPayRent method to ensure robustness in payment processing.


<tr>
<td>Amount Due</td>
<td> <b> <?= number_format($rent->total - $rent->paid_amount, 2) ?> </b></td>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move the calculation of Amount Due to the backend to maintain separation of concerns and ensure data integrity.

Comment on lines +3 to +31
CREATE PROCEDURE `CreatePaymentForRent`(
IN rent_id INT
)
BEGIN
DECLARE lastPaymentID INT;
DECLARE reference_number VARCHAR(10);
DECLARE amount DECIMAL(10, 2);

-- Fetching the outstanding amount for the given rent ID
SELECT total - paid_amount INTO amount FROM rent WHERE id = rent_id;

-- Insert a new payment entry
INSERT INTO payment (amount, status) VALUES (amount, 'pending');

-- Get the ID of the last inserted payment
SET lastPaymentID = LAST_INSERT_ID();

-- Create a reference number using the last payment ID
SET reference_number = CONCAT('RNT', LPAD(lastPaymentID, 5, '0'));

-- Update the payment with the reference number
UPDATE payment SET reference_number = reference_number WHERE id = lastPaymentID;

-- Insert into rent_pay table
INSERT INTO rent_pay (rent_id, payment_id, amount) VALUES (rent_id, lastPaymentID, amount);

-- Select the reference number and total amount for the output
SELECT reference_number AS orderID, amount AS totalAmount;
END $$
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure to start a transaction at the beginning of the procedure and commit it at the end to maintain data integrity across the inserts and updates.

Comment on lines +44 to +51
public function fullPay(string $a = '', string $b = '', string $c = ''):void {
AuthorizationMiddleware::authorize(['customer']);

$rent = new RentModel;
$data['rent'] = $rent->first(['id' => $a]);

$this->view('customer/components/fullpay', $data);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add error handling for cases where rent data might not be found before rendering the view in the fullPay method.

Comment on lines +3 to +43
CREATE TRIGGER `AfterPaymentStatusCompleted`
AFTER UPDATE ON `payment`
FOR EACH ROW
BEGIN
-- Declare variables and cursor at the beginning of the block
DECLARE total_paid DECIMAL(10,2);
DECLARE done INT DEFAULT FALSE;
DECLARE rent_id_var INT;
DECLARE rent_cursor CURSOR FOR
SELECT rent_id FROM rent_pay WHERE payment_id = NEW.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

-- Check if the payment status has been updated to 'completed'
IF NEW.status = 'completed' AND OLD.status <> 'completed' THEN

-- Open the cursor
OPEN rent_cursor;

-- Loop through all rent IDs fetched by the cursor
rent_loop: LOOP
FETCH rent_cursor INTO rent_id_var;
IF done THEN
LEAVE rent_loop;
END IF;

-- Calculate the total paid amount for the specific rent
SELECT SUM(rp.amount) INTO total_paid
FROM rent_pay rp
JOIN payment p ON rp.payment_id = p.id
WHERE rp.rent_id = rent_id_var AND p.status = 'completed';

-- Update the paid_amount in the rent table for each affected rent
UPDATE rent
SET paid_amount = total_paid
WHERE id = rent_id_var;
END LOOP;

-- Close the cursor
CLOSE rent_cursor;
END IF;
END$$
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize the SQL queries within the trigger to reduce the potential performance overhead from using a cursor and multiple updates.

Comment on lines +99 to +137
public function fullPay(string $a = '', string $b = '', string $c = ''):void {


AuthorizationMiddleware::authorize(['customer']);

$response = new JSONResponse();

$rent = new RentModel;
$payment = new PaymentModel;
$data['rent'] = $rent->first(['id' => $a]);

$data['payment'] = $payment ->fullPayRent(['rent_id' => $a])[0];

$merchant_id = MERCHANT_ID;
$merchant_secret = MERCHANT_SECRET;
// $amount = $data['rent']->total - $data['rent']->paid_amount;
$amount = number_format($data['rent']->total - $data['rent']->paid_amount, 2, '.', '');

$hash = strtoupper(
md5(
$merchant_id .
$data['payment']->orderID .
// number_format($order->totalAmount, 2, '.', '') .
$amount .
'LKR' .
strtoupper(md5($merchant_secret))
)
);

$data['hash'] = $hash;
$data['merchant_id'] = $merchant_id;
$data['orderId'] = $data['payment']->orderID;
$data['amount'] = $amount;

$response->data($data)->statusCode(200)->send();




Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean up commented-out code and ensure all necessary error checks are in place in the fullPay method to maintain code clarity and robustness.

@nsavinda nsavinda merged commit 999f65c into dev Apr 25, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant