format with prettier

This commit is contained in:
Rimian Perkins 2019-08-27 20:37:20 +10:00
parent 675c3d27ba
commit 0cb3a9acde
16 changed files with 519 additions and 409 deletions

View File

@ -1,4 +1 @@
export default Ember.Component.extend({});
export default Ember.Component.extend({
});

View File

@ -1,5 +1,5 @@
export default Ember.Component.extend({ export default Ember.Component.extend({
classNames: 'donation-list', classNames: "donation-list",
hasSubscriptions: Ember.computed.notEmpty('subscriptions'), hasSubscriptions: Ember.computed.notEmpty("subscriptions"),
hasCharges: Ember.computed.notEmpty('charges') hasCharges: Ember.computed.notEmpty("charges")
}); });

View File

@ -1,15 +1,15 @@
import { ajax } from 'discourse/lib/ajax'; import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from "discourse/lib/ajax-error";
import { formatAnchor, formatAmount } from '../lib/donation-utilities'; import { formatAnchor, formatAmount } from "../lib/donation-utilities";
import { default as computed } from 'ember-addons/ember-computed-decorators'; import { default as computed } from "ember-addons/ember-computed-decorators";
import showModal from "discourse/lib/show-modal"; import showModal from "discourse/lib/show-modal";
export default Ember.Component.extend({ export default Ember.Component.extend({
classNameBindings: [':donation-row', 'canceled', 'updating'], classNameBindings: [":donation-row", "canceled", "updating"],
includePrefix: Ember.computed.or('invoice', 'charge'), includePrefix: Ember.computed.or("invoice", "charge"),
canceled: Ember.computed.equal('subscription.status', 'canceled'), canceled: Ember.computed.equal("subscription.status", "canceled"),
@computed('subscription', 'invoice', 'charge', 'customer') @computed("subscription", "invoice", "charge", "customer")
data(subscription, invoice, charge, customer) { data(subscription, invoice, charge, customer) {
if (subscription) { if (subscription) {
return $.extend({}, subscription.plan, { return $.extend({}, subscription.plan, {
@ -41,22 +41,22 @@ export default Ember.Component.extend({
} }
}, },
@computed('data.currency') @computed("data.currency")
currency(currency) { currency(currency) {
return currency ? currency.toUpperCase() : null; return currency ? currency.toUpperCase() : null;
}, },
@computed('data.amount', 'currency') @computed("data.amount", "currency")
amount(amount, currency) { amount(amount, currency) {
return formatAmount(amount, currency); return formatAmount(amount, currency);
}, },
@computed('data.interval') @computed("data.interval")
interval(interval) { interval(interval) {
return interval || 'once'; return interval || "once";
}, },
@computed('data.anchor', 'interval') @computed("data.anchor", "interval")
period(anchor, interval) { period(anchor, interval) {
return I18n.t(`discourse_donations.period.${interval}`, { return I18n.t(`discourse_donations.period.${interval}`, {
anchor: formatAnchor(interval, moment.unix(anchor)) anchor: formatAnchor(interval, moment.unix(anchor))
@ -64,30 +64,33 @@ export default Ember.Component.extend({
}, },
cancelSubscription() { cancelSubscription() {
const subscriptionId = this.get('subscription.id'); const subscriptionId = this.get("subscription.id");
this.set('updating', true); this.set("updating", true);
ajax('/donate/charges/cancel-subscription', { ajax("/donate/charges/cancel-subscription", {
data: { data: {
subscription_id: subscriptionId subscription_id: subscriptionId
}, },
method: 'put' method: "put"
}).then(result => { })
if (result.success) { .then(result => {
this.set('subscription', result.subscription); if (result.success) {
} this.set("subscription", result.subscription);
}).catch(popupAjaxError).finally(() => { }
this.set('updating', false); })
}); .catch(popupAjaxError)
.finally(() => {
this.set("updating", false);
});
}, },
actions: { actions: {
cancelSubscription() { cancelSubscription() {
showModal('cancel-subscription', { showModal("cancel-subscription", {
model: { model: {
currency: this.get('currency'), currency: this.get("currency"),
amount: this.get('amount'), amount: this.get("amount"),
period: this.get('period'), period: this.get("period"),
confirm: () => this.cancelSubscription() confirm: () => this.cancelSubscription()
} }
}); });

View File

@ -1,6 +1,6 @@
import { ajax } from 'discourse/lib/ajax'; import { ajax } from "discourse/lib/ajax";
import { formatAnchor, zeroDecimalCurrencies } from '../lib/donation-utilities'; import { formatAnchor, zeroDecimalCurrencies } from "../lib/donation-utilities";
import { default as computed } from 'ember-addons/ember-computed-decorators'; import { default as computed } from "ember-addons/ember-computed-decorators";
import { emailValid as emailValidHelper } from "discourse/lib/utilities"; import { emailValid as emailValidHelper } from "discourse/lib/utilities";
export default Ember.Component.extend({ export default Ember.Component.extend({
@ -13,14 +13,17 @@ export default Ember.Component.extend({
init() { init() {
this._super(); this._super();
const user = this.get('currentUser'); const user = this.get("currentUser");
const settings = Discourse.SiteSettings; const settings = Discourse.SiteSettings;
this.set('create_accounts', !user && settings.discourse_donations_enable_create_accounts); this.set(
this.set('stripe', Stripe(settings.discourse_donations_public_key)); "create_accounts",
!user && settings.discourse_donations_enable_create_accounts
);
this.set("stripe", Stripe(settings.discourse_donations_public_key));
const types = settings.discourse_donations_types.split('|') || []; const types = settings.discourse_donations_types.split("|") || [];
const amounts = this.get('donateAmounts'); const amounts = this.get("donateAmounts");
this.setProperties({ this.setProperties({
types, types,
@ -31,10 +34,13 @@ export default Ember.Component.extend({
@computed @computed
causes() { causes() {
const categoryEnabled = Discourse.SiteSettings.discourse_donations_cause_category; const categoryEnabled =
Discourse.SiteSettings.discourse_donations_cause_category;
if (categoryEnabled) { if (categoryEnabled) {
let categoryIds = Discourse.SiteSettings.discourse_donations_causes_categories.split('|'); let categoryIds = Discourse.SiteSettings.discourse_donations_causes_categories.split(
"|"
);
if (categoryIds.length) { if (categoryIds.length) {
categoryIds = categoryIds.map(Number); categoryIds = categoryIds.map(Number);
@ -42,7 +48,8 @@ export default Ember.Component.extend({
.get("categoriesList") .get("categoriesList")
.filter(c => { .filter(c => {
return categoryIds.indexOf(c.id) > -1; return categoryIds.indexOf(c.id) > -1;
}).map(c => { })
.map(c => {
return { return {
id: c.id, id: c.id,
name: c.name name: c.name
@ -53,13 +60,13 @@ export default Ember.Component.extend({
} }
} else { } else {
const causes = Discourse.SiteSettings.discourse_donations_causes; const causes = Discourse.SiteSettings.discourse_donations_causes;
return causes ? causes.split('|') : []; return causes ? causes.split("|") : [];
} }
}, },
@computed('types') @computed("types")
donationTypes(types) { donationTypes(types) {
return types.map((type) => { return types.map(type => {
return { return {
id: type, id: type,
name: I18n.t(`discourse_donations.types.${type}`) name: I18n.t(`discourse_donations.types.${type}`)
@ -67,16 +74,20 @@ export default Ember.Component.extend({
}); });
}, },
@computed('type') @computed("type")
period(type) { period(type) {
return I18n.t(`discourse_donations.period.${type}`, { anchor: formatAnchor(type) }); return I18n.t(`discourse_donations.period.${type}`, {
anchor: formatAnchor(type)
});
}, },
@computed @computed
donateAmounts() { donateAmounts() {
const setting = Discourse.SiteSettings.discourse_donations_amounts.split('|'); const setting = Discourse.SiteSettings.discourse_donations_amounts.split(
"|"
);
if (setting.length) { if (setting.length) {
return setting.map((amount) => { return setting.map(amount => {
return { return {
value: parseInt(amount, 10), value: parseInt(amount, 10),
name: `${amount}.00` name: `${amount}.00`
@ -87,167 +98,177 @@ export default Ember.Component.extend({
} }
}, },
@computed('stripe') @computed("stripe")
card(stripe) { card(stripe) {
let elements = stripe.elements(); let elements = stripe.elements();
let card = elements.create('card', { let card = elements.create("card", {
hidePostalCode: !Discourse.SiteSettings.discourse_donations_zip_code hidePostalCode: !Discourse.SiteSettings.discourse_donations_zip_code
}); });
card.addEventListener('change', (event) => { card.addEventListener("change", event => {
if (event.error) { if (event.error) {
this.set('stripeError', event.error.message); this.set("stripeError", event.error.message);
} else { } else {
this.set('stripeError', ''); this.set("stripeError", "");
} }
if (event.elementType === 'card' && event.complete) { if (event.elementType === "card" && event.complete) {
this.set('stripeReady', true); this.set("stripeReady", true);
} }
}); });
return card; return card;
}, },
@computed('amount') @computed("amount")
transactionFee(amount) { transactionFee(amount) {
const fixed = Discourse.SiteSettings.discourse_donations_transaction_fee_fixed; const fixed =
const percent = Discourse.SiteSettings.discourse_donations_transaction_fee_percent; Discourse.SiteSettings.discourse_donations_transaction_fee_fixed;
const fee = ((amount + fixed) / (1 - percent)) - amount; const percent =
Discourse.SiteSettings.discourse_donations_transaction_fee_percent;
const fee = (amount + fixed) / (1 - percent) - amount;
return Math.round(fee * 100) / 100; return Math.round(fee * 100) / 100;
}, },
@computed('amount', 'transactionFee', 'includeTransactionFee') @computed("amount", "transactionFee", "includeTransactionFee")
totalAmount(amount, fee, include) { totalAmount(amount, fee, include) {
if (include) return amount + fee; if (include) return amount + fee;
return amount; return amount;
}, },
@computed('email') @computed("email")
emailValid(email) { emailValid(email) {
return emailValidHelper(email); return emailValidHelper(email);
}, },
@computed('email', 'emailValid') @computed("email", "emailValid")
showEmailError(email, emailValid) { showEmailError(email, emailValid) {
return email && email.length > 3 && !emailValid; return email && email.length > 3 && !emailValid;
}, },
@computed('currentUser', 'emailValid') @computed("currentUser", "emailValid")
userReady(currentUser, emailValid) { userReady(currentUser, emailValid) {
return currentUser || emailValid; return currentUser || emailValid;
}, },
@computed('cause') @computed("cause")
causeValid(cause) { causeValid(cause) {
return cause || !Discourse.SiteSettings.discourse_donations_cause_required; return cause || !Discourse.SiteSettings.discourse_donations_cause_required;
}, },
@computed('userReady', 'stripeReady', 'causeValid') @computed("userReady", "stripeReady", "causeValid")
formIncomplete(userReady, stripeReady, causeValid) { formIncomplete(userReady, stripeReady, causeValid) {
return !userReady || !stripeReady || !causeValid; return !userReady || !stripeReady || !causeValid;
}, },
@computed('transactionInProgress', 'formIncomplete') @computed("transactionInProgress", "formIncomplete")
disableSubmit(transactionInProgress, formIncomplete) { disableSubmit(transactionInProgress, formIncomplete) {
return transactionInProgress || formIncomplete; return transactionInProgress || formIncomplete;
}, },
didInsertElement() { didInsertElement() {
this._super(); this._super();
this.get('card').mount('#card-element'); this.get("card").mount("#card-element");
Ember.$(document).on('click', Ember.run.bind(this, this.documentClick)); Ember.$(document).on("click", Ember.run.bind(this, this.documentClick));
}, },
willDestroyElement() { willDestroyElement() {
Ember.$(document).off('click', Ember.run.bind(this, this.documentClick)); Ember.$(document).off("click", Ember.run.bind(this, this.documentClick));
}, },
documentClick(e) { documentClick(e) {
let $element = this.$('.transaction-fee-description'); let $element = this.$(".transaction-fee-description");
let $target = $(e.target); let $target = $(e.target);
if ($target.closest($element).length < 1 && if ($target.closest($element).length < 1 && this._state !== "destroying") {
this._state !== 'destroying') { this.set("showTransactionFeeDescription", false);
this.set('showTransactionFeeDescription', false);
} }
}, },
setSuccess() { setSuccess() {
this.set('paymentSuccess', true); this.set("paymentSuccess", true);
}, },
endTranscation() { endTranscation() {
this.set('transactionInProgress', false); this.set("transactionInProgress", false);
}, },
concatMessages(messages) { concatMessages(messages) {
this.set('result', this.get('result').concat(messages)); this.set("result", this.get("result").concat(messages));
}, },
actions: { actions: {
toggleTransactionFeeDescription() { toggleTransactionFeeDescription() {
this.toggleProperty('showTransactionFeeDescription'); this.toggleProperty("showTransactionFeeDescription");
}, },
submitStripeCard() { submitStripeCard() {
let self = this; let self = this;
this.set('transactionInProgress', true); this.set("transactionInProgress", true);
this.get('stripe').createToken(this.get('card')).then(data => { this.get("stripe")
self.set('result', []); .createToken(this.get("card"))
.then(data => {
self.set("result", []);
if (data.error) { if (data.error) {
this.setProperties({ this.setProperties({
stripeError: data.error.message, stripeError: data.error.message,
stripeReady: false stripeReady: false
});
self.endTranscation();
} else {
const settings = Discourse.SiteSettings;
const transactionFeeEnabled = settings.discourse_donations_enable_transaction_fee;
let amount = transactionFeeEnabled ? this.get('totalAmount') : this.get('amount');
if (zeroDecimalCurrencies.indexOf(settings.discourse_donations_currency) === -1) {
amount = amount * 100;
}
let params = {
stripeToken: data.token.id,
cause: self.get('cause'),
type: self.get('type'),
amount,
email: self.get('email'),
username: self.get('username'),
create_account: self.get('create_accounts')
};
if(!self.get('paymentSuccess')) {
ajax('/donate/charges', {
data: params,
method: 'post'
}).then(result => {
if (result.subscription) {
let subscription = $.extend({}, result.subscription, {
new: true
});
this.get('subscriptions').unshiftObject(subscription);
}
if (result.charge) {
let charge = $.extend({}, result.charge, {
new: true
});
this.get('charges').unshiftObject(charge);
}
self.concatMessages(result.messages);
self.endTranscation();
}); });
self.endTranscation();
} else {
const settings = Discourse.SiteSettings;
const transactionFeeEnabled =
settings.discourse_donations_enable_transaction_fee;
let amount = transactionFeeEnabled
? this.get("totalAmount")
: this.get("amount");
if (
zeroDecimalCurrencies.indexOf(
settings.discourse_donations_currency
) === -1
) {
amount = amount * 100;
}
let params = {
stripeToken: data.token.id,
cause: self.get("cause"),
type: self.get("type"),
amount,
email: self.get("email"),
username: self.get("username"),
create_account: self.get("create_accounts")
};
if (!self.get("paymentSuccess")) {
ajax("/donate/charges", {
data: params,
method: "post"
}).then(result => {
if (result.subscription) {
let subscription = $.extend({}, result.subscription, {
new: true
});
this.get("subscriptions").unshiftObject(subscription);
}
if (result.charge) {
let charge = $.extend({}, result.charge, {
new: true
});
this.get("charges").unshiftObject(charge);
}
self.concatMessages(result.messages);
self.endTranscation();
});
}
} }
} });
});
} }
} }
}); });

View File

@ -1,12 +1,12 @@
export default Ember.Controller.extend({ export default Ember.Controller.extend({
actions: { actions: {
confirm() { confirm() {
this.get('model.confirm')(); this.get("model.confirm")();
this.send('closeModal'); this.send("closeModal");
}, },
cancel() { cancel() {
this.send('closeModal'); this.send("closeModal");
} }
} }
}); });

View File

@ -1,54 +1,59 @@
import { default as computed } from 'ember-addons/ember-computed-decorators'; import { default as computed } from "ember-addons/ember-computed-decorators";
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from "discourse/lib/ajax-error";
import { ajax } from 'discourse/lib/ajax'; import { ajax } from "discourse/lib/ajax";
import { getOwner } from 'discourse-common/lib/get-owner'; import { getOwner } from "discourse-common/lib/get-owner";
import { emailValid } from "discourse/lib/utilities"; import { emailValid } from "discourse/lib/utilities";
export default Ember.Controller.extend({ export default Ember.Controller.extend({
loadingDonations: false, loadingDonations: false,
loadDonationsDisabled: Ember.computed.not('emailVaild'), loadDonationsDisabled: Ember.computed.not("emailVaild"),
@computed('charges.[]', 'subscriptions.[]') @computed("charges.[]", "subscriptions.[]")
hasDonations(charges, subscriptions) { hasDonations(charges, subscriptions) {
return (charges && charges.length > 0) || return (
(subscriptions && subscriptions.length > 0); (charges && charges.length > 0) ||
(subscriptions && subscriptions.length > 0)
);
}, },
@computed('email') @computed("email")
emailVaild(email) { emailVaild(email) {
return emailValid(email); return emailValid(email);
}, },
actions: { actions: {
loadDonations() { loadDonations() {
let email = this.get('email'); let email = this.get("email");
this.set('loadingDonations', true); this.set("loadingDonations", true);
ajax('/donate/charges', { ajax("/donate/charges", {
data: { email }, data: { email },
type: 'GET' type: "GET"
}).then((result) => { })
this.setProperties({ .then(result => {
charges: Ember.A(result.charges), this.setProperties({
subscriptions: Ember.A(result.subscriptions), charges: Ember.A(result.charges),
customer: result.customer subscriptions: Ember.A(result.subscriptions),
}); customer: result.customer
}).catch(popupAjaxError).finally(() => { });
this.setProperties({ })
loadingDonations: false, .catch(popupAjaxError)
hasEmailResult: true .finally(() => {
}); this.setProperties({
loadingDonations: false,
hasEmailResult: true
});
Ember.run.later(() => { Ember.run.later(() => {
this.set('hasEmailResult', false); this.set("hasEmailResult", false);
}, 6000); }, 6000);
}); });
}, },
showLogin() { showLogin() {
const controller = getOwner(this).lookup('route:application'); const controller = getOwner(this).lookup("route:application");
controller.send('showLogin'); controller.send("showLogin");
} }
} }
}); });

View File

@ -1,3 +1,3 @@
export default function() { export default function() {
this.route('donate'); this.route("donate");
}; }

View File

@ -1,34 +1,49 @@
import { withPluginApi } from 'discourse/lib/plugin-api'; import { withPluginApi } from "discourse/lib/plugin-api";
export default { export default {
name: 'donations-edits', name: "donations-edits",
initialize(container) { initialize(container) {
const siteSettings = container.lookup('site-settings:main'); const siteSettings = container.lookup("site-settings:main");
withPluginApi('0.8.12', api => { withPluginApi("0.8.12", api => {
api.decorateCooked($post => { api.decorateCooked($post => {
const $form = $post.find('.stripe-checkout'); const $form = $post.find(".stripe-checkout");
if ($form.length) { if ($form.length) {
const $input = $form.find('input'); const $input = $form.find("input");
var s = document.createElement('script'); var s = document.createElement("script");
s.src = 'https://checkout.stripe.com/checkout.js'; s.src = "https://checkout.stripe.com/checkout.js";
s.setAttribute('class', 'stripe-button'); s.setAttribute("class", "stripe-button");
s.setAttribute('data-key', siteSettings.discourse_donations_public_key); s.setAttribute(
s.setAttribute('data-amount', $input.attr('amount')); "data-key",
s.setAttribute('data-name', siteSettings.discourse_donations_shop_name); siteSettings.discourse_donations_public_key
s.setAttribute('data-description', $form.attr('content')); );
s.setAttribute('data-image', $form.attr('image') || ''); s.setAttribute("data-amount", $input.attr("amount"));
s.setAttribute('data-locale', 'auto'); s.setAttribute(
s.setAttribute('data-zip-code', siteSettings.discourse_donations_zip_code); "data-name",
s.setAttribute('data-billing-address', siteSettings.discourse_donations_billing_address); siteSettings.discourse_donations_shop_name
s.setAttribute('data-currency', siteSettings.discourse_donations_currency); );
s.setAttribute("data-description", $form.attr("content"));
s.setAttribute("data-image", $form.attr("image") || "");
s.setAttribute("data-locale", "auto");
s.setAttribute(
"data-zip-code",
siteSettings.discourse_donations_zip_code
);
s.setAttribute(
"data-billing-address",
siteSettings.discourse_donations_billing_address
);
s.setAttribute(
"data-currency",
siteSettings.discourse_donations_currency
);
$form.append(s); $form.append(s);
} }
}); });
if (siteSettings.discourse_donations_cause_category) { if (siteSettings.discourse_donations_cause_category) {
api.decorateWidget('category-header-widget:after', helper => { api.decorateWidget("category-header-widget:after", helper => {
helper.widget.appEvents.on('page:changed', () => { helper.widget.appEvents.on("page:changed", () => {
helper.widget.scheduleRerender(); helper.widget.scheduleRerender();
}); });
}); });

View File

@ -1,27 +1,44 @@
const formatAnchor = function(type = null, time = moment()) { const formatAnchor = function(type = null, time = moment()) {
let format; let format;
switch(type) { switch (type) {
case 'once': case "once":
format = 'Do MMMM YYYY'; format = "Do MMMM YYYY";
break; break;
case 'week': case "week":
format = 'dddd'; format = "dddd";
break; break;
case 'month': case "month":
format = 'Do'; format = "Do";
break; break;
case 'year': case "year":
format = 'MMMM D'; format = "MMMM D";
break; break;
default: default:
format = 'dddd'; format = "dddd";
} }
return moment(time).format(format); return moment(time).format(format);
}; };
const zeroDecimalCurrencies = ['MGA', 'BIF', 'CLP', 'PYG', 'DFJ', 'RWF', 'GNF', 'UGX', 'JPY', 'VND', 'VUV', 'XAF', 'KMF', 'KRW', 'XOF', 'XPF']; const zeroDecimalCurrencies = [
"MGA",
"BIF",
"CLP",
"PYG",
"DFJ",
"RWF",
"GNF",
"UGX",
"JPY",
"VND",
"VUV",
"XAF",
"KMF",
"KRW",
"XOF",
"XPF"
];
const formatAmount = function(amount, currency) { const formatAmount = function(amount, currency) {
let zeroDecimal = zeroDecimalCurrencies.indexOf(currency) > -1; let zeroDecimal = zeroDecimalCurrencies.indexOf(currency) > -1;

View File

@ -1,12 +1,12 @@
import DiscourseRoute from "discourse/routes/discourse"; import DiscourseRoute from "discourse/routes/discourse";
import DiscourseURL from 'discourse/lib/url'; import DiscourseURL from "discourse/lib/url";
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from "discourse/lib/ajax-error";
import { ajax } from 'discourse/lib/ajax'; import { ajax } from "discourse/lib/ajax";
export default DiscourseRoute.extend({ export default DiscourseRoute.extend({
redirect() { redirect() {
if (!Discourse.SiteSettings.discourse_donations_enabled) { if (!Discourse.SiteSettings.discourse_donations_enabled) {
DiscourseURL.routeTo('/'); DiscourseURL.routeTo("/");
return; return;
} }
}, },
@ -16,22 +16,25 @@ export default DiscourseRoute.extend({
let subscriptions = []; let subscriptions = [];
let customer = {}; let customer = {};
controller.set('loadingDonations', true); controller.set("loadingDonations", true);
ajax('/donate/charges').then((result) => { ajax("/donate/charges")
if (result) { .then(result => {
charges = result.charges; if (result) {
subscriptions = result.subscriptions; charges = result.charges;
customer = result.customer; subscriptions = result.subscriptions;
} customer = result.customer;
}
controller.setProperties({ controller.setProperties({
charges: Ember.A(charges), charges: Ember.A(charges),
subscriptions: Ember.A(subscriptions), subscriptions: Ember.A(subscriptions),
customer customer
});
})
.catch(popupAjaxError)
.finally(() => {
controller.set("loadingDonations", false);
}); });
}).catch(popupAjaxError).finally(() => {
controller.set('loadingDonations', false);
});
} }
}); });

View File

@ -1,86 +1,96 @@
import { createWidget } from 'discourse/widgets/widget'; import { createWidget } from "discourse/widgets/widget";
import { h } from 'virtual-dom'; import { h } from "virtual-dom";
import { avatarFor } from 'discourse/widgets/post'; import { avatarFor } from "discourse/widgets/post";
import { userPath } from "discourse/lib/url"; import { userPath } from "discourse/lib/url";
function donationDisplay(amount, type) { function donationDisplay(amount, type) {
return h(`div.donations-${type}`, [ return h(`div.donations-${type}`, [
h('span', I18n.t(`discourse_donations.cause.category.${type}`)), h("span", I18n.t(`discourse_donations.cause.category.${type}`)),
h('span', `$${(amount/100).toFixed(2)}`) h("span", `$${(amount / 100).toFixed(2)}`)
]); ]);
} }
createWidget('category-header-widget', { createWidget("category-header-widget", {
tagName: 'span', tagName: "span",
html(args) { html(args) {
const controller = this.register.lookup("controller:navigation/category");
const controller = this.register.lookup('controller:navigation/category');
const category = controller.get("category"); const category = controller.get("category");
if (args.currentPath.toLowerCase().indexOf('category') > -1 && if (
category && args.currentPath.toLowerCase().indexOf("category") > -1 &&
category.donations_cause) { category &&
category.donations_cause
) {
$("body").addClass("donations-category"); $("body").addClass("donations-category");
let contents = [ let contents = [
h('div.donations-category-contents', [ h("div.donations-category-contents", [
h('h1', category.name), h("h1", category.name),
h('div.category-title-description', h('p', category.description_text)) h("div.category-title-description", h("p", category.description_text))
]) ])
]; ];
let metadata = []; let metadata = [];
if (category.donations_total !== undefined) { if (category.donations_total !== undefined) {
metadata.push(donationDisplay(category.donations_total || 0, 'total')); metadata.push(donationDisplay(category.donations_total || 0, "total"));
if (Discourse.SiteSettings.discourse_donations_cause_month) { if (Discourse.SiteSettings.discourse_donations_cause_month) {
metadata.push(donationDisplay(category.donations_month || 0, 'month')); metadata.push(
donationDisplay(category.donations_month || 0, "month")
);
} }
} }
if (category.donations_github) { if (category.donations_github) {
metadata.push( metadata.push(
h('div.donations-github', this.attach('link', { h(
icon: 'github', "div.donations-github",
label: 'discourse_donations.cause.github.label', this.attach("link", {
href: category.donations_github icon: "github",
})) label: "discourse_donations.cause.github.label",
href: category.donations_github
})
)
); );
} }
if (category.donations_meta) { if (category.donations_meta) {
metadata.push( metadata.push(
h('div.donations-meta', this.attach('link', { h(
href: category.donations_meta, "div.donations-meta",
contents: () => { this.attach("link", {
return [ href: category.donations_meta,
h('img.meta-icon', { contents: () => {
attributes: { return [
src: 'https://discourse-meta.s3.dualstack.us-west-1.amazonaws.com/original/3X/b/1/b19ba793155a785bbd9707bc0cabbd3a987fa126.png?v=6' h("img.meta-icon", {
} attributes: {
}), src:
h('span', I18n.t('discourse_donations.cause.meta.label')) "https://discourse-meta.s3.dualstack.us-west-1.amazonaws.com/original/3X/b/1/b19ba793155a785bbd9707bc0cabbd3a987fa126.png?v=6"
]; }
} }),
})) h("span", I18n.t("discourse_donations.cause.meta.label"))
];
}
})
)
); );
} }
if (category.donations_release_oldest) { if (category.donations_release_oldest) {
let releaseArray = category.donations_release_oldest.split('/'); let releaseArray = category.donations_release_oldest.split("/");
let label = releaseArray[releaseArray.length - 1]; let label = releaseArray[releaseArray.length - 1];
metadata.push( metadata.push(
h('div.donations-release-oldest', [ h("div.donations-release-oldest", [
h('span', '>='), h("span", ">="),
this.attach('link', { this.attach("link", {
href: category.donations_release_oldest, href: category.donations_release_oldest,
icon: 'tag', icon: "tag",
rawLabel: label, rawLabel: label,
omitSpan: true, omitSpan: true,
attributes: { attributes: {
target: '_blank' target: "_blank"
} }
}) })
]) ])
@ -88,18 +98,18 @@ createWidget('category-header-widget', {
} }
if (category.donations_release_latest) { if (category.donations_release_latest) {
let releaseArray = category.donations_release_latest.split('/'); let releaseArray = category.donations_release_latest.split("/");
let label = releaseArray[releaseArray.length - 1]; let label = releaseArray[releaseArray.length - 1];
metadata.push( metadata.push(
h('div.donations-release-latest', [ h("div.donations-release-latest", [
h('span', '<='), h("span", "<="),
this.attach('link', { this.attach("link", {
href: category.donations_release_latest, href: category.donations_release_latest,
icon: 'tag', icon: "tag",
rawLabel: label, rawLabel: label,
omitSpan: true, omitSpan: true,
attributes: { attributes: {
target: '_blank' target: "_blank"
} }
}) })
]) ])
@ -107,61 +117,78 @@ createWidget('category-header-widget', {
} }
if (metadata.length) { if (metadata.length) {
contents.push(h('div.donations-category-metadata', metadata)); contents.push(h("div.donations-category-metadata", metadata));
} }
let users = []; let users = [];
if (category.donations_backers.length) { if (category.donations_backers.length) {
users.push(h('div.donations-backers', [ users.push(
h('div.donations-backers-title', I18n.t('discourse_donations.cause.backers.label')), h("div.donations-backers", [
category.donations_backers.map(user => { h(
if (user) { "div.donations-backers-title",
return avatarFor('medium', { I18n.t("discourse_donations.cause.backers.label")
template: user.avatar_template, ),
username: user.username, category.donations_backers.map(user => {
name: user.name, if (user) {
url: userPath(user.username), return avatarFor("medium", {
className: "backer-avatar" template: user.avatar_template,
}); username: user.username,
} else { name: user.name,
return; url: userPath(user.username),
} className: "backer-avatar"
}) });
])); } else {
}; return;
}
})
])
);
}
if (category.donations_maintainers.length) { if (category.donations_maintainers.length) {
let maintainersLabel = category.donations_maintainers_label || let maintainersLabel =
I18n.t('discourse_donations.cause.maintainers.label'); category.donations_maintainers_label ||
I18n.t("discourse_donations.cause.maintainers.label");
users.push(h('div.donations-maintainers', [ users.push(
h('div.donations-maintainers-title', maintainersLabel), h("div.donations-maintainers", [
category.donations_maintainers.map(user => { h("div.donations-maintainers-title", maintainersLabel),
if (user) { category.donations_maintainers.map(user => {
return avatarFor('medium', { if (user) {
template: user.avatar_template, return avatarFor("medium", {
username: user.username, template: user.avatar_template,
name: user.name, username: user.username,
url: userPath(user.username), name: user.name,
className: "maintainer-avatar" url: userPath(user.username),
}); className: "maintainer-avatar"
} else { });
return; } else {
} return;
}) }
])); })
])
);
} }
if (users.length) { if (users.length) {
contents.push(h('div.donations-category-users', users)); contents.push(h("div.donations-category-users", users));
} }
return h('div.donations-category-header', { return h(
"attributes" : { "div.donations-category-header",
"style" : "background-color: #" + category.color + "; color: #" + category.text_color + ";" {
} attributes: {
}, contents); style:
"background-color: #" +
category.color +
"; color: #" +
category.text_color +
";"
}
},
contents
);
} else { } else {
$("body").removeClass("donations-category"); $("body").removeClass("donations-category");
} }

View File

@ -1,90 +1,104 @@
function validationErrors(tagInfo, content, siteSettings) { function validationErrors(tagInfo, content, siteSettings) {
let errors = []; let errors = [];
if (!siteSettings.discourse_donations_public_key) { errors.push("missing key (site setting)"); } if (!siteSettings.discourse_donations_public_key) {
if (!siteSettings.discourse_donations_currency) { errors.push("missing currency (site setting)"); } errors.push("missing key (site setting)");
if (!siteSettings.discourse_donations_shop_name) { errors.push("missing name (site setting)"); } }
if (!siteSettings.discourse_donations_zip_code) { errors.push("missing zip code toggle (site setting)"); } if (!siteSettings.discourse_donations_currency) {
if (!siteSettings.discourse_donations_billing_address) { errors.push("missing billing address toggle (site setting)"); } errors.push("missing currency (site setting)");
if (!tagInfo.attrs['amount']) { errors.push("missing amount"); } }
if (!content) { errors.push("missing description"); } if (!siteSettings.discourse_donations_shop_name) {
return errors; errors.push("missing name (site setting)");
}
if (!siteSettings.discourse_donations_zip_code) {
errors.push("missing zip code toggle (site setting)");
}
if (!siteSettings.discourse_donations_billing_address) {
errors.push("missing billing address toggle (site setting)");
}
if (!tagInfo.attrs["amount"]) {
errors.push("missing amount");
}
if (!content) {
errors.push("missing description");
}
return errors;
} }
function replaceWithStripeOrError(siteSettings) { function replaceWithStripeOrError(siteSettings) {
return function (state, tagInfo, content) { return function(state, tagInfo, content) {
let errors = validationErrors(tagInfo, content, siteSettings); let errors = validationErrors(tagInfo, content, siteSettings);
if (errors.length) { if (errors.length) {
displayErrors(state, errors); displayErrors(state, errors);
} else { } else {
insertCheckout(state, tagInfo, content); insertCheckout(state, tagInfo, content);
} }
return true; return true;
}; };
} }
function displayErrors(state, errors) { function displayErrors(state, errors) {
let token = state.push('div-open', 'div', 1); let token = state.push("div-open", "div", 1);
token.attrs = [['class', 'stripe-errors']]; token.attrs = [["class", "stripe-errors"]];
token = state.push('html_inline', '', 0); token = state.push("html_inline", "", 0);
token.content = "Stripe checkout can't be rendered: " + errors.join(", "); token.content = "Stripe checkout can't be rendered: " + errors.join(", ");
state.push('div-close', 'div', -1); state.push("div-close", "div", -1);
} }
function insertCheckout(state, tagInfo, content) { function insertCheckout(state, tagInfo, content) {
let token = state.push('stripe-checkout-form-open', 'form', 1); let token = state.push("stripe-checkout-form-open", "form", 1);
token.attrs = [ token.attrs = [
['method', 'POST'], ["method", "POST"],
['action', '/checkout'], ["action", "/checkout"],
['content', content], ["content", content],
['image', tagInfo.attrs['image']], ["image", tagInfo.attrs["image"]],
['class', 'stripe-checkout'] ["class", "stripe-checkout"]
]; ];
token = state.push('stripe-checkout-form-amount', 'input', 0); token = state.push("stripe-checkout-form-amount", "input", 0);
token.attrs = [ token.attrs = [
['type', 'hidden'], ["type", "hidden"],
['name', 'amount'], ["name", "amount"],
['value', tagInfo.attrs['amount']] ["value", tagInfo.attrs["amount"]]
]; ];
state.push('stripe-checkout-form-close', 'form', -1); state.push("stripe-checkout-form-close", "form", -1);
} }
function setupMarkdownIt(helper, siteSettings) { function setupMarkdownIt(helper, siteSettings) {
helper.registerPlugin(md => { helper.registerPlugin(md => {
md.inline.bbcode.ruler.push('stripe-checkout', { md.inline.bbcode.ruler.push("stripe-checkout", {
tag: 'stripe', tag: "stripe",
replace: replaceWithStripeOrError(siteSettings) replace: replaceWithStripeOrError(siteSettings)
});
}); });
});
} }
export function setup(helper) { export function setup(helper) {
helper.registerOptions((opts,siteSettings)=>{ helper.registerOptions((opts, siteSettings) => {
helper.whiteList([ helper.whiteList([
'div[class]', "div[class]",
'form[method]', "form[method]",
'form[action]', "form[action]",
'form[class]', "form[class]",
'form[content]', "form[content]",
'form[image]', "form[image]",
'input[type]', "input[type]",
'input[name]', "input[name]",
'input[value]', "input[value]",
'script[class]', "script[class]",
'script[src]', "script[src]",
'script[data-key]', "script[data-key]",
'script[data-amount]', "script[data-amount]",
'script[data-name]', "script[data-name]",
'script[data-description]', "script[data-description]",
'script[data-image]', "script[data-image]",
'script[data-zip-code]', "script[data-zip-code]",
'script[data-billing-address]', "script[data-billing-address]",
'script[data-currency]', "script[data-currency]",
'script[data-locale]' "script[data-locale]"
]); ]);
if (helper.markdownIt) { if (helper.markdownIt) {
setupMarkdownIt(helper, siteSettings); setupMarkdownIt(helper, siteSettings);
} }
}); });
} }

View File

@ -28,7 +28,8 @@ div.stripe-errors {
margin: 0; margin: 0;
} }
.error, .stripe-error { .error,
.stripe-error {
margin-top: 5px; margin-top: 5px;
color: $danger; color: $danger;
} }
@ -50,7 +51,7 @@ div.stripe-errors {
background-color: $secondary; background-color: $secondary;
border: 1px solid $primary-low; border: 1px solid $primary-low;
padding: 10px; padding: 10px;
box-shadow: 0 2px 2px rgba(0,0,0,0.4); box-shadow: 0 2px 2px rgba(0, 0, 0, 0.4);
width: 400px; width: 400px;
z-index: 1; z-index: 1;
} }
@ -59,7 +60,8 @@ div.stripe-errors {
margin-bottom: 20px; margin-bottom: 20px;
.donation-list { .donation-list {
.subscription-list, .charge-list { .subscription-list,
.charge-list {
margin-bottom: 10px; margin-bottom: 10px;
> ul { > ul {
@ -120,7 +122,7 @@ div.stripe-errors {
text-align: center; text-align: center;
i { i {
margin-right: .25em; margin-right: 0.25em;
font-size: 1.5em; font-size: 1.5em;
} }
@ -147,11 +149,13 @@ div.stripe-errors {
justify-content: space-around; justify-content: space-around;
font-size: 1.2rem; font-size: 1.2rem;
.donations-total span:first-of-type, .donations-month span:first-of-type { .donations-total span:first-of-type,
.donations-month span:first-of-type {
margin-right: 5px; margin-right: 5px;
} }
.donations-github a, .donations-meta a { .donations-github a,
.donations-meta a {
color: inherit; color: inherit;
} }
@ -167,7 +171,8 @@ div.stripe-errors {
} }
} }
.donations-release-latest, .donations-release-oldest { .donations-release-latest,
.donations-release-oldest {
display: flex; display: flex;
align-items: center; align-items: center;
@ -189,15 +194,18 @@ div.stripe-errors {
display: flex; display: flex;
align-items: center; align-items: center;
.donations-backers, .donations-maintainers { .donations-backers,
.donations-maintainers {
flex: 1 1 auto; flex: 1 1 auto;
} }
.backer-avatar, .maintainer-avatar { .backer-avatar,
.maintainer-avatar {
margin: 0 5px; margin: 0 5px;
} }
.donations-backers-title, .donations-maintainers-title { .donations-backers-title,
.donations-maintainers-title {
padding-bottom: 10px; padding-bottom: 10px;
} }
} }

View File

@ -1,8 +1,8 @@
import componentTest from 'helpers/component-test'; import componentTest from "helpers/component-test";
moduleForComponent('donation-form', { integration: true }); moduleForComponent("donation-form", { integration: true });
componentTest('donation form', { componentTest("donation form", {
template: `{{donation-form}}`, template: `{{donation-form}}`,
test(assert) { test(assert) {

View File

@ -1,26 +1,26 @@
import componentTest from 'helpers/component-test'; import componentTest from "helpers/component-test";
moduleForComponent('donation-row', { integration: true }); moduleForComponent("donation-row", { integration: true });
componentTest('donation-row', { componentTest("donation-row", {
template: `{{donation-row currency=3 amount=21 period='monthly'}}`, template: `{{donation-row currency=3 amount=21 period='monthly'}}`,
test(assert) { test(assert) {
assert.equal(find('.donation-row-currency').text(), '3'); assert.equal(find(".donation-row-currency").text(), "3");
assert.equal(find('.donation-row-amount').text(), '21'); assert.equal(find(".donation-row-amount").text(), "21");
assert.equal(find('.donation-row-period').text(), 'monthly'); assert.equal(find(".donation-row-period").text(), "monthly");
}, }
}); });
componentTest('donation-row cancels subscription', { componentTest("donation-row cancels subscription", {
template: `{{donation-row currentUser=currentUser subscription=subscription}}`, template: `{{donation-row currentUser=currentUser subscription=subscription}}`,
beforeEach() { beforeEach() {
this.set('currentUser', true); this.set("currentUser", true);
this.set('subscription', true); this.set("subscription", true);
}, },
async test(assert) { async test(assert) {
assert.ok(find('.donation-row-subscription').length); assert.ok(find(".donation-row-subscription").length);
}, }
}); });

View File

@ -1,6 +1,6 @@
import componentTest from 'helpers/component-test'; import componentTest from "helpers/component-test";
moduleForComponent('stripe-card', { integration: true }); moduleForComponent("stripe-card", { integration: true });
window.Stripe = function() { window.Stripe = function() {
return { return {
@ -13,18 +13,18 @@ window.Stripe = function() {
}; };
} }
}; };
}, }
}; };
}; };
componentTest('stripe card', { componentTest("stripe card", {
template: `{{stripe-card donateAmounts=donateAmounts}}`, template: `{{stripe-card donateAmounts=donateAmounts}}`,
skip: true, skip: true,
beforeEach() { beforeEach() {
Discourse.SiteSettings.discourse_donations_types = ''; Discourse.SiteSettings.discourse_donations_types = "";
this.set('donateAmounts', [{ value: 2 }]); this.set("donateAmounts", [{ value: 2 }]);
}, },
test(assert) { test(assert) {