Skip to content

Commit

Permalink
Fix matrix test
Browse files Browse the repository at this point in the history
  • Loading branch information
richardhjtan committed Nov 18, 2024
1 parent bebbd71 commit 1d3e105
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 24 deletions.
33 changes: 24 additions & 9 deletions packages/host/app/components/operator-mode/container.gts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { registerDestructor } from '@ember/destroyable';
import { action } from '@ember/object';
import type Owner from '@ember/owner';
import { service } from '@ember/service';
import { trackedFunction } from 'ember-resources/util/function';
import { buildWaiter } from '@ember/test-waiters';
import { isTesting } from '@embroider/macros';
import Component from '@glimmer/component';
Expand All @@ -11,7 +12,7 @@ import perform from 'ember-concurrency/helpers/perform';

import { Modal } from '@cardstack/boxel-ui/components';

import { not } from '@cardstack/boxel-ui/helpers';
import { or, not } from '@cardstack/boxel-ui/helpers';

import type { Loader, Query } from '@cardstack/runtime-common';

Expand Down Expand Up @@ -121,12 +122,24 @@ export default class OperatorModeContainer extends Component<Signature> {
return this.operatorModeStateService.state?.submode === Submodes.Code;
}

private fetchUserInfo = trackedFunction(this, async () => {
if (!this.matrixService.isLoggedIn) {
return;
}
return await this.realmServer.fetchUser();
});

private get isUserInfoLoadings() {
return this.fetchUserInfo.isLoading;
}

private get isUserSubscribed() {
if (!this.realmServer.user) {
if (this.isUserInfoLoading) {
return false;
}
return (
!!this.realmServer.user.stripeCustomerId && !!this.realmServer.user.plan
!!this.fetchUserInfo.value?.stripeCustomerId &&
!!this.fetchUserInfo.value?.plan
);
}

Expand All @@ -144,16 +157,18 @@ export default class OperatorModeContainer extends Component<Signature> {
@boxelModalOverlayColor='var(--operator-mode-bg-color)'
>
<CardCatalogModal />
{{#if (not this.matrixService.isLoggedIn)}}
{{#if
(or
(not this.matrixService.isLoggedIn)
this.matrixService.isInitializingNewUser
this.isUserInfoLoading
)
}}
<Auth />
{{else if (not this.isUserSubscribed)}}
<PaymentSetup
@matrixUserId={{this.matrixUserId}}
@flow={{if
this.matrixService.isInitializingNewUser
'register'
'logged-in'
}}
@flow={{if this.matrixService.isNewUser 'register' 'logged-in'}}
/>
{{else if this.isCodeMode}}
<CodeSubmode
Expand Down
1 change: 0 additions & 1 deletion packages/host/app/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export default class Index extends Route<void> {
if (!this.didMatrixServiceStart) {
await this.matrixService.ready;
await this.matrixService.start();
await this.realmServer.fetchUser();
this.didMatrixServiceStart = true;
}

Expand Down
7 changes: 7 additions & 0 deletions packages/host/app/services/matrix-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export default class MatrixService extends Service {
@service private declare reset: ResetService;
@tracked private _client: ExtendedClient | undefined;
@tracked private _isInitializingNewUser = false;
@tracked private _isNewUser = false;
@tracked private postLoginCompleted = false;

profile = getMatrixProfile(this, () => this.client.getUserId());
Expand Down Expand Up @@ -257,6 +258,10 @@ export default class MatrixService extends Service {
return this._isInitializingNewUser;
}

get isNewUser() {
return this._isNewUser;
}

async initializeNewUser(auth: LoginResponse, displayName: string) {
displayName = displayName.trim();
this._isInitializingNewUser = true;
Expand All @@ -271,6 +276,8 @@ export default class MatrixService extends Service {
}),
this.realmServer.fetchCatalogRealms(),
]);
this._isNewUser = true;
this._isInitializingNewUser = false;
}

public async createPersonalRealmForUser({
Expand Down
13 changes: 2 additions & 11 deletions packages/host/app/services/realm-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,27 +223,18 @@ export default class RealmServerService extends Service {
};
}

async fetchUser() {
if (this.auth.type !== 'logged-in') {
this._user = undefined;
return;
}
async fetchUser(): Promise<User> {
const json = await this.authenticatedUserRequest();
let plan =
json.included?.find((i: { type: string }) => i.type === 'plan')
?.attributes?.name ?? null;
this._user = {
return {
matrixUserId: json.data.attributes.matrixUserId,
stripeCustomerId: json.data.attributes.stripeCustomerId,
plan: plan,
};
}

@cached
get user() {
return this._user;
}

async fetchCatalogRealms() {
if (this.catalogRealmURLs.length > 0) {
return;
Expand Down
24 changes: 21 additions & 3 deletions packages/matrix/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,19 @@ export async function assertPaymentSetup(page: Page, username: string) {
);
}

export async function setupUser(
username: string,
realmServer: IsolatedRealmServer,
) {
let findUser = await realmServer.executeSQL(`SELECT * FROM users`);

await realmServer.executeSQL(
`INSERT INTO users (matrix_user_id) VALUES ('${username}')`,
);

findUser = await realmServer.executeSQL(`SELECT * FROM users`);
}

export async function setupPayment(
page: Page,
username: string,
Expand All @@ -596,9 +609,14 @@ export async function setupPayment(
let freePlan = await realmServer.executeSQL(
`SELECT * FROM plans WHERE name = 'Free'`,
);
let subscriptionId = `sub_1234567890`;

const randomNumber = Math.random().toString(36).substring(2, 12);

let subscriptionId = `sub_${randomNumber}`;
let stripeCustomerId = `cus_${randomNumber}`;

await realmServer.executeSQL(
`UPDATE users SET stripe_customer_id = 'cus_1234567890' WHERE matrix_user_id = '${decodedUsername}'`,
`UPDATE users SET stripe_customer_id = '${stripeCustomerId}' WHERE matrix_user_id = '${decodedUsername}'`,
);

let findUser = await realmServer.executeSQL(
Expand Down Expand Up @@ -662,7 +680,7 @@ export async function setupPayment(
// assert return url contains ?from-free-plan-payment-link=true
const currentUrl = new URL(page.url());
const currentParams = currentUrl.searchParams;
currentParams.append('from-free-plan-payment-link', 'true');
await currentParams.append('from-free-plan-payment-link', 'true');
const returnUrl = `${currentUrl.origin}${
currentUrl.pathname
}?${currentParams.toString()}`;
Expand Down
14 changes: 14 additions & 0 deletions packages/matrix/tests/registration-with-token.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
registerRealmUsers,
enterWorkspace,
showAllCards,
setupUser,
} from '../helpers';
import { registerUser, createRegistrationToken } from '../docker/synapse';

Expand Down Expand Up @@ -188,11 +189,24 @@ test.describe('User Registration w/ Token - isolated realm server', () => {
await logout(page);
await assertLoggedOut(page);

await setupUser('@user2:localhost', realmServer);

// assert workspaces state don't leak into other sessions
await login(page, 'user2', 'pass', {
url: serverIndexUrl,
skipOpeningAssistant: true,
});

await expect(
page.locator('[data-test-setup-payment-message]'),
).toContainText('Setup your payment method now to enjoy Boxel');

const user2MatrixUserId =
Buffer.from('@user2:localhost').toString('base64');

await assertPaymentSetup(page, user2MatrixUserId);
await setupPayment(page, user2MatrixUserId, realmServer);

await assertLoggedIn(page, {
userId: '@user2:localhost',
displayName: 'user2',
Expand Down

0 comments on commit 1d3e105

Please sign in to comment.