Skip to content

Commit 9be4e72

Browse files
feat: sync fixes, framework integration (getBank) (#85)
* feat: take initial value from export, when frameworkIntegration is enabled * feat: accounts configure options, syncInitialBankBalance * fix(sync/optimisations): sync newAccountBalance * fix: renam NewAccountBalance broadcast * feat: changedDefaultAccount event, updated export to getBank
1 parent 86be57e commit 9be4e72

23 files changed

Lines changed: 387 additions & 252 deletions

config.json

Lines changed: 214 additions & 223 deletions
Large diffs are not rendered by default.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"build": "yarn nx run-many --target=build --all",
1818
"lint": "yarn nx run-many --target=lint --all",
1919
"dev": "yarn nx run-many --target=dev --all",
20+
"tsc": "yarn nx run-many --target=tsc --all",
2021
"dev:ingame": "yarn nx run-many --target=dev:ingame --all",
2122
"dev:mobile": "yarn nx run-many --target=dev:mobile --all",
2223
"pre-release": "yarn build && sh ./scripts/prerelease.sh",

src/client/cl_events.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,14 @@ const SendBankUIMessage = (data: object) => {
5252
}
5353
};
5454

55+
onNet(Broadcasts.NewAccount, (payload: Account) => {
56+
SendBankUIMessage({ type: Broadcasts.NewAccount, payload });
57+
});
58+
59+
onNet(Broadcasts.NewAccountBalance, (balance: number) => {
60+
SendBankUIMessage({ type: Broadcasts.NewAccountBalance, payload: balance });
61+
});
62+
5563
onNet(Broadcasts.NewTransaction, (payload: Transaction) => {
5664
SendBankUIMessage({ type: Broadcasts.NewTransaction, payload });
5765
});

src/server/server.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ import { mockedResourceName } from './globals.server';
2828
import { config } from './utils/server-config';
2929
import { UserService } from './services/user/user.service';
3030
import { container } from 'tsyringe';
31-
// import { InvoiceController } from './services/invoice/invoice.controller';
3231

3332
const hotReloadConfig = {
3433
resourceName: GetCurrentResourceName(),
@@ -125,6 +124,20 @@ if (isMocking) {
125124
}
126125

127126
const debug = async () => {
127+
// RegisterCommand(
128+
// 'giveBankBalance',
129+
// (src: number) => {
130+
// const accountService = container.resolve(AccountService);
131+
// const amount = Math.ceil(Math.random() * 1000);
132+
// console.log('---------------');
133+
// console.log('---------------');
134+
// console.log({ amount });
135+
// console.log('---------------');
136+
// console.log('---------------');
137+
// accountService.setMoney({ data: { amount }, source: src });
138+
// },
139+
// false,
140+
// );
128141
//
129142
//
130143
//

src/server/services/account/account.model.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ AccountModel.init(
4646
},
4747
balance: {
4848
type: DataTypes.INTEGER,
49-
defaultValue: config?.accounts?.startAmount ?? 0,
49+
defaultValue: config?.accounts?.otherAccountStartBalance ?? 0,
5050
},
5151
type: {
5252
type: DataTypes.STRING,

src/server/services/account/account.service.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,12 @@ import {
3636
} from '@typings/Errors';
3737
import { SharedAccountDB } from '@services/accountShared/sharedAccount.db';
3838
import { AccountEvents, Broadcasts } from '@server/../../typings/Events';
39+
import { getFrameworkExports } from '@server/utils/frameworkIntegration';
3940

4041
const logger = mainLogger.child({ module: 'accounts' });
42+
const { enabled = false, syncInitialBankBalance = false } = config.frameworkIntegration ?? {};
43+
const { firstAccountStartBalance } = config.accounts ?? {};
44+
const isFrameworkIntegrationEnabled = enabled;
4145

4246
@singleton()
4347
export class AccountService {
@@ -212,12 +216,24 @@ export class AccountService {
212216
return defaultAccount.toJSON();
213217
}
214218

215-
logger.debug('Creating initial account ...');
219+
let balance = firstAccountStartBalance;
220+
if (isFrameworkIntegrationEnabled && syncInitialBankBalance) {
221+
logger.info('Syncing initial bank balance from framework.');
222+
223+
const exports = getFrameworkExports();
224+
balance = exports.getBank(source);
225+
226+
logger.info('Moving bank balance from export to initial account.');
227+
logger.info({ identifier, balance });
228+
}
229+
230+
logger.debug('Creating initial account .. ');
216231
const initialAccount = await this._accountDB.createAccount({
217232
isDefault: true,
218233
accountName: i18next.t('Personal account'),
219234
ownerIdentifier: user.getIdentifier(),
220235
type: AccountType.Personal,
236+
balance,
221237
});
222238

223239
logger.debug('Successfully created initial account.');
@@ -518,8 +534,12 @@ export class AccountService {
518534
throw new Error('This is already the default account');
519535
}
520536

521-
await defaultAccount?.update({ isDefault: false });
522-
await newDefaultAccount.update({ isDefault: true });
537+
await defaultAccount?.update({ isDefault: false }, { transaction: t });
538+
await newDefaultAccount.update({ isDefault: true }, { transaction: t });
539+
540+
t.afterCommit(() => {
541+
emit(AccountEvents.UpdatedDefaultAccount, newDefaultAccount.toJSON());
542+
});
523543

524544
t.commit();
525545
return newDefaultAccount;

src/server/services/broadcast/broadcast.controller.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ export class BroadcastController {
1919
this.broadcastService.broadcastNewDefaultAccountBalance(account);
2020
}
2121

22+
@Event(AccountEvents.NewBalance)
23+
async onNewAccountBalance(account: Account) {
24+
this.broadcastService.broadcastNewAccountBalance(account);
25+
}
26+
2227
@Event(AccountEvents.NewAccountCreated)
2328
async onNewAccountCreation(account: Account) {
2429
this.broadcastService.broadcastUpdatedAccount(account);

src/server/services/broadcast/broadcast.service.ts

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,26 @@ import { mainLogger } from '@server/sv_logger';
44
import { UserService } from '../user/user.service';
55
import { Broadcasts } from '@typings/Events';
66
import { TransactionDB } from '../transaction/transaction.db';
7-
import { Account } from '@server/../../typings/Account';
7+
import { Account, AccountType } from '@server/../../typings/Account';
88
import { Cash } from '@server/../../typings/Cash';
9+
import { AccountService } from '../account/account.service';
910

1011
const logger = mainLogger.child({ module: 'broadcastService' });
1112

1213
@singleton()
1314
export class BroadcastService {
1415
_transactionDB: TransactionDB;
1516
_userService: UserService;
17+
_accountService: AccountService;
1618

17-
constructor(transactionDB: TransactionDB, userService: UserService) {
19+
constructor(
20+
transactionDB: TransactionDB,
21+
userService: UserService,
22+
accountService: AccountService,
23+
) {
1824
this._transactionDB = transactionDB;
1925
this._userService = userService;
26+
this._accountService = accountService;
2027
}
2128

2229
async broadcastUpdatedAccount(account: Account) {
@@ -64,6 +71,46 @@ export class BroadcastService {
6471
}
6572
}
6673

74+
async broadcastNewAccountBalance(account: Account) {
75+
logger.silly('Broadcasting new balance for account ..');
76+
77+
const isShared = account.type === AccountType.Shared;
78+
const identifier = account.ownerIdentifier;
79+
const user = this._userService.getUserByIdentifier(identifier);
80+
const onlineUsers = this._userService.getAllUsers();
81+
82+
if (isShared) {
83+
const users = await this._accountService.getUsersFromShared({
84+
data: { accountId: account.id },
85+
source: 0,
86+
});
87+
88+
const identifiers = users.map((user) => user.userIdentifier);
89+
90+
onlineUsers.forEach((user) => {
91+
if (!identifiers.includes(user.getIdentifier())) {
92+
return;
93+
}
94+
95+
emitNet(Broadcasts.NewAccountBalance, user.getSource(), account);
96+
97+
logger.silly('Broadcasted new balance for shared account:');
98+
logger.silly({ identifier, source: user.getSource(), balance: account.balance });
99+
});
100+
return;
101+
}
102+
103+
if (!user) {
104+
/* User is probably offline */
105+
return;
106+
}
107+
108+
emitNet(Broadcasts.NewAccountBalance, user?.getSource(), account);
109+
110+
logger.silly('Broadcasted new balance for personal account:');
111+
logger.silly({ identifier, source: user.getSource(), balance: account.balance });
112+
}
113+
67114
async broadcastNewDefaultAccountBalance(account: Account) {
68115
/* Do not broadcast updated values for none default account */
69116
if (!account.isDefault) {

src/server/utils/frameworkIntegration.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const frameworkIntegrationKeys: FrameworkIntegrationFunction[] = [
1212
'addCash',
1313
'removeCash',
1414
'getCash',
15+
'getBank',
1516
];
1617

1718
export const validateResourceExports = (resourceExports: FrameworkIntegrationExports): boolean => {

typings/Account.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ export interface CreateAccountInput {
4646
type: AccountType;
4747
isDefault?: boolean;
4848
number?: string;
49+
balance?: number;
4950
}
5051

5152
export interface SharedAccount {

0 commit comments

Comments
 (0)