* feat: add time-based cancellation fees for no-show fee events - Add configurable time threshold (minutes/hours/days) for cancellation fees - Show warnings during booking submission and cancellation - Automatically charge fees when bookings cancelled within threshold - Exempt organizer/admin cancellations from fees - Extend existing no-show fee infrastructure Co-Authored-By: [email protected] <[email protected]> * fix: replace any type with proper type guards for metadata - Use Record<string, unknown> instead of any for metadata type - Add proper type assertions for nested metadata properties - Maintain type safety while avoiding ESLint no-explicit-any warning Co-Authored-By: [email protected] <[email protected]> * fix: handle JsonValue type compatibility in shouldChargeCancellationFee - Add proper type guard for metadata JsonValue from Prisma - Ensure metadata is object before casting to Record<string, unknown> - Fixes TypeScript error on line 390 in handleCancelBooking.ts Co-Authored-By: [email protected] <[email protected]> * Refactor Devin changes to Stripe options * Undo Devin changes to advanced tab * Add translations * Pass props to CancelBooking * Display no show fee charge for attendee * WIP * Anstract shouldChargeNoSHowCancellationFee * Abstract `handleNoShowFee` * Add to * Refactor `chargeCard.handler` * Remove Devin code * Type fix in `shouldChargeNoShowCancellationFee` * Create `processNoSHowFeeOnCancellation` * Process no show fee on cancellation * Type fix * Skip processing no show fee if organizer or admin is cancelling * Add translation * Dynamically get and in * Remove unused translations * Undo dev change * Refactor logic * Type fix * remove any * revert WEBAPP_URL_FOR_OAUTH * Clean up console.log remnants * test: add comprehensive tests for time-based cancellation fees - Add unit tests for shouldChargeCancellationFee function with time thresholds and role exemptions - Add handleCancelBooking integration tests for organizer/team admin exemptions - Add handleCancelBooking test for attendee fee charging within time threshold - Add UI component tests for cancellation fee warning display - Add E2E test for cancellation fee warning during booking flow All 23 new tests pass successfully, covering: - Time-based logic with different units (minutes, hours, days) - Role-based exemptions (organizer, team admin vs regular attendee) - Payment charging integration with HOLD payment option - UI warning display during booking submission and cancellation - Edge cases like invalid metadata and past bookings Fixed lint issues: - Replaced 'any' types with proper Record<string, unknown> - Fixed Playwright test.skip() usage with ESLint disable comments Co-Authored-By: [email protected] <[email protected]> * test: add comprehensive tests for time-based cancellation fees - Add unit tests for shouldChargeCancellationFee function with time thresholds and role exemptions - Add handleCancelBooking integration tests for organizer/team admin exemptions - Add handleCancelBooking test for attendee fee charging within time threshold - Add UI component tests for cancellation fee warning display - Add E2E test for cancellation fee warning during booking flow All unit and integration tests pass successfully. E2E test implementation complete. Co-Authored-By: [email protected] <[email protected]> * test: add comprehensive tests for time-based cancellation fees - Add unit tests for shouldChargeCancellationFee function with time thresholds and role exemptions - Add handleCancelBooking integration tests for organizer/team admin exemptions - Add handleCancelBooking test for attendee fee charging within time threshold - Add UI component tests for cancellation fee warning display - Add E2E test for cancellation fee warning during booking flow - Fix TypeScript issues and prettier formatting - All tests follow existing Cal.com patterns and pass locally Co-Authored-By: [email protected] <[email protected]> * test: add comprehensive unit and E2E tests for time-based cancellation fees - Add unit tests for shouldChargeCancellationFee function with time thresholds and role exemptions - Add handleCancelBooking integration tests for organizer/team admin exemptions and attendee fee charging - Add UI component tests for cancellation fee warning display in CancelBooking component - Add E2E test for cancellation fee warning during booking flow - Fix TypeScript errors in CancelBooking.tsx with proper type annotations - All tests follow existing Cal.com patterns and use proper mocking/test utilities Co-Authored-By: [email protected] <[email protected]> * Revert dev change * Add missing translation * Remove Devin code * Revert Devin changes * test: fix attendee cancellation test logic and ensure comprehensive test coverage - Fix userId in attendee cancellation test to properly test fee charging - Ensure all test files follow Cal.com patterns with proper mocking - Add comprehensive coverage for time thresholds, role exemptions, and UI warnings - All tests pass locally with proper timezone handling Co-Authored-By: [email protected] <[email protected]> * Fix tests * test: add comprehensive unit tests for no-show fee payment functions - Add unit tests for handleNoShowFee.ts covering successful scenarios, error handling, and edge cases - Add unit tests for processNoShowFeeOnCancellation.ts covering cancellation logic and payment conditions - Tests include proper mocking of dependencies and comprehensive coverage of all code paths - All tests pass with TZ=UTC yarn test and type checking passes Co-Authored-By: [email protected] <[email protected]> * Don't block cancel flow for failed payment processing * Await single attendee getTranslation in `handleNoShowFee` * Add missing data * Undo old strings * Type fix --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Syed Ali Shahbaz <[email protected]> Co-authored-by: Alex van Andel <[email protected]>
454 lines
13 KiB
TypeScript
454 lines
13 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from "vitest";
|
|
|
|
// eslint-disable-next-line no-restricted-imports
|
|
import { PaymentServiceMap } from "@calcom/app-store/payment.services.generated";
|
|
import { sendNoShowFeeChargedEmail } from "@calcom/emails";
|
|
import { ErrorCode } from "@calcom/lib/errorCodes";
|
|
import { ErrorWithCode } from "@calcom/lib/errors";
|
|
import { getTranslation } from "@calcom/lib/server/i18n";
|
|
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
|
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
|
|
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
|
|
|
import { handleNoShowFee } from "./handleNoShowFee";
|
|
|
|
vi.mock("@calcom/app-store/payment.services.generated", () => ({
|
|
PaymentServiceMap: {
|
|
stripepayment: Promise.resolve({
|
|
PaymentService: vi.fn().mockImplementation(() => ({
|
|
chargeCard: vi.fn(),
|
|
})),
|
|
}),
|
|
},
|
|
}));
|
|
|
|
vi.mock("@calcom/emails", () => ({
|
|
sendNoShowFeeChargedEmail: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("@calcom/lib/server/i18n", () => ({
|
|
getTranslation: vi.fn().mockResolvedValue((key: string) => key),
|
|
}));
|
|
|
|
vi.mock("@calcom/lib/server/repository/credential", () => ({
|
|
CredentialRepository: {
|
|
findPaymentCredentialByAppIdAndUserIdOrTeamId: vi.fn(),
|
|
findPaymentCredentialByAppIdAndTeamId: vi.fn(),
|
|
},
|
|
}));
|
|
|
|
vi.mock("@calcom/lib/server/repository/membership", () => ({
|
|
MembershipRepository: {
|
|
findUniqueByUserIdAndTeamId: vi.fn(),
|
|
},
|
|
}));
|
|
|
|
vi.mock("@calcom/lib/server/repository/team", () => ({
|
|
TeamRepository: vi.fn().mockImplementation(() => ({
|
|
findParentOrganizationByTeamId: vi.fn(),
|
|
})),
|
|
}));
|
|
|
|
vi.mock("@calcom/prisma", () => ({
|
|
default: {},
|
|
}));
|
|
|
|
describe("handleNoShowFee", () => {
|
|
let mockPaymentService: { chargeCard: ReturnType<typeof vi.fn> };
|
|
|
|
beforeEach(async () => {
|
|
vi.clearAllMocks();
|
|
mockPaymentService = {
|
|
chargeCard: vi.fn(),
|
|
};
|
|
|
|
const paymentServiceModule = await PaymentServiceMap.stripepayment;
|
|
vi.mocked(paymentServiceModule.PaymentService).mockImplementation(() => mockPaymentService);
|
|
});
|
|
|
|
const mockBooking = {
|
|
id: 1,
|
|
uid: "booking-123",
|
|
title: "Test Meeting",
|
|
startTime: new Date("2024-09-01T10:00:00Z"),
|
|
endTime: new Date("2024-09-01T11:00:00Z"),
|
|
userPrimaryEmail: "[email protected]",
|
|
userId: 1,
|
|
user: {
|
|
email: "[email protected]",
|
|
name: "John Organizer",
|
|
locale: "en",
|
|
timeZone: "UTC",
|
|
},
|
|
eventType: {
|
|
title: "Test Event Type",
|
|
hideOrganizerEmail: false,
|
|
teamId: null,
|
|
metadata: {},
|
|
},
|
|
attendees: [
|
|
{
|
|
name: "Jane Attendee",
|
|
email: "[email protected]",
|
|
timeZone: "UTC",
|
|
locale: "en",
|
|
},
|
|
],
|
|
};
|
|
|
|
const mockPayment = {
|
|
id: 1,
|
|
amount: 5000,
|
|
currency: "USD",
|
|
paymentOption: "HOLD",
|
|
appId: "stripepayment",
|
|
};
|
|
|
|
const mockCredential = {
|
|
id: 1,
|
|
type: "stripepayment_payment",
|
|
key: { test: "key" },
|
|
userId: 1,
|
|
teamId: null,
|
|
appId: "stripepayment",
|
|
invalid: false,
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
app: {
|
|
keys: { test: "key" },
|
|
slug: "stripepayment",
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
dirName: "stripepayment",
|
|
categories: ["payment"],
|
|
enabled: true,
|
|
},
|
|
};
|
|
|
|
describe("successful scenarios", () => {
|
|
it("should successfully process no-show fee for individual user", async () => {
|
|
mockPaymentService.chargeCard.mockResolvedValue({ success: true, paymentId: "pay_123" });
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
vi.mocked(sendNoShowFeeChargedEmail).mockResolvedValue(undefined);
|
|
|
|
const result = await handleNoShowFee({
|
|
booking: mockBooking,
|
|
payment: mockPayment,
|
|
});
|
|
|
|
expect(result).toEqual({ success: true, paymentId: "pay_123" });
|
|
expect(mockPaymentService.chargeCard).toHaveBeenCalledWith(mockPayment, mockBooking.id);
|
|
expect(sendNoShowFeeChargedEmail).toHaveBeenCalled();
|
|
});
|
|
|
|
it("should successfully process no-show fee for team event", async () => {
|
|
const teamBooking = {
|
|
...mockBooking,
|
|
eventType: {
|
|
...mockBooking.eventType,
|
|
teamId: 1,
|
|
},
|
|
};
|
|
|
|
mockPaymentService.chargeCard.mockResolvedValue({ success: true, paymentId: "pay_123" });
|
|
|
|
vi.mocked(MembershipRepository.findUniqueByUserIdAndTeamId).mockResolvedValue({
|
|
id: 1,
|
|
userId: 1,
|
|
teamId: 1,
|
|
role: "MEMBER",
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
disableImpersonation: false,
|
|
accepted: true,
|
|
customRoleId: null,
|
|
});
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
|
|
const result = await handleNoShowFee({
|
|
booking: teamBooking,
|
|
payment: mockPayment,
|
|
});
|
|
|
|
expect(result).toEqual({ success: true, paymentId: "pay_123" });
|
|
expect(MembershipRepository.findUniqueByUserIdAndTeamId).toHaveBeenCalledWith({
|
|
userId: 1,
|
|
teamId: 1,
|
|
});
|
|
});
|
|
|
|
it("should find credential from parent organization when team credential not found", async () => {
|
|
const teamBooking = {
|
|
...mockBooking,
|
|
eventType: {
|
|
...mockBooking.eventType,
|
|
teamId: 1,
|
|
},
|
|
};
|
|
|
|
mockPaymentService.chargeCard.mockResolvedValue({ success: true, paymentId: "pay_123" });
|
|
|
|
vi.mocked(MembershipRepository.findUniqueByUserIdAndTeamId).mockResolvedValue({
|
|
id: 1,
|
|
userId: 1,
|
|
teamId: 1,
|
|
role: "MEMBER",
|
|
createdAt: new Date(),
|
|
updatedAt: new Date(),
|
|
disableImpersonation: false,
|
|
accepted: true,
|
|
customRoleId: null,
|
|
});
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId)
|
|
.mockResolvedValueOnce(null)
|
|
.mockResolvedValueOnce(mockCredential);
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndTeamId).mockResolvedValue(mockCredential);
|
|
|
|
const mockTeamRepository = {
|
|
findParentOrganizationByTeamId: vi.fn().mockResolvedValue({ id: 2 }),
|
|
};
|
|
vi.mocked(TeamRepository).mockImplementation(() => mockTeamRepository);
|
|
|
|
const result = await handleNoShowFee({
|
|
booking: teamBooking,
|
|
payment: mockPayment,
|
|
});
|
|
|
|
expect(result).toEqual({ success: true, paymentId: "pay_123" });
|
|
expect(mockTeamRepository.findParentOrganizationByTeamId).toHaveBeenCalledWith(1);
|
|
expect(CredentialRepository.findPaymentCredentialByAppIdAndTeamId).toHaveBeenCalledWith({
|
|
appId: "stripepayment",
|
|
teamId: 2,
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("error scenarios", () => {
|
|
it("should throw error when userId is missing", async () => {
|
|
const bookingWithoutUser = {
|
|
...mockBooking,
|
|
userId: null,
|
|
};
|
|
|
|
await expect(
|
|
handleNoShowFee({
|
|
booking: bookingWithoutUser,
|
|
payment: mockPayment,
|
|
})
|
|
).rejects.toThrow("User ID is required");
|
|
});
|
|
|
|
it("should throw error when user is not a member of the team", async () => {
|
|
const teamBooking = {
|
|
...mockBooking,
|
|
eventType: {
|
|
...mockBooking.eventType,
|
|
teamId: 1,
|
|
},
|
|
};
|
|
|
|
vi.mocked(MembershipRepository.findUniqueByUserIdAndTeamId).mockResolvedValue(null);
|
|
|
|
await expect(
|
|
handleNoShowFee({
|
|
booking: teamBooking,
|
|
payment: mockPayment,
|
|
})
|
|
).rejects.toThrow("User is not a member of the team");
|
|
});
|
|
|
|
it("should throw error when no payment credential is found", async () => {
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockReset();
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndTeamId).mockReset();
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(null);
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndTeamId).mockResolvedValue(null);
|
|
|
|
const bookingWithoutCredential = {
|
|
...mockBooking,
|
|
eventType: {
|
|
...mockBooking.eventType,
|
|
teamId: null,
|
|
},
|
|
};
|
|
|
|
await expect(
|
|
handleNoShowFee({
|
|
booking: bookingWithoutCredential,
|
|
payment: mockPayment,
|
|
})
|
|
).rejects.toThrow("No payment credential found");
|
|
});
|
|
|
|
it("should throw error when payment app is not implemented", async () => {
|
|
const paymentWithUnknownApp = {
|
|
...mockPayment,
|
|
appId: "unknown-app",
|
|
};
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockImplementation(
|
|
async () => ({
|
|
...mockCredential,
|
|
app: {
|
|
...mockCredential.app,
|
|
dirName: "unknown-app",
|
|
},
|
|
})
|
|
);
|
|
|
|
await expect(
|
|
handleNoShowFee({
|
|
booking: mockBooking,
|
|
payment: paymentWithUnknownApp,
|
|
})
|
|
).rejects.toThrow("Payment app not implemented");
|
|
});
|
|
|
|
it("should throw error when payment service is not found", async () => {
|
|
const originalStripepayment = PaymentServiceMap.stripepayment;
|
|
// @ts-expect-error - Mocking for test
|
|
PaymentServiceMap.stripepayment = Promise.resolve({});
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
|
|
try {
|
|
await expect(
|
|
handleNoShowFee({
|
|
booking: mockBooking,
|
|
payment: mockPayment,
|
|
})
|
|
).rejects.toThrow("Payment service not found");
|
|
} finally {
|
|
// @ts-expect-error - Restoring for test
|
|
PaymentServiceMap.stripepayment = originalStripepayment;
|
|
}
|
|
});
|
|
|
|
it("should throw error when payment processing fails", async () => {
|
|
mockPaymentService.chargeCard.mockResolvedValue(null);
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
|
|
await expect(
|
|
handleNoShowFee({
|
|
booking: mockBooking,
|
|
payment: mockPayment,
|
|
})
|
|
).rejects.toThrow("Payment processing failed");
|
|
});
|
|
|
|
it("should handle ChargeCardFailure error with proper message", async () => {
|
|
mockPaymentService.chargeCard.mockRejectedValue(
|
|
new ErrorWithCode(ErrorCode.ChargeCardFailure, "Card declined")
|
|
);
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
vi.mocked(getTranslation).mockResolvedValue((key: string) => `Translated: ${key}`);
|
|
|
|
await expect(
|
|
handleNoShowFee({
|
|
booking: mockBooking,
|
|
payment: mockPayment,
|
|
})
|
|
).rejects.toThrow("Translated: Card declined");
|
|
});
|
|
|
|
it("should handle generic payment errors", async () => {
|
|
mockPaymentService.chargeCard.mockRejectedValue(new Error("Generic payment error"));
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
vi.mocked(getTranslation).mockResolvedValue((key: string) => `Translated: ${key}`);
|
|
|
|
await expect(
|
|
handleNoShowFee({
|
|
booking: mockBooking,
|
|
payment: mockPayment,
|
|
})
|
|
).rejects.toThrow(/Translated: Error processing paymentId 1 with error/);
|
|
});
|
|
});
|
|
|
|
describe("edge cases", () => {
|
|
it("should handle booking without event type", async () => {
|
|
const bookingWithoutEventType = {
|
|
...mockBooking,
|
|
eventType: null,
|
|
};
|
|
|
|
mockPaymentService.chargeCard.mockResolvedValue({ success: true, paymentId: "pay_123" });
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
|
|
const result = await handleNoShowFee({
|
|
booking: bookingWithoutEventType,
|
|
payment: mockPayment,
|
|
});
|
|
|
|
expect(result).toEqual({ success: true, paymentId: "pay_123" });
|
|
});
|
|
|
|
it("should handle booking without user details", async () => {
|
|
const bookingWithoutUserDetails = {
|
|
...mockBooking,
|
|
user: null,
|
|
};
|
|
|
|
mockPaymentService.chargeCard.mockResolvedValue({ success: true, paymentId: "pay_123" });
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
|
|
const result = await handleNoShowFee({
|
|
booking: bookingWithoutUserDetails,
|
|
payment: mockPayment,
|
|
});
|
|
|
|
expect(result).toEqual({ success: true, paymentId: "pay_123" });
|
|
});
|
|
|
|
it("should handle attendees without locale", async () => {
|
|
const bookingWithAttendeesWithoutLocale = {
|
|
...mockBooking,
|
|
attendees: [
|
|
{
|
|
name: "Jane Attendee",
|
|
email: "[email protected]",
|
|
timeZone: "UTC",
|
|
locale: null,
|
|
},
|
|
],
|
|
};
|
|
|
|
mockPaymentService.chargeCard.mockResolvedValue({ success: true, paymentId: "pay_123" });
|
|
|
|
vi.mocked(CredentialRepository.findPaymentCredentialByAppIdAndUserIdOrTeamId).mockResolvedValue(
|
|
mockCredential
|
|
);
|
|
|
|
const result = await handleNoShowFee({
|
|
booking: bookingWithAttendeesWithoutLocale,
|
|
payment: mockPayment,
|
|
});
|
|
|
|
expect(result).toEqual({ success: true, paymentId: "pay_123" });
|
|
expect(getTranslation).toHaveBeenCalledWith("en", "common");
|
|
});
|
|
});
|
|
});
|