UNPKG

@churchapps/apphelper-donations

Version:
233 lines 14.1 kB
"use client"; import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime"; import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js"; import { useState, useRef, useEffect } from "react"; import ReCAPTCHA from "react-google-recaptcha"; import { ErrorMessages, InputBox } from "@churchapps/apphelper"; import { FundDonations } from "."; import { ApiHelper, DateHelper, CurrencyHelper } from "@churchapps/helpers"; import { Locale, DonationHelper } from "../helpers"; import { Grid, Alert, TextField, Button, FormControl, InputLabel, Select, MenuItem, FormGroup, FormControlLabel, Checkbox, Typography } from "@mui/material"; export const NonAuthDonationInner = ({ mainContainerCssProps, showHeader = true, ...props }) => { const stripe = useStripe(); const elements = useElements(); const formStyling = { style: { base: { fontSize: "18px" } } }; const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); const [email, setEmail] = useState(""); const [fundsTotal, setFundsTotal] = useState(0); const [transactionFee, setTransactionFee] = useState(0); const [total, setTotal] = useState(0); const [errors, setErrors] = useState([]); const [fundDonations, setFundDonations] = useState([]); const [funds, setFunds] = useState([]); const [donationComplete, setDonationComplete] = useState(false); const [processing, setProcessing] = useState(false); const [donationType, setDonationType] = useState("once"); const [interval, setInterval] = useState("one_month"); const [startDate, setStartDate] = useState(new Date().toDateString()); const [captchaResponse, setCaptchaResponse] = useState(""); const [church, setChurch] = useState(); const [gateway, setGateway] = useState(null); const [searchParams, setSearchParams] = useState(); const captchaRef = useRef(null); const getUrlParam = (param) => { if (typeof window === "undefined") return null; const urlParams = new URLSearchParams(window.location.search); return urlParams.get(param); }; const init = () => { const fundId = getUrlParam("fundId"); const amount = getUrlParam("amount"); setSearchParams({ fundId, amount }); ApiHelper.get("/funds/churchId/" + props.churchId, "GivingApi").then((data) => { setFunds(data); if (fundId && fundId !== "") { const selectedFund = data.find((f) => f.id === fundId); if (selectedFund) { setFundDonations([{ fundId: selectedFund.id, amount: (amount && amount !== "") ? parseFloat(amount) : 0 }]); } } else if (data.length) { setFundDonations([{ fundId: data[0].id }]); } }); ApiHelper.get("/churches/" + props.churchId, "MembershipApi").then((data) => { setChurch(data); }); ApiHelper.get("/gateways/churchId/" + props.churchId, "GivingApi").then((data) => { if (data.length !== 0) setGateway(data[0]); }); }; const handleCaptchaChange = (value) => { const captchaToken = captchaRef.current.getValue(); ApiHelper.postAnonymous("/donate/captcha-verify", { token: captchaToken }, "GivingApi").then((data) => { setCaptchaResponse(data.response); }); }; const handleCheckChange = (e, checked) => { const totalPayAmount = checked ? fundsTotal + transactionFee : fundsTotal; setTotal(totalPayAmount); }; const handleSave = async () => { if (validate()) { setProcessing(true); ApiHelper.post("/users/loadOrCreate", { userEmail: email, firstName, lastName }, "MembershipApi") .catch((ex) => { setErrors([ex.toString()]); setProcessing(false); }) .then(async (userData) => { const personData = { churchId: props.churchId, firstName, lastName, email }; const person = await ApiHelper.post("/people/loadOrCreate", personData, "MembershipApi"); saveCard(userData, person); }); } }; const saveCard = async (user, person) => { const cardData = elements.getElement(CardElement); const stripePM = await stripe.createPaymentMethod({ type: "card", card: cardData }); if (stripePM.error) { setErrors([stripePM.error.message]); setProcessing(false); } else { const pm = { id: stripePM.paymentMethod.id, personId: person.id, email: email, name: person.name.display, churchId: props.churchId }; await ApiHelper.post("/paymentmethods/addcard", pm, "GivingApi").then((result) => { if (result?.raw?.message) { setErrors([result.raw.message]); setProcessing(false); } else { const d = result; saveDonation(d.paymentMethod, d.customerId, person); } }); } }; const saveDonation = async (paymentMethod, customerId, person) => { const donation = { amount: total, id: paymentMethod.id, customerId: customerId, type: paymentMethod.type, churchId: props.churchId, funds: [], person: { id: person?.id, email: person?.contactInfo?.email, name: person?.name?.display } }; if (donationType === "recurring") { donation.billing_cycle_anchor = +new Date(startDate); donation.interval = DonationHelper.getInterval(interval); } for (const fundDonation of fundDonations) { const fund = funds.find((fund) => fund.id === fundDonation.fundId); donation.funds.push({ id: fundDonation.fundId, amount: fundDonation.amount || 0, name: fund.name }); } const churchObj = { name: church.name, subDomain: church.subDomain, churchURL: typeof window !== "undefined" && window.location.origin, logo: props?.churchLogo }; let results; if (donationType === "once") results = await ApiHelper.post("/donate/charge/", { ...donation, church: churchObj }, "GivingApi"); if (donationType === "recurring") results = await ApiHelper.post("/donate/subscribe/", { ...donation, church: churchObj }, "GivingApi"); if (results?.status === "succeeded" || results?.status === "pending" || results?.status === "active") { setDonationComplete(true); } if (results?.raw?.message) { setErrors([results?.raw?.message]); setProcessing(false); } setProcessing(false); }; const validate = () => { const result = []; if (!firstName) result.push(Locale.label("donation.donationForm.validate.firstName")); if (!lastName) result.push(Locale.label("donation.donationForm.validate.lastName")); if (!email) result.push(Locale.label("donation.donationForm.validate.email")); if (fundsTotal === 0) result.push(Locale.label("donation.donationForm.validate.amount")); if (result.length === 0) { if (!email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w+)+$/)) result.push(Locale.label("donation.donationForm.validate.validEmail")); //eslint-disable-line } //Todo - make sure the account doesn't exist. (loadOrCreate?) setErrors(result); return result.length === 0; }; const handleChange = (e) => { const val = e.currentTarget.value; switch (e.currentTarget.name) { case "firstName": setFirstName(val); break; case "lastName": setLastName(val); break; case "email": setEmail(val); break; case "startDate": setStartDate(val); break; case "interval": setInterval(val); break; } }; const handleFundDonationsChange = async (fd) => { setFundDonations(fd); let totalAmount = 0; const selectedFunds = []; for (const fundDonation of fd) { totalAmount += fundDonation.amount || 0; const fund = funds.find((fund) => fund.id === fundDonation.fundId); selectedFunds.push({ id: fundDonation.fundId, amount: fundDonation.amount || 0, name: fund.name }); } setFundsTotal(totalAmount); setTotal(totalAmount); const fee = await getTransactionFee(totalAmount); setTransactionFee(fee); if (gateway && gateway.payFees === true) { setTotal(totalAmount + fee); } }; const getTransactionFee = async (amount) => { if (amount > 0) { try { const response = await ApiHelper.post("/donate/fee?churchId=" + props.churchId, { type: "creditCard", amount }, "GivingApi"); return response.calculatedFee; } catch (error) { console.log("Error calculating transaction fee: ", error); return 0; } } else { return 0; } }; const getFundList = () => { if (funds) { return (_jsxs(_Fragment, { children: [_jsx("hr", {}), _jsx("h4", { children: Locale.label("donation.donationForm.funds") }), _jsx(FundDonations, { fundDonations: fundDonations, funds: funds, params: searchParams, updatedFunction: handleFundDonationsChange })] })); } }; useEffect(init, []); //eslint-disable-line if (donationComplete) return _jsx(Alert, { severity: "success", children: Locale.label("donation.donationForm.thankYou") }); else { return (_jsxs(InputBox, { headerIcon: showHeader ? "volunteer_activism" : "", headerText: showHeader ? "Donate" : "", saveFunction: handleSave, saveText: "Donate", isSubmitting: processing || !captchaResponse || captchaResponse === "robot", mainContainerCssProps: mainContainerCssProps, children: [_jsx(ErrorMessages, { errors: errors }), _jsxs(Grid, { container: true, spacing: 3, children: [_jsx(Grid, { size: { xs: 12, md: 6 }, children: _jsx(Button, { "aria-label": "single-donation", size: "small", fullWidth: true, style: { minHeight: "50px" }, variant: donationType === "once" ? "contained" : "outlined", onClick: () => setDonationType("once"), children: Locale.label("donation.donationForm.make") }) }), _jsx(Grid, { size: { xs: 12, md: 6 }, children: _jsx(Button, { "aria-label": "recurring-donation", size: "small", fullWidth: true, style: { minHeight: "50px" }, variant: donationType === "recurring" ? "contained" : "outlined", onClick: () => setDonationType("recurring"), children: Locale.label("donation.donationForm.makeRecurring") }) }), _jsx(Grid, { size: { xs: 12, md: 6 }, children: _jsx(TextField, { fullWidth: true, label: Locale.label("person.firstName"), name: "firstName", value: firstName, onChange: handleChange }) }), _jsx(Grid, { size: { xs: 12, md: 6 }, children: _jsx(TextField, { fullWidth: true, label: Locale.label("person.lastName"), name: "lastName", value: lastName, onChange: handleChange }) }), _jsx(Grid, { size: { xs: 12, md: 6 }, children: _jsx(TextField, { fullWidth: true, label: Locale.label("person.email"), name: "email", value: email, onChange: handleChange }) }), _jsx(Grid, { size: { xs: 12, md: 6 }, children: _jsx(ReCAPTCHA, { sitekey: props.recaptchaSiteKey, ref: captchaRef, onChange: handleCaptchaChange }) })] }), _jsx("div", { style: { padding: 10, border: "1px solid #CCC", borderRadius: 5, marginTop: 10 }, children: _jsx(CardElement, { options: formStyling }) }), donationType === "recurring" && _jsxs(Grid, { container: true, spacing: 3, style: { marginTop: 0 }, children: [_jsx(Grid, { size: { xs: 12, md: 6 }, children: _jsxs(FormControl, { fullWidth: true, children: [_jsx(InputLabel, { children: Locale.label("donation.donationForm.frequency") }), _jsxs(Select, { label: "Frequency", name: "interval", "aria-label": "interval", value: interval, onChange: (e) => { setInterval(e.target.value); }, children: [_jsx(MenuItem, { value: "one_week", children: Locale.label("donation.donationForm.weekly") }), _jsx(MenuItem, { value: "two_week", children: Locale.label("donation.donationForm.biWeekly") }), _jsx(MenuItem, { value: "one_month", children: Locale.label("donation.donationForm.monthly") }), _jsx(MenuItem, { value: "three_month", children: Locale.label("donation.donationForm.quarterly") }), _jsx(MenuItem, { value: "one_year", children: Locale.label("donation.donationForm.annually") })] })] }) }), _jsx(Grid, { size: { xs: 12, md: 6 }, children: _jsx(TextField, { fullWidth: true, name: "startDate", type: "date", "aria-label": "startDate", label: Locale.label("donation.donationForm.startDate"), value: DateHelper.formatHtml5Date(new Date(startDate)), onChange: handleChange }) })] }), getFundList(), _jsx("div", { children: fundsTotal > 0 && _jsxs(_Fragment, { children: [(gateway && gateway.payFees === true) ? _jsxs(Typography, { fontSize: 14, fontStyle: "italic", children: ["*", Locale.label("donation.donationForm.fees").replace("{}", CurrencyHelper.formatCurrency(transactionFee))] }) : (_jsx(FormGroup, { children: _jsx(FormControlLabel, { control: _jsx(Checkbox, {}), name: "transaction-fee", label: Locale.label("donation.donationForm.cover").replace("{}", CurrencyHelper.formatCurrency(transactionFee)), onChange: handleCheckChange }) })), _jsxs("p", { children: ["Total Donation Amount: $", total] })] }) })] })); } }; //# sourceMappingURL=NonAuthDonationInner.js.map