Skip to content
This repository has been archived by the owner on Dec 10, 2024. It is now read-only.

Commit

Permalink
Merge pull request #85 from igrowker/Alina_Donations
Browse files Browse the repository at this point in the history
Fixed endpoints and added getMaterialDonationById and updateMaterialD…
  • Loading branch information
fhuayller authored Dec 5, 2024
2 parents 1d60e46 + 2c362f0 commit 83ec89f
Show file tree
Hide file tree
Showing 7 changed files with 227 additions and 112 deletions.
81 changes: 53 additions & 28 deletions src/controllers/donationsRequestController.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,66 @@
import { Request, Response } from 'express';
import DonationRequest from '../models/donationsRequest';
import { Request, Response } from "express";
import DonationRequest from "../models/donationsRequest";

export const createDonationRequest = async (req: Request, res: Response) => {
try {
const { title, description, imageUrl, monetaryDonation, cuantityDonation, donationNumber } = req.body;
const {
title,
description,
imageUrl,
isMonetaryDonation,
cuantityDonation,
donationNumber,
} = req.body;

if (!req.user) {
return res.status(400).json({ message: 'User not authenticated' });
return res.status(400).json({ message: "User not authenticated" });
}

const refugee_id = req.user.id;

if (!title || !description || !refugee_id || typeof monetaryDonation !== 'boolean') {
return res.status(400).json({ message: 'Missing required fields' });
if (
!title ||
!description ||
!refugee_id ||
typeof isMonetaryDonation !== "boolean"
) {
return res.status(400).json({ message: "Missing required fields" });
}

const donationRequest = new DonationRequest({
title,
description,
imageUrl: imageUrl ? imageUrl : "https://e7.pngegg.com/pngimages/142/119/png-clipart-cat-paw-dog-paw-prints-animals-pet-thumbnail.png",
imageUrl: imageUrl
? imageUrl
: "https://e7.pngegg.com/pngimages/142/119/png-clipart-cat-paw-dog-paw-prints-animals-pet-thumbnail.png",
refugee_id: refugee_id,
monetaryDonation,
targetAmountMoney: monetaryDonation ? cuantityDonation : undefined,
targetItemsCount: !monetaryDonation ? donationNumber : undefined,
isMonetaryDonation,
targetAmountMoney: isMonetaryDonation ? cuantityDonation : undefined,
targetItemsCount: !isMonetaryDonation ? donationNumber : undefined,
});

await donationRequest.save();
console.log()
res.status(201).json({ message: 'Donation request created successfully', donationRequest });
console.log();
res
.status(201)
.json({
message: "Donation request created successfully",
donationRequest,
});
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Error creating donation request', error });
res.status(500).json({ message: "Error creating donation request", error });
}
};


export const getAllDonationRequests = async (req: Request, res: Response) => {
try {
const donationRequests = await DonationRequest.find().populate('donationId');
const donationRequests = await DonationRequest.find().populate(
"donationId"
);
res.status(200).json({ donationRequests });
} catch (error) {
res.status(500).json({ message: 'Error in the request', error });
res.status(500).json({ message: "Error in the request", error });
}
};

Expand All @@ -51,37 +71,42 @@ export const deleteDonationRequest = async (req: Request, res: Response) => {
const deletedRequest = await DonationRequest.findByIdAndDelete(id);

if (!deletedRequest) {
return res.status(404).json({ message: 'Request not found' });
return res.status(404).json({ message: "Request not found" });
}

res.status(200).json({ message: 'Deleted successfully', deletedRequest });
res.status(200).json({ message: "Deleted successfully", deletedRequest });
} catch (error) {
res.status(500).json({ message: 'Error in the request', error });
res.status(500).json({ message: "Error in the request", error });
}
};

export const updateDonationRequestStatus = async (req: Request, res: Response) => {
export const updateDonationRequestStatus = async (
req: Request,
res: Response
) => {
try {
const { id } = req.params;
const { status } = req.body;

const validStatuses = ['active', 'completed', 'canceled'];
const validStatuses = ["active", "completed", "canceled"];
if (!validStatuses.includes(status)) {
return res.status(400).json({ message: 'Invalid status value' });
return res.status(400).json({ message: "Invalid status value" });
}

const updatedRequest = await DonationRequest.findByIdAndUpdate(
id,
{ status },
{ new: true }
{ new: true }
);

if (!updatedRequest) {
return res.status(404).json({ message: 'Request not found' });
return res.status(404).json({ message: "Request not found" });
}

res.status(200).json({ message: 'Status updated successfully', updatedRequest });
res
.status(200)
.json({ message: "Status updated successfully", updatedRequest });
} catch (error) {
res.status(500).json({ message: 'Error updating status', error });
res.status(500).json({ message: "Error updating status", error });
}
};
};
81 changes: 75 additions & 6 deletions src/controllers/materialDonation.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,91 @@
import { Request, Response } from 'express';
import MaterialDonation from '../models/materialDonationModel';
import { Request, Response } from "express";
import MaterialDonation from "../models/materialDonationModel";

export const createMaterialDonation = async (req: Request, res: Response) => {
try {
const { id, name, quantity, description, materialStatus, donation_request_id } = req.body;
const {
id,
name,
user_id,
quantity,
description,
materialStatus,
donation_request_id,
} = req.body;

const materialDonation = new MaterialDonation({
id,
name,
user_id,
quantity,
description,
materialStatus,
donation_request_id,
});

await materialDonation.save();
res.status(201).json({ message: 'Donación de material creada exitosamente', materialDonation });
res.status(201).json({
message: "Donación de material creada exitosamente",
materialDonation,
});
} catch (error) {
res
.status(500)
.json({ message: "Error al crear la donación de material", error });
}
};

export const getMaterialDonationsByUser = async (
req: Request,
res: Response
) => {
try {
const { user_id } = req.params;

const materialDonations = await MaterialDonation.find({ user_id });

res.status(200).json({
message: "Donaciones obtenidas exitosamente",
materialDonations,
});
} catch (error) {
res.status(500).json({ message: 'Error al crear la donación de material', error });
res.status(500).json({
message: "Error al obtener las donaciones",
error,
});
}
};

export const updateMaterialDonationQuantity = async (
req: Request,
res: Response
) => {
try {
const { id } = req.params;
const { quantity } = req.body;

if (quantity === undefined || quantity < 0) {
return res.status(400).json({ message: "Cantidad inválida" });
}

const updatedMaterialDonation = await MaterialDonation.findByIdAndUpdate(
id,
{ quantity },
{ new: true }
);

if (!updatedMaterialDonation) {
return res.status(404).json({ message: "Donación no encontrada" });
}

res.status(200).json({
message: "Cantidad actualizada exitosamente",
materialDonation: updatedMaterialDonation,
});
} catch (error) {
res.status(500).json({
message: "Error al actualizar la cantidad",
error,
});
}
};
};
71 changes: 35 additions & 36 deletions src/controllers/paymentController.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,39 @@
import { Request, Response } from 'express';
import Stripe from 'stripe';
import dotenv from 'dotenv'
import { Request, Response } from "express";
import Stripe from "stripe";
import dotenv from "dotenv";

dotenv.config();
export const createSession = async (req: Request, res: Response) => {

const {title, description, moneyAmount, refugee_id, user_id} = req.body;
const stripe = new Stripe(process.env.STRIPE!)
try {
const session = await stripe.checkout.sessions.create({
line_items: [
{
price_data: {
currency: 'eur',
product_data: {
name: title,
description: description,
},
unit_amount: moneyAmount,
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'http://localhost:5173/donation-success',
cancel_url: 'http://localhost:5173/donation-cancel',
metadata: {
refugee_id: refugee_id,
user_id: req.user?.id || "unknown_user",
}
});
const { title, description, moneyAmount, refugee_id, user_id } = req.body;
const stripe = new Stripe(process.env.STRIPE!);
try {
const session = await stripe.checkout.sessions.create({
line_items: [
{
price_data: {
currency: "eur",
product_data: {
name: title,
description: description,
},
unit_amount: moneyAmount,
},
quantity: 1,
},
],
mode: "payment",
success_url: "http://localhost:5173/donation-success",
cancel_url: "http://localhost:5173/donation-cancel",
metadata: {
refugee_id: refugee_id,
user_id: req.user?.id || "unknown_user",
},
});

// Devolver la sesión creada
res.status(201).json({ message: 'Session created successfully', session });
} catch (error) {
console.error('Error creando la sesión:', error);
res.status(500).json({ message: 'Error creating session', error });
}
};
// Devolver la sesión creada
res.status(201).json({ message: "Session created successfully", session });
} catch (error) {
console.error("Error creando la sesión:", error);
res.status(500).json({ message: "Error creating session", error });
}
};
Loading

0 comments on commit 83ec89f

Please sign in to comment.