Skip to content

Commit

Permalink
Convert Order model to expected typescript (#10066)
Browse files Browse the repository at this point in the history
* convert Order model to expected typescript
  • Loading branch information
znarf authored Apr 29, 2024
1 parent aa18000 commit c06e65c
Show file tree
Hide file tree
Showing 22 changed files with 410 additions and 318 deletions.
6 changes: 3 additions & 3 deletions cron/hourly/70-handle-batch-subscriptions-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import logger from '../../server/lib/logger';
import { reportErrorToSentry } from '../../server/lib/sentry';
import { parseToBoolean, sleep } from '../../server/lib/utils';
import models, { Collective, Op } from '../../server/models';
import { OrderModelInterface } from '../../server/models/Order';
import Order from '../../server/models/Order';
import { CONTRIBUTION_PAUSED_MSG } from '../../server/paymentProviders/paypal/subscription';

if (parseToBoolean(process.env.SKIP_BATCH_SUBSCRIPTION_UPDATE)) {
Expand Down Expand Up @@ -49,7 +49,7 @@ const getHostFromOrder = async order => {

const getOrderCancelationReason = (
collective: Collective,
order: OrderModelInterface,
order: Order,
orderHost: Collective,
): {
code: 'PAUSED' | 'DELETED_TIER' | 'ARCHIVED_ACCOUNT' | 'UNHOSTED_COLLECTIVE' | 'CHANGED_HOST' | 'CANCELLED_ORDER';
Expand All @@ -76,7 +76,7 @@ const getOrderCancelationReason = (
* performance constraints.
*/
export async function run() {
const orphanOrders = await models.Order.findAll<OrderModelInterface>({
const orphanOrders = await models.Order.findAll<Order>({
where: {
status: [OrderStatuses.CANCELLED, OrderStatuses.PAUSED],
data: { needsAsyncDeactivation: true },
Expand Down
4 changes: 2 additions & 2 deletions scripts/paypal/cancel-all-subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { flatten, get, uniq } from 'lodash';
import OrderStatuses from '../../server/constants/order-status';
import logger from '../../server/lib/logger';
import models, { Op } from '../../server/models';
import { OrderModelInterface } from '../../server/models/Order';
import Order from '../../server/models/Order';
import { TransactionInterface } from '../../server/models/Transaction';
import { paypalRequestV2 } from '../../server/paymentProviders/paypal/api';
import { getCaptureIdFromPaypalTransaction } from '../../server/paymentProviders/paypal/payment';
Expand Down Expand Up @@ -65,7 +65,7 @@ const main = async () => {
throw new Error(`Collective ${collectiveSlug} not found`);
}

const orders = await models.Order.findAll<OrderModelInterface & { Transaction?: TransactionInterface }>({
const orders = await models.Order.findAll<Order & { Transaction?: TransactionInterface }>({
order: [['createdAt', 'DESC']],
where: {
CollectiveId: collective.id,
Expand Down
6 changes: 3 additions & 3 deletions server/graphql/common/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import models from '../../models';
import Comment, { CommentType } from '../../models/Comment';
import Conversation from '../../models/Conversation';
import Expense, { ExpenseStatus } from '../../models/Expense';
import { OrderModelInterface } from '../../models/Order';
import Order from '../../models/Order';
import Update from '../../models/Update';
import { NotFound, Unauthorized, ValidationFailed } from '../errors';
import { canComment as canCommentOrder } from '../v2/object/OrderPermissions';
Expand All @@ -15,7 +15,7 @@ import { canComment as canCommentExpense, canUsePrivateNotes as canUseExpensePri
import { checkRemoteUserCanUseComment } from './scope-check';
import { canSeeUpdate } from './update';

type CommentableEntity = Update | Expense | Conversation | OrderModelInterface;
type CommentableEntity = Update | Expense | Conversation | Order;

const loadCommentedEntity = async (commentValues): Promise<[CommentableEntity, ActivityTypes]> => {
const include = { association: 'collective', required: true };
Expand All @@ -32,7 +32,7 @@ const loadCommentedEntity = async (commentValues): Promise<[CommentableEntity, A
entity = (await Update.findByPk(commentValues.UpdateId, { include })) as Update;
activityType = ActivityTypes.UPDATE_COMMENT_CREATED;
} else if (commentValues.OrderId) {
entity = (await models.Order.findByPk(commentValues.OrderId, { include })) as OrderModelInterface;
entity = (await models.Order.findByPk(commentValues.OrderId, { include })) as Order;
activityType = ActivityTypes.ORDER_COMMENT_CREATED;
}

Expand Down
4 changes: 2 additions & 2 deletions server/graphql/common/orders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import status from '../../constants/order-status';
import { purgeCacheForCollective } from '../../lib/cache';
import { executeOrder } from '../../lib/payments';
import models, { AccountingCategory, Collective, Tier, User } from '../../models';
import { OrderModelInterface } from '../../models/Order';
import Order from '../../models/Order';
import { ValidationFailed } from '../errors';
import { getOrderTaxInfoFromTaxInput } from '../v1/mutations/orders';
import { TaxInput } from '../v2/input/TaxInput';
Expand Down Expand Up @@ -74,7 +74,7 @@ export async function addFunds(order: AddFundsInput, remoteUser: User) {
checkCanUseAccountingCategoryForOrder(order.accountingCategory, host.id);
}

const orderData: Partial<InferCreationAttributes<OrderModelInterface>> = {
const orderData: Partial<InferCreationAttributes<Order>> = {
CreatedByUserId: remoteUser.id,
FromCollectiveId: fromCollective.id,
CollectiveId: collective.id,
Expand Down
4 changes: 2 additions & 2 deletions server/lib/collectivelib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import models, { Collective, Member, Op, sequelize } from '../models';
import Expense from '../models/Expense';
import { MemberModelInterface } from '../models/Member';
import { MemberInvitationModelInterface } from '../models/MemberInvitation';
import { OrderModelInterface } from '../models/Order';
import Order from '../models/Order';
import { PaymentMethodModelInterface } from '../models/PaymentMethod';

import logger from './logger';
Expand Down Expand Up @@ -399,7 +399,7 @@ export async function deleteCollective(collective) {
status: { [Op.not]: ['PAID', 'ACTIVE', 'CANCELLED'] },
},
});
await map(orders, (order: OrderModelInterface) => order.destroy(), { concurrency: 3 });
await map(orders, (order: Order) => order.destroy(), { concurrency: 3 });

const expenses = await models.Expense.findAll({
where: {
Expand Down
38 changes: 18 additions & 20 deletions server/lib/payments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { TransactionKind } from '../constants/transaction-kind';
import { TransactionTypes } from '../constants/transactions';
import { Op } from '../models';
import Activity from '../models/Activity';
import Order, { OrderModelInterface } from '../models/Order';
import Order from '../models/Order';
import PaymentMethod, { PaymentMethodModelInterface } from '../models/PaymentMethod';
import PayoutMethod, { PayoutMethodTypes } from '../models/PayoutMethod';
import Subscription from '../models/Subscription';
Expand Down Expand Up @@ -110,7 +110,7 @@ export function findPaymentMethodProvider(
* the `PaymentMethods` table.
*/
export async function processOrder(
order: OrderModelInterface,
order: Order,
options: { isAddedFund?: boolean; invoiceTemplate?: string } = {},
): Promise<TransactionInterface | void> {
const paymentMethodProvider = findPaymentMethodProvider(order.paymentMethod);
Expand Down Expand Up @@ -614,7 +614,8 @@ export async function associateTransactionRefundId(
* In all cases, transaction.type is CREDIT.
*
*/
export const sendEmailNotifications = (order: OrderModelInterface, transaction?: TransactionInterface | void): void => {

export const sendEmailNotifications = (order: Order, transaction?: TransactionInterface | void): void => {
debug('sendEmailNotifications');
if (
transaction &&
Expand Down Expand Up @@ -643,7 +644,7 @@ export const sendEmailNotifications = (order: OrderModelInterface, transaction?:
}
};

export const createSubscription = async (order: OrderModelInterface): Promise<void> => {
export const createSubscription = async (order: Order): Promise<void> => {
const subscription = await Subscription.create({
amount: order.totalAmount,
interval: order.interval,
Expand Down Expand Up @@ -680,7 +681,7 @@ export const createSubscription = async (order: OrderModelInterface): Promise<vo
*/
export const executeOrder = async (
user: User,
order: OrderModelInterface,
order: Order,
options: { isAddedFund?: boolean; invoiceTemplate?: string } = {},
): Promise<void> => {
if (!(user instanceof User)) {
Expand Down Expand Up @@ -772,10 +773,7 @@ const validatePayment = (payment): void => {
}
};

const sendOrderConfirmedEmail = async (
order: OrderModelInterface,
transaction: TransactionInterface,
): Promise<void> => {
const sendOrderConfirmedEmail = async (order: Order, transaction: TransactionInterface): Promise<void> => {
const attachments = [];
const { collective, interval, fromCollective, paymentMethod } = order;
const user = await order.getUserForActivity();
Expand Down Expand Up @@ -864,7 +862,7 @@ const sendOrderConfirmedEmail = async (
};

// Assumes one-time payments,
export const sendOrderPendingEmail = async (order: OrderModelInterface): Promise<void> => {
export const sendOrderPendingEmail = async (order: Order): Promise<void> => {
const { collective, fromCollective } = order;
const user = order.createdByUser;
const host = await collective.getHostCollective();
Expand Down Expand Up @@ -916,7 +914,7 @@ export const sendOrderPendingEmail = async (order: OrderModelInterface): Promise
});
};

const sendOrderProcessingEmail = async (order: OrderModelInterface): Promise<void> => {
const sendOrderProcessingEmail = async (order: Order): Promise<void> => {
const { collective, fromCollective } = order;
const user = order.createdByUser;
const host = await collective.getHostCollective();
Expand All @@ -940,7 +938,7 @@ const sendOrderProcessingEmail = async (order: OrderModelInterface): Promise<voi
});
};

export const sendOrderFailedEmail = async (order: OrderModelInterface, reason: string): Promise<void> => {
export const sendOrderFailedEmail = async (order: Order, reason: string): Promise<void> => {
const user = order.createdByUser;
const { collective, fromCollective } = order;
const host = await collective.getHostCollective();
Expand All @@ -965,7 +963,7 @@ export const sendOrderFailedEmail = async (order: OrderModelInterface, reason: s
});
};

const sendManualPendingOrderEmail = async (order: OrderModelInterface): Promise<void> => {
const sendManualPendingOrderEmail = async (order: Order): Promise<void> => {
const { collective, fromCollective } = order;
const host = await collective.getHostCollective();

Expand Down Expand Up @@ -1001,7 +999,7 @@ const sendManualPendingOrderEmail = async (order: OrderModelInterface): Promise<
});
};

export const sendReminderPendingOrderEmail = async (order: OrderModelInterface): Promise<void> => {
export const sendReminderPendingOrderEmail = async (order: Order): Promise<void> => {
const { collective, fromCollective } = order;
const host = await collective.getHostCollective();

Expand Down Expand Up @@ -1043,7 +1041,7 @@ export const sendExpiringCreditCardUpdateEmail = async (data): Promise<void> =>
});
};

export const getApplicationFee = async (order: OrderModelInterface): Promise<number> => {
export const getApplicationFee = async (order: Order): Promise<number> => {
let applicationFee = 0;

if (order.platformTipAmount) {
Expand All @@ -1060,7 +1058,7 @@ export const getApplicationFee = async (order: OrderModelInterface): Promise<num
return applicationFee;
};

export const getPlatformTip = (order: OrderModelInterface): number => {
export const getPlatformTip = (order: Order): number => {
if (!isNil(order.platformTipAmount)) {
return order.platformTipAmount;
}
Expand All @@ -1071,7 +1069,7 @@ export const getPlatformTip = (order: OrderModelInterface): number => {
return 0;
};

export const getHostFee = async (order: OrderModelInterface): Promise<number> => {
export const getHostFee = async (order: Order): Promise<number> => {
const totalAmount = order.totalAmount || 0;
const taxAmount = order.taxAmount || 0;
const platformTipAmount = order.platformTipAmount || 0;
Expand All @@ -1081,7 +1079,7 @@ export const getHostFee = async (order: OrderModelInterface): Promise<number> =>
return calcFee(totalAmount - taxAmount - platformTipAmount, hostFeePercent);
};

export const isPlatformTipEligible = async (order: OrderModelInterface): Promise<boolean> => {
export const isPlatformTipEligible = async (order: Order): Promise<boolean> => {
if (!isNil(order.platformTipEligible)) {
return order.platformTipEligible;
}
Expand Down Expand Up @@ -1110,7 +1108,7 @@ export const isPlatformTipEligible = async (order: OrderModelInterface): Promise
};

export const getHostFeePercent = async (
order: OrderModelInterface,
order: Order,
{ loaders = null }: { loaders?: loaders } = {},
): Promise<number> => {
const collective =
Expand Down Expand Up @@ -1251,7 +1249,7 @@ export const getHostFeePercent = async (
};

export const getHostFeeSharePercent = async (
order: OrderModelInterface,
order: Order,
{ loaders = null }: { loaders?: loaders } = {},
): Promise<number> => {
if (!order.collective) {
Expand Down
12 changes: 6 additions & 6 deletions server/lib/subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { PAYMENT_METHOD_SERVICE, PAYMENT_METHOD_TYPE } from '../constants/paymen
import { BadRequest, Unauthorized, UnexpectedError } from '../graphql/errors';
import { sequelize } from '../models';
import { MemberModelInterface } from '../models/Member';
import { OrderModelInterface } from '../models/Order';
import Order from '../models/Order';
import { PaymentMethodModelInterface } from '../models/PaymentMethod';
import Tier from '../models/Tier';
import User from '../models/User';
Expand Down Expand Up @@ -42,9 +42,9 @@ const getNextChargeDateForUpdateContribution = (baseNextChargeDate, newInterval)

export const updatePaymentMethodForSubscription = async (
user: User,
order: OrderModelInterface,
order: Order,
newPaymentMethod: PaymentMethodModelInterface,
): Promise<OrderModelInterface> => {
): Promise<Order> => {
const prevPaymentMethod = order.paymentMethod;
const newPaymentMethodCollective = await newPaymentMethod.getCollective();
if (!user.isAdminOfCollective(newPaymentMethodCollective)) {
Expand Down Expand Up @@ -133,7 +133,7 @@ const checkSubscriptionDetails = (order, tier: Tier, amountInCents) => {
};

type OrderSubscriptionUpdate = {
order: OrderModelInterface;
order: Order;
previousOrderValues: Record<string, unknown>;
previousSubscriptionValues: Record<string, unknown>;
};
Expand All @@ -143,7 +143,7 @@ type OrderSubscriptionUpdate = {
* for each, to easily rollback if necessary.
*/
export const updateOrderSubscription = async (
order: OrderModelInterface,
order: Order,
member: MemberModelInterface,
newOrderData: Record<string, unknown>,
newSubscriptionData: Record<string, unknown>,
Expand Down Expand Up @@ -174,7 +174,7 @@ export const updateOrderSubscription = async (
};

export const updateSubscriptionDetails = async (
order: OrderModelInterface,
order: Order,
tier: Tier,
member: MemberModelInterface,
amountInCents: number,
Expand Down
6 changes: 3 additions & 3 deletions server/models/AccountingCategory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import sequelize, { DataTypes, Model } from '../lib/sequelize';
import Activity from './Activity';
import Collective from './Collective';
import Expense from './Expense';
import { OrderModelInterface } from './Order';
import Order from './Order';
import User from './User';

type AccountingCategoryCreationAttributes = InferCreationAttributes<
Expand Down Expand Up @@ -60,11 +60,11 @@ class AccountingCategory extends Model<InferAttributes<AccountingCategory>, Acco
// Associations
declare getCollective: BelongsToGetAssociationMixin<Collective>;
declare getExpenses: HasManyGetAssociationsMixin<Expense>;
declare getOrders: HasManyGetAssociationsMixin<OrderModelInterface>;
declare getOrders: HasManyGetAssociationsMixin<Order>;

declare collective?: Collective;
declare expenses?: Expense[];
declare orders?: OrderModelInterface[];
declare orders?: Order[];

// Static methods
public static async createEditActivity(
Expand Down
Loading

0 comments on commit c06e65c

Please sign in to comment.