@ozdao/martyrs 0.2.557 → 0.2.559

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,225 @@
1
+ import * as QRCode from "qrcode";
2
+ import { m as middlewareIndexFactory } from "./index-_Edcmck_.js";
3
+ import { c as controllerFactory$1 } from "./tickets.controller-B7r0mK-5.js";
4
+ import { O as ObserverNamespaced } from "./core.observer-MZsqaE6F.js";
5
+ import Stripe from "stripe";
6
+ const controllerFactory = (db) => {
7
+ const Payment = db.payment;
8
+ const Wallet = db.wallet;
9
+ db.order;
10
+ const create = async (req, res) => {
11
+ let { amount, positions, userId } = req.body;
12
+ const newPayment = new Payment(req.body);
13
+ await newPayment.save();
14
+ const qrData = `PaymentID:${newPayment._id};Amount:${amount}`;
15
+ const qrCode = await QRCode.toDataURL(qrData);
16
+ res.send({ qrCode, paymentId: newPayment._id });
17
+ };
18
+ const read = async (req, res) => {
19
+ try {
20
+ const paymentes = await Payment.find({}).sort({ createdAt: "desc" }).exec();
21
+ if (!paymentes) {
22
+ return res.status(404).send({ message: "Paymentes not found." });
23
+ }
24
+ res.status(200).send(paymentes);
25
+ } catch (err) {
26
+ res.status(500).send({ message: err.toString() });
27
+ }
28
+ };
29
+ const update = async (req, res) => {
30
+ const session = await db.mongoose.startSession();
31
+ session.startTransaction();
32
+ try {
33
+ const { paymentId, walletId } = req.body;
34
+ const payment = await Payment.findById(paymentId).session(session);
35
+ if (!payment) {
36
+ throw new Error("Payment not found");
37
+ }
38
+ if (payment.status !== "pending") {
39
+ throw new Error("Payment is not in a pending state");
40
+ }
41
+ const wallet = await Wallet.findById(walletId).session(session);
42
+ if (!wallet) {
43
+ throw new Error("Wallet not found");
44
+ }
45
+ if (wallet.amount < payment.amount) {
46
+ throw new Error("Insufficient funds");
47
+ }
48
+ wallet.amount -= payment.amount;
49
+ await wallet.save({ session });
50
+ payment.status = "completed";
51
+ await payment.save({ session });
52
+ await session.commitTransaction();
53
+ res.send("Payment processed successfully");
54
+ } catch (error) {
55
+ await session.abortTransaction();
56
+ res.status(500).send(error.message);
57
+ } finally {
58
+ session.endSession();
59
+ }
60
+ };
61
+ const deletePayment = (req, res) => {
62
+ Payment.findOneAndDelete({ _id: req.params._id }, (err, payment) => {
63
+ if (err) {
64
+ return res.status(500).send({ message: err });
65
+ }
66
+ if (!payment) {
67
+ return res.status(404).send({ message: "Something wrong when deleting payment." });
68
+ }
69
+ res.status(200).send(payment);
70
+ });
71
+ };
72
+ return {
73
+ create,
74
+ read,
75
+ update,
76
+ delete: deletePayment
77
+ };
78
+ };
79
+ class Webhook {
80
+ constructor(app, db, observer, path, handlerMethod, middlewares = []) {
81
+ this.app = app;
82
+ this.db = db;
83
+ this.observer = observer;
84
+ this.app.post(path, [...middlewares, handlerMethod.bind(this)]);
85
+ }
86
+ // Abstract method, must be implemented in derived classes
87
+ handleWebhook(req, res) {
88
+ throw new Error("handleWebhook() must be implemented by subclasses");
89
+ }
90
+ }
91
+ const stripe = new Stripe(process.env.STRIPE_API_KEY ?? "", {
92
+ apiVersion: "2025-04-30.basil"
93
+ });
94
+ function middleware(req, res, next) {
95
+ next();
96
+ }
97
+ class StripeWebhook extends Webhook {
98
+ constructor(app, db, observer, path = "/api/webhook/stripe", handlerMethod = StripeWebhook.prototype.handleWebhook, middlewares = []) {
99
+ super(app, db, observer, path, handlerMethod, [middleware]);
100
+ }
101
+ async handleWebhook(req, res) {
102
+ req.headers["stripe-signature"];
103
+ try {
104
+ const payload = req.body;
105
+ const payloadString = JSON.stringify(payload, null, 2);
106
+ const secret = process.env.STRIPE_WEBHOOK_SECRET;
107
+ const header = stripe.webhooks.generateTestHeaderString({
108
+ payload: payloadString,
109
+ secret
110
+ });
111
+ const event = stripe.webhooks.constructEvent(payloadString, header, secret);
112
+ this.observer.notify(event.type, event.data.object);
113
+ } catch (err) {
114
+ console.log(`Error verifying Stripe webhook signature: ${err.message}`);
115
+ return res.status(400).send(`Webhook Error: ${err.message}`);
116
+ }
117
+ res.sendStatus(200);
118
+ }
119
+ }
120
+ const RoutesPayments = (function(app, db, origins, publicPath) {
121
+ const observer = new ObserverNamespaced();
122
+ new StripeWebhook(app, db, observer);
123
+ const controller = controllerFactory(db);
124
+ console.log("payments ticket", publicPath);
125
+ const controllerTickets = controllerFactory$1(db, publicPath);
126
+ middlewareIndexFactory(db);
127
+ observer.subscribe("checkout.session.completed", async (paymentIntent) => {
128
+ try {
129
+ const event = await db.event.findOne({ _id: paymentIntent.metadata.product });
130
+ if (!event) {
131
+ console.error("Event not found:", paymentIntent.metadata.product);
132
+ return;
133
+ }
134
+ const ticketType = event.ticketsTypes.find((type) => type.name === paymentIntent.metadata.ticketType);
135
+ if (!ticketType) {
136
+ console.error("Ticket type not found:", paymentIntent.metadata.ticketType);
137
+ return;
138
+ }
139
+ const quantity = paymentIntent.amount_total / (ticketType.price * 100);
140
+ console.log("Purchase details:");
141
+ console.log("Email:", paymentIntent.customer_details.email);
142
+ console.log("Name:", paymentIntent.customer_details.name);
143
+ console.log("Event ID:", paymentIntent.metadata.eventId);
144
+ console.log("Ticket Type:", ticketType.name);
145
+ console.log("Quantity:", quantity);
146
+ let ticketData = {
147
+ name: paymentIntent.customer_details.name,
148
+ email: paymentIntent.customer_details.email,
149
+ target: paymentIntent.metadata.product,
150
+ type: "event",
151
+ seat: ticketType.name,
152
+ quantity,
153
+ price: ticketType.price
154
+ };
155
+ await controllerTickets.saveAndSendTicket(ticketData);
156
+ } catch (error) {
157
+ console.error("Error processing checkout session:", error);
158
+ }
159
+ });
160
+ app.get("/api/payments/read", controller.read);
161
+ app.post("/api/payments/create", controller.create);
162
+ app.post("/api/payments/update", controller.update);
163
+ app.delete("/api/payments/delete", controller.delete);
164
+ });
165
+ const ModelPayment = (db) => {
166
+ const PaymentSchema = new db.mongoose.Schema(
167
+ {
168
+ data: {
169
+ type: Object
170
+ },
171
+ currency: {
172
+ type: String
173
+ },
174
+ status: {
175
+ type: String
176
+ },
177
+ customer: {
178
+ type: db.mongoose.Schema.Types.ObjectId,
179
+ ref: "User"
180
+ },
181
+ creator: {
182
+ type: db.mongoose.Schema.Types.ObjectId,
183
+ ref: "User"
184
+ }
185
+ },
186
+ {
187
+ timestamps: {
188
+ currentTime: () => Date.now()
189
+ }
190
+ }
191
+ );
192
+ const Payment = db.mongoose.model("Payment", PaymentSchema);
193
+ return Payment;
194
+ };
195
+ function initializePayments(app, db, wss, origins, publicPath) {
196
+ db.payment = ModelPayment(db);
197
+ if (app) {
198
+ RoutesPayments(app, db, origins, publicPath);
199
+ }
200
+ }
201
+ const models = {
202
+ // ModelWallet,
203
+ ModelPayment
204
+ // ModelReward,
205
+ };
206
+ const routes = {
207
+ RoutesPayments
208
+ // RoutesRewards,
209
+ };
210
+ const controllers = {
211
+ FactoryPayments: controllerFactory
212
+ };
213
+ const wallet_server = {
214
+ initialize: initializePayments,
215
+ models,
216
+ routes,
217
+ controllers
218
+ };
219
+ export {
220
+ controllers,
221
+ wallet_server as default,
222
+ initializePayments as initialize,
223
+ models,
224
+ routes
225
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ozdao/martyrs",
3
- "version": "0.2.557",
3
+ "version": "0.2.559",
4
4
  "description": "Fullstack framework focused on user experience and ease of development.",
5
5
  "author": "OZ DAO <hello@ozdao.dev>",
6
6
  "license": "GPL-3.0-or-later",
@@ -1,15 +1,15 @@
1
1
  import FactoryPayments from './controllers/factories/payments.factory.js';
2
2
  import RoutesPayments from './controllers/routes/payments.routes.js';
3
- import RoutesRewards from './controllers/routes/rewards.routes.js';
3
+ // import RoutesRewards from './controllers/routes/rewards.routes.js';
4
4
  import ModelPayment from './models/payment.model.js';
5
- import ModelReward from './models/reward.model.js';
6
- import ModelWallet from './models/wallet.model.js';
5
+ // import ModelReward from './models/reward.model.js';
6
+ // import ModelWallet from './models/wallet.model.js';
7
7
  // Initialization function for setting up the module within the application
8
- function initializePayments(app, db, wss, wdmClient, origins, publicPath) {
8
+ function initializePayments(app, db, wss, origins, publicPath) {
9
9
  // Setup models in the database object
10
- db.wallet = ModelWallet(db);
10
+ // db.wallet = ModelWallet(db);
11
11
  db.payment = ModelPayment(db);
12
- db.reward = ModelReward(db);
12
+ // db.reward = ModelReward(db);
13
13
  // Setup routes if the app object is provided
14
14
  if (app) {
15
15
  RoutesPayments(app, db, origins, publicPath);
@@ -17,13 +17,13 @@ function initializePayments(app, db, wss, wdmClient, origins, publicPath) {
17
17
  }
18
18
  }
19
19
  export const models = {
20
- ModelWallet,
20
+ // ModelWallet,
21
21
  ModelPayment,
22
- ModelReward,
22
+ // ModelReward,
23
23
  };
24
24
  export const routes = {
25
25
  RoutesPayments,
26
- RoutesRewards,
26
+ // RoutesRewards,
27
27
  };
28
28
  export const controllers = {
29
29
  FactoryPayments,