Skip to content
This repository has been archived by the owner on May 6, 2022. It is now read-only.

Commit

Permalink
fix: 🚀 Fixed currencies
Browse files Browse the repository at this point in the history
Customer had no custom currency, thus added.

No
  • Loading branch information
Tolfx committed Mar 7, 2022
1 parent 9661abd commit e5a49fc
Show file tree
Hide file tree
Showing 13 changed files with 107 additions and 21 deletions.
9 changes: 8 additions & 1 deletion src/Database/Models/Customers/Customer.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Default_Language, MongoDB_URI } from "../../../Config";
import { ICustomer, ICustomerMethods } from "../../../Interfaces/Customer.interface";
import Logger from "../../../Lib/Logger";
import GetText from "../../../Translation/GetText";
import { A_PaymentCurrency } from "../../../Types/PaymentTypes";

const CustomerSchema = new Schema
(
Expand Down Expand Up @@ -96,7 +97,13 @@ const CustomerSchema = new Schema
type: Object,
required: false,
default: {},
}
},

currency: {
type: String,
enum: A_PaymentCurrency,
required: true,
},

}
);
Expand Down
4 changes: 2 additions & 2 deletions src/Email/Templates/Invoices/Invoice.template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export default async (invoice: IInvoice, customer: ICustomer) => await UseStyles
<tr>
<td>${item.notes}</td>
<td>${item.quantity}</td>
<td>${item.amount} ${await Company_Currency()}</td>
<td>${item.amount} ${!customer.currency ? await Company_Currency() : customer.currency}</td>
</tr>
`))).join('')}
</tbody>
Expand All @@ -85,7 +85,7 @@ export default async (invoice: IInvoice, customer: ICustomer) => await UseStyles
<strong>
Total:
</strong>
${invoice.amount+invoice.amount*invoice.tax_rate/100} ${await Company_Currency()} (${invoice.tax_rate}%)
${invoice.amount+invoice.amount*invoice.tax_rate/100} ${!customer.currency ? await Company_Currency() : customer.currency} (${invoice.tax_rate}%)
</p>
<p>
<strong>
Expand Down
4 changes: 2 additions & 2 deletions src/Email/Templates/Invoices/LateInvoice.Template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export default async (invoice: IInvoice, customer: ICustomer) => await UseStyles
<tr>
<td>${item.notes}</td>
<td>${item.quantity}</td>
<td>${item.amount} ${await Company_Currency()}</td>
<td>${item.amount} ${!customer.currency ? await Company_Currency() : customer.currency}</td>
</tr>
`))).join('')}
</tbody>
Expand All @@ -73,7 +73,7 @@ export default async (invoice: IInvoice, customer: ICustomer) => await UseStyles
<strong>
Total:
</strong>
${invoice.amount+invoice.amount*invoice.tax_rate/100} ${await Company_Currency()} (${invoice.tax_rate}%)
${invoice.amount+invoice.amount*invoice.tax_rate/100} ${!customer.currency ? await Company_Currency() : customer.currency} (${invoice.tax_rate}%)
</p>
<p>
<strong>
Expand Down
6 changes: 3 additions & 3 deletions src/Email/Templates/Orders/NewOrderCreated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export default async (order: IOrder, customer: ICustomer) => await UseStyles(str
<tr>
<td>${p?.name}</td>
<td>${product.quantity}</td>
<td>${p?.price} ${await Company_Currency()}</td>
<td>${p?.price} ${!customer.currency ? await Company_Currency() : customer.currency}</td>
</tr>`;
if(p_c.length > 0)
Expand All @@ -59,7 +59,7 @@ export default async (order: IOrder, customer: ICustomer) => await UseStyles(str
<tr>
<td>+ ${p?.name} - ${c?.name}</td>
<td>1</td>
<td>${c?.price} ${await Company_Currency()}</td>
<td>${c?.price} ${!customer.currency ? await Company_Currency() : customer.currency}</td>
</tr>`
}
}
Expand Down Expand Up @@ -95,7 +95,7 @@ export default async (order: IOrder, customer: ICustomer) => await UseStyles(str
total += p_c.reduce((a, b) => a + b);
return total;
}))).reduce((acc, cur) => acc + cur, 0)} ${(await Company_Currency()).toLocaleUpperCase()}
}))).reduce((acc, cur) => acc + cur, 0)} ${(!customer.currency ? await Company_Currency() : customer.currency).toLocaleUpperCase()}
</p>
</div>
`);
2 changes: 1 addition & 1 deletion src/Email/Templates/Transaction/NewTransaction.template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export = async (t: ITransactions, c: ICustomer, charged = false) => UseStyles(st
${await PrintCompanyInformation()}
</p>
<p>
Amount: ${t.amount} ${await Company_Currency()}
Amount: ${t.amount} ${!c.currency ? await Company_Currency() : c.currency}
</p>
</div>
`);
2 changes: 2 additions & 0 deletions src/Interfaces/Customer.interface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ICompanyConfig } from "./Admin/Configs.interface";
import { IImage } from "./Images.interface";

/**
Expand Down Expand Up @@ -26,6 +27,7 @@ export interface ICustomer
password: string;
createdAt: Date;
profile_picture: IImage["id"] | null;
currency: string | ICompanyConfig["currency"];
extra: {
[key: string]: any;
};
Expand Down
2 changes: 1 addition & 1 deletion src/Lib/Invoices/CreatePDFInvoice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export default function createPDFInvoice(invoice: IInvoice): Promise<string>
},
"taxNotation": "vat",
"settings": {
"currency": (await Company_Currency()).toUpperCase(),
"currency": (!Customer.currency ? await Company_Currency() : Customer.currency).toUpperCase(),
"margin-top": 25,
"margin-right": 25,
"margin-left": 25,
Expand Down
40 changes: 40 additions & 0 deletions src/Payments/Currencies/Paypal.currencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// A list of accaptable curenices for paypal
const data = {
/*
Australian dollar AUD
Brazilian real 2 BRL
Canadian dollar CAD
Chinese Renmenbi 3 CNY
Czech koruna CZK
Danish krone DKK
Euro EUR
Hong Kong dollar HKD
Hungarian forint 1 HUF
Israeli new shekel ILS
Japanese yen 1 JPY
Malaysian ringgit 3 MYR
Mexican peso MXN
New Taiwan dollar 1 TWD
New Zealand dollar NZD
Norwegian krone NOK
Philippine peso PHP
Polish złoty PLN
Pound sterling GBP
Russian ruble RUB
Singapore dollar SGD
Swedish krona SEK
Swiss franc CHF
Thai baht THB
United States dollar USD
*/
// Use these currencies for paypal
currencies: ["AUD", "BRL", "CAD", "CNY", "CZK", "DKK", "EUR", "HKD", "HUF", "ILS", "JPY", "MYR", "MXN", "TWD", "NZD", "NOK", "PHP", "PLN", "GBP", "RUB", "SGD", "SEK", "CHF", "THB", "USD"] as const,
}

export const PaypalCurrencies = data.currencies;

export function validCurrencyPaypal(currency: typeof data["currencies"])
{
// @ts-ignore
return data.currencies.includes(currency);
}
30 changes: 25 additions & 5 deletions src/Payments/Paypal.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import paypal from "paypal-rest-sdk";
import { Company_Currency, DebugMode, Domain, Http_Schema, Paypal_Client_Id, Paypal_Client_Secret, PORT } from "../Config";
import { Company_Currency, DebugMode, Domain, Full_Domain, Http_Schema, Paypal_Client_Id, Paypal_Client_Secret, PORT } from "../Config";
import CustomerModel from "../Database/Models/Customers/Customer.model";
import TransactionsModel from "../Database/Models/Transactions.model";
import { IInvoice } from "../Interfaces/Invoice.interface";
import { idTransicitons } from "../Lib/Generator";
Expand All @@ -8,6 +9,7 @@ import Logger from "../Lib/Logger";
import { getDate } from "../Lib/Time";
import sendEmailOnTransactionCreation from "../Lib/Transaction/SendEmailOnCreation";
import GetText from "../Translation/GetText";
import { validCurrencyPaypal } from "./Currencies/Paypal.currencies";

if(Paypal_Client_Id !== "" || Paypal_Client_Secret !== "")
paypal.configure({
Expand Down Expand Up @@ -37,15 +39,33 @@ export function createPaypalPaymentFromInvoice(invoice: IInvoice): Promise<paypa
Logger.warning(GetText().paypal.txt_Paypal_Creating_Payment_For_Invoice(invoice))
// Logger.warning(`Creating payment paypal for invoice ${invoice.uid}`);

const customer = await CustomerModel.findOne({ $or: [
{
id: invoice.customer_uid
},
{
uid: invoice.customer_uid
}
] });

// Check if our currency is acctable, otherwise.. go to USD
const c = (customer?.currency ?
customer.currency
:
await Company_Currency());

// @ts-ignore
const currency = validCurrencyPaypal(c) ? c : "USD";

const create_payment_json =
{
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": `${Http_Schema}://${Domain === "localhost" ? `localhost:${PORT}` : Domain}/v2/paypal/success`,
"cancel_url": `${Http_Schema}://${Domain === "localhost" ? `localhost:${PORT}` : Domain}/v2/paypal/cancel`
"return_url": `${Full_Domain}/v2/paypal/success`,
"cancel_url": `${Full_Domain}/v2/paypal/cancel`
},
transactions: [
{
Expand All @@ -55,13 +75,13 @@ export function createPaypalPaymentFromInvoice(invoice: IInvoice): Promise<paypa
return {
name: removeTags(item.notes),
price: (item.amount+(item.amount*invoice.tax_rate/100)).toString(),
currency: (await Company_Currency()).toUpperCase(),
currency: (currency).toUpperCase(),
quantity: item.quantity
}
}))
},
amount: {
currency: (await Company_Currency()).toUpperCase(),
currency: (currency).toUpperCase(),
total: (invoice.amount+(invoice.amount*invoice.tax_rate/100)).toString(),
details: {
subtotal: (invoice.amount+(invoice.amount*invoice.tax_rate/100)).toString(),
Expand Down
4 changes: 2 additions & 2 deletions src/Payments/Stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const CreatePaymentIntent = async (invoice: IInvoice) =>
const intent = (await Stripe.paymentIntents.create({
customer: s_customer?.id,
amount: (invoice.amount+invoice.amount*invoice.tax_rate/100) * 100,
currency: await Company_Currency() ?? "sek",
currency: (!customer.currency ? await Company_Currency() : customer.currency) ?? "sek",
payment_method_types: ["card"],
receipt_email: customer?.personal.email,
// @ts-ignore
Expand Down Expand Up @@ -154,7 +154,7 @@ export const ChargeCustomer = async (invoice_id: IInvoice["id"]) =>
{
const paymentIntent = await Stripe.paymentIntents.create({
amount: (invoice.amount+invoice.amount*invoice.tax_rate/100) * 100,
currency: await Company_Currency() ?? "sek",
currency: (!customer.currency ? await Company_Currency() : customer.currency) ?? "sek",
payment_method_types: ["card"],
receipt_email: customer?.personal.email,
// @ts-ignore
Expand Down
8 changes: 7 additions & 1 deletion src/Server/Routes/v2/Customers/Customers.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { APIError, APISuccess } from "../../../../Lib/Response";
import BaseModelAPI from "../../../../Models/BaseModelAPI";
import Logger from "../../../../Lib/Logger";
import { SendEmail } from "../../../../Email/Send";
import { Company_Name } from "../../../../Config";
import { Company_Currency, Company_Name } from "../../../../Config";
import mainEvent from "../../../../Events/Main.event";
import { sanitizeMongoose } from "../../../../Lib/Sanitize";
import WelcomeTemplate from "../../../../Email/Templates/Customer/Welcome.template";
Expand All @@ -33,6 +33,12 @@ function insert(req: Request, res: Response)
if(doesExist)
return APIError(`Email ${email} already exists`, 409)(res);

if(!req.body.currency)
{
const currency = await Company_Currency();
req.body.currency = currency;
}

API.create(req.body)
.then(async (result) =>
{
Expand Down
9 changes: 7 additions & 2 deletions src/Server/Routes/v2/Stripe/Stripe.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ export = class StripeRouter

const intent = await CreatePaymentIntent(invoice);

const customer = await CustomerModel.findOne({ $or: [
{ id: invoice.customer_uid },
{ uid: invoice.customer_uid }
] });

res.send(`
<head>
<title>Checkout | ${invoice.id}</title>
Expand Down Expand Up @@ -84,7 +89,7 @@ export = class StripeRouter
${await (await Promise.all(invoice.items.map(async (item) => `
<tr>
<td>${item.notes}</td>
<td>${item.amount} ${(await Company_Currency()).toUpperCase()}</td>
<td>${item.amount} ${(!customer?.currency ? await Company_Currency() : customer?.currency ?? "sek").toUpperCase()}</td>
</tr>
`))).join("")}
Expand All @@ -94,7 +99,7 @@ export = class StripeRouter
</tr>
<tr>
<td>Total</td>
<td>${invoice.amount+invoice.amount*invoice.tax_rate/100} ${(await Company_Currency()).toUpperCase()}</td>
<td>${invoice.amount+invoice.amount*invoice.tax_rate/100} ${(!customer?.currency ? await Company_Currency() : customer?.currency ?? "sek").toUpperCase()}</td>
</tr>
</table>
Expand Down
8 changes: 7 additions & 1 deletion src/Types/PaymentTypes.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
export type TPaymentTypes = "one_time" | "recurring" | "free";
export const A_PaymentTypes = ["one_time", "recurring", "free"] as const;
export const A_PaymentTypes = ["one_time", "recurring", "free"] as const;

// Every currencie code is in ISO 4217
export type TPaymentCurrency = "usd" | "eur" | "gbp" | "cad" | "aud" | "jpy" | "nzd" | "chf" | "sek" | "dkk" | "nok" | "hkd" | "sgd" | "thb" | "eur" | "zar" | "brl" | "rub" | "krw" | "ils" | "php" | "vnd" | "myr" | "idr" | "cny" | "twd" | "huf" | "czk" | "pln" | "hkd" | "sgd" | "thb" | "eur" | "zar" | "brl" | "rub" | "krw" | "ils" | "php" | "vnd" | "myr" | "idr" | "cny" | "twd" | "huf" | "czk" | "pln" | "hkd" | "sgd" | "thb" | "eur" | "zar" | "brl" | "rub" | "krw" | "ils" | "php" | "vnd" | "myr" | "idr" | "cny" | "twd" | "huf" | "czk" | "pln" | "hkd" | "sgd" | "thb" | "eur" | "zar" | "brl" | "rub" | "krw" | "ils" | "php" | "vnd" | "myr" | "idr" | "cny" | "twd" | "huf" | "czk" | "pln" | "hkd" | "sgd" | "thb" | "eur" | "zar" | "brl" | "rub" | "krw" | "ils" | "php" | "vnd" | "myr" | "idr" | "cny" | "twd" | "huf" | "czk" | "pln" | "hkd" | "sgd" | "thb" | "eur" | "zar" | "brl" | "rub" | "krw" | "ils" | "php" | "vnd" | "myr" | "idr" | "cny" | "twd" | "huf" | "czk" | "pln" | "hkd" | "sgd" | "thb" | "eur" | "zar" | "brl" | "rub" | "krw" | "ils" | "php" | "vnd" | "myr" | "idr" | "cny" | "twd" | "huf" | "czk" | "pln" | "hkd" | "sgd" | "thb";
export const A_PaymentCurrency = [
"usd", "eur", "gbp", "cad", "aud", "jpy", "nzd", "chf", "sek", "dkk", "nok", "hkd", "sgd", "thb", "eur", "zar", "brl", "rub", "krw", "ils", "php", "vnd", "myr", "idr", "cny", "twd", "huf", "czk", "pln", "hkd", "sgd", "thb", "eur", "zar", "brl", "rub", "krw", "ils", "php", "vnd", "myr", "idr", "cny", "twd", "huf", "czk", "pln", "hkd", "sgd", "thb", "eur", "zar", "brl", "rub", "krw", "ils", "php", "vnd", "myr", "idr", "cny", "twd", "huf", "czk", "pln", "hkd", "sgd", "thb", "eur", "zar", "brl", "rub", "krw", "ils", "php", "vnd", "myr", "idr", "cny", "twd", "huf", "czk", "pln", "hkd", "sgd", "thb", "eur", "zar", "brl", "rub", "krw", "ils", "php", "vnd", "myr", "idr", "cny", "twd", "huf", "czk", "pln", "hkd", "sgd", "thb", "eur", "zar", "brl", "rub", "krw", "ils", "php", "vnd", "myr", "idr", "cny", "twd", "huf", "czk", "pln", "hkd", "sgd", "thb", "eur", "zar", "brl", "rub", "krw", "ils", "php", "vnd", "myr", "idr", "cny", "twd", "huf", "czk", "pln", "hkd", "sgd", "thb"
] as const;

0 comments on commit e5a49fc

Please sign in to comment.