Compare commits

...

18 Commits

Author SHA1 Message Date
Ahmed Bouhuolia
0588a30c88 fix: auth pages errors handler 2025-10-30 19:27:29 +02:00
Ahmed Bouhuolia
4a0091d3f8 Merge pull request #835 from bigcapitalhq/fix-edit-payment-transaction
fix: edit payment transaction
2025-10-29 12:57:24 +02:00
Ahmed Bouhuolia
fc89cfb14a fix: edit payment transaction 2025-10-29 12:54:12 +02:00
Ahmed Bouhuolia
98401b5a01 Merge pull request #438 from bigcapitalhq/BIG-166
feat: one-command setup script
2025-10-29 00:39:45 +02:00
Ahmed Bouhuolia
3afe4f470f Update setup.sh
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-29 00:39:26 +02:00
Ahmed Bouhuolia
b4281a71d4 Apply suggestion from @Copilot
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-29 00:39:15 +02:00
Ahmed Bouhuolia
87c127fabd Merge branch 'develop' into BIG-166 2025-10-29 00:35:33 +02:00
Ahmed Bouhuolia
50d9e8d375 Merge pull request #833 from bigcapitalhq/fix-more-bugs
fix: issues related to PUT operations
2025-10-28 18:14:00 +02:00
Ahmed Bouhuolia
4839a6dea8 Update packages/server/src/modules/Bills/commands/EditBill.service.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-28 18:13:52 +02:00
Ahmed Bouhuolia
f736c3f9eb fix: issues related to PUT operations 2025-10-28 18:12:08 +02:00
Ahmed Bouhuolia
368c85a01a Merge pull request #832 from bigcapitalhq/validate-tenant-existance-in-guards
fix: validate request org id existance in guards
2025-10-25 15:20:42 +02:00
Ahmed Bouhuolia
5d792fea26 fix 2025-10-25 15:19:10 +02:00
Ahmed Bouhuolia
1bccba572a fix: validate request org id existance in guards 2025-10-25 15:15:13 +02:00
Ahmed Bouhuolia
900921e6ba Merge pull request #831 from bigcapitalhq/fix-tenant-build
fix: organization build db connection error
2025-10-25 14:59:28 +02:00
Ahmed Bouhuolia
2b4772a070 fix: organization build db connection error 2025-10-25 14:57:38 +02:00
Ahmed Bouhuolia
8852a4a0f8 Merge pull request #830 from bigcapitalhq/fix-system-tenant-migration
fix: seed migration issue
2025-10-25 14:02:19 +02:00
Ahmed Bouhuolia
8e2cd98689 fix: the menu labels 2024-05-12 18:32:19 +02:00
Ahmed Bouhuolia
f934797929 feat: one-command setup script 2024-05-12 18:07:38 +02:00
54 changed files with 526 additions and 199 deletions

View File

@@ -24,7 +24,7 @@ export class AuthSendResetPasswordService {
@Inject(SystemUser.name) @Inject(SystemUser.name)
private readonly systemUserModel: typeof SystemUser, private readonly systemUserModel: typeof SystemUser,
) {} ) { }
/** /**
* Sends the given email reset password email. * Sends the given email reset password email.
@@ -33,8 +33,9 @@ export class AuthSendResetPasswordService {
async sendResetPassword(email: string): Promise<void> { async sendResetPassword(email: string): Promise<void> {
const user = await this.systemUserModel const user = await this.systemUserModel
.query() .query()
.findOne({ email }) .findOne({ email });
.throwIfNotFound();
if (!user) return;
const token: string = uniqid(); const token: string = uniqid();
@@ -48,10 +49,8 @@ export class AuthSendResetPasswordService {
this.deletePasswordResetToken(email); this.deletePasswordResetToken(email);
// Creates a new password reset row with unique token. // Creates a new password reset row with unique token.
const passwordReset = await this.resetPasswordModel.query().insert({ await this.resetPasswordModel.query().insert({ email, token });
email,
token,
});
// Triggers sent reset password event. // Triggers sent reset password event.
await this.eventPublisher.emitAsync(events.auth.sendResetPassword, { await this.eventPublisher.emitAsync(events.auth.sendResetPassword, {
user, user,

View File

@@ -1,9 +1,11 @@
import { ClsService } from 'nestjs-cls'; import { ClsService } from 'nestjs-cls';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { SystemUser } from '@/modules/System/models/SystemUser'; import { SystemUser } from '@/modules/System/models/SystemUser';
import { ModelObject } from 'objection'; import { ModelObject } from 'objection';
import { JwtPayload } from '../Auth.interfaces'; import { JwtPayload } from '../Auth.interfaces';
import { InvalidEmailPasswordException } from '../exceptions/InvalidEmailPassword.exception';
import { UserNotFoundException } from '../exceptions/UserNotFound.exception';
@Injectable() @Injectable()
export class AuthSigninService { export class AuthSigninService {
@@ -12,7 +14,7 @@ export class AuthSigninService {
private readonly systemUserModel: typeof SystemUser, private readonly systemUserModel: typeof SystemUser,
private readonly jwtService: JwtService, private readonly jwtService: JwtService,
private readonly clsService: ClsService, private readonly clsService: ClsService,
) {} ) { }
/** /**
* Validates the given email and password. * Validates the given email and password.
@@ -32,14 +34,10 @@ export class AuthSigninService {
.findOne({ email }) .findOne({ email })
.throwIfNotFound(); .throwIfNotFound();
} catch (err) { } catch (err) {
throw new UnauthorizedException( throw new InvalidEmailPasswordException(email);
`There isn't any user with email: ${email}`,
);
} }
if (!(await user.checkPassword(password))) { if (!(await user.checkPassword(password))) {
throw new UnauthorizedException( throw new InvalidEmailPasswordException(email);
`Wrong password for user with email: ${email}`,
);
} }
return user; return user;
} }
@@ -61,9 +59,7 @@ export class AuthSigninService {
this.clsService.set('tenantId', user.tenantId); this.clsService.set('tenantId', user.tenantId);
this.clsService.set('userId', user.id); this.clsService.set('userId', user.id);
} catch (error) { } catch (error) {
throw new UnauthorizedException( throw new UserNotFoundException(String(payload.sub));
`There isn't any user with email: ${payload.sub}`,
);
} }
return payload; return payload;
} }

View File

@@ -32,7 +32,7 @@ export class AuthSignupService {
@Inject(SystemUser.name) @Inject(SystemUser.name)
private readonly systemUserModel: typeof SystemUser, private readonly systemUserModel: typeof SystemUser,
) {} ) { }
/** /**
* Registers a new tenant with user from user input. * Registers a new tenant with user from user input.
@@ -121,7 +121,6 @@ export class AuthSignupService {
const isAllowedDomain = signupRestrictions.allowedDomains.some( const isAllowedDomain = signupRestrictions.allowedDomains.some(
(domain) => emailDomain === domain, (domain) => emailDomain === domain,
); );
if (!isAllowedEmail && !isAllowedDomain) { if (!isAllowedEmail && !isAllowedDomain) {
throw new ServiceError( throw new ServiceError(
ERRORS.SIGNUP_RESTRICTED_NOT_ALLOWED, ERRORS.SIGNUP_RESTRICTED_NOT_ALLOWED,

View File

@@ -0,0 +1,15 @@
import { UnauthorizedException } from '@nestjs/common';
import { ERRORS } from '../Auth.constants';
export class InvalidEmailPasswordException extends UnauthorizedException {
constructor(email: string) {
super({
statusCode: 401,
error: 'Unauthorized',
message: `Invalid email or password for ${email}`,
code: ERRORS.INVALID_DETAILS,
});
}
}

View File

@@ -0,0 +1,13 @@
import { UnauthorizedException } from '@nestjs/common';
import { ERRORS } from '../Auth.constants';
export class UserNotFoundException extends UnauthorizedException {
constructor(identifier: string) {
super({
statusCode: 401,
error: 'Unauthorized',
message: `User not found: ${identifier}`,
code: ERRORS.USER_NOT_FOUND,
});
}
}

View File

@@ -28,7 +28,12 @@ export class GetBankRulesTransformer extends Transformer {
* @returns {string} * @returns {string}
*/ */
protected assignCategoryFormatted(bankRule: any) { protected assignCategoryFormatted(bankRule: any) {
return getCashflowTransactionFormattedType(bankRule.assignCategory); const translationKey = getCashflowTransactionFormattedType(
bankRule.assignCategory,
);
return translationKey
? this.context.i18n.t(translationKey)
: bankRule.assignCategory;
} }
/** /**

View File

@@ -19,7 +19,7 @@ export class BillPaymentsPages {
@Inject(BillPayment.name) @Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>, private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
) {} ) { }
/** /**
* Retrieve bill payment with associated metadata. * Retrieve bill payment with associated metadata.
@@ -46,7 +46,8 @@ export class BillPaymentsPages {
paymentAmount: entry.paymentAmount, paymentAmount: entry.paymentAmount,
})); }));
const resPayableBills = await Bill.query() const resPayableBills = await this.billModel()
.query()
.modify('opened') .modify('opened')
.modify('dueBills') .modify('dueBills')
.where('vendor_id', billPayment.vendorId) .where('vendor_id', billPayment.vendorId)

View File

@@ -28,8 +28,8 @@ export class EditBillService {
private transformerDTO: BillDTOTransformer, private transformerDTO: BillDTOTransformer,
@Inject(Bill.name) private billModel: TenantModelProxy<typeof Bill>, @Inject(Bill.name) private billModel: TenantModelProxy<typeof Bill>,
@Inject(Vendor.name) private contactModel: TenantModelProxy<typeof Vendor>, @Inject(Vendor.name) private vendorModel: TenantModelProxy<typeof Vendor>,
) {} ) { }
/** /**
* Edits details of the given bill id with associated entries. * Edits details of the given bill id with associated entries.
@@ -58,10 +58,9 @@ export class EditBillService {
this.validators.validateBillExistance(oldBill); this.validators.validateBillExistance(oldBill);
// Retrieve vendor details or throw not found service error. // Retrieve vendor details or throw not found service error.
const vendor = await this.contactModel() const vendor = await this.vendorModel()
.query() .query()
.findById(billDTO.vendorId) .findById(billDTO.vendorId)
.modify('vendor')
.throwIfNotFound(); .throwIfNotFound();
// Validate bill number uniqiness on the storage. // Validate bill number uniqiness on the storage.

View File

@@ -1,6 +1,7 @@
import { ToNumber } from '@/common/decorators/Validators'; import { ToNumber } from '@/common/decorators/Validators';
import { ItemEntryDto } from '@/modules/TransactionItemEntry/dto/ItemEntry.dto'; import { ItemEntryDto } from '@/modules/TransactionItemEntry/dto/ItemEntry.dto';
import { Type } from 'class-transformer'; import { Type, Transform } from 'class-transformer';
import { parseBoolean } from '@/utils/parse-boolean';
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { import {
ArrayMinSize, ArrayMinSize,
@@ -31,6 +32,7 @@ export class BillEntryDto extends ItemEntryDto {
}) })
@IsOptional() @IsOptional()
@IsBoolean() @IsBoolean()
@Transform(({ value }) => parseBoolean(value, false))
landedCost?: boolean; landedCost?: boolean;
} }
@@ -211,5 +213,5 @@ export class CommandBillDto {
adjustment?: number; adjustment?: number;
} }
export class CreateBillDto extends CommandBillDto {} export class CreateBillDto extends CommandBillDto { }
export class EditBillDto extends CommandBillDto {} export class EditBillDto extends CommandBillDto { }

View File

@@ -10,6 +10,7 @@ import { BranchTransactionDTOTransformer } from '@/modules/Branches/integrations
import { WarehouseTransactionDTOTransform } from '@/modules/Warehouses/Integrations/WarehouseTransactionDTOTransform'; import { WarehouseTransactionDTOTransform } from '@/modules/Warehouses/Integrations/WarehouseTransactionDTOTransform';
import { BrandingTemplateDTOTransformer } from '../../PdfTemplate/BrandingTemplateDTOTransformer'; import { BrandingTemplateDTOTransformer } from '../../PdfTemplate/BrandingTemplateDTOTransformer';
import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index'; import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index';
import { formatDateFields } from '@/utils/format-date-fields';
import { CreditNoteAutoIncrementService } from './CreditNoteAutoIncrement.service'; import { CreditNoteAutoIncrementService } from './CreditNoteAutoIncrement.service';
import { CreditNote } from '../models/CreditNote'; import { CreditNote } from '../models/CreditNote';
import { import {
@@ -33,7 +34,7 @@ export class CommandCreditNoteDTOTransform {
private readonly warehouseDTOTransform: WarehouseTransactionDTOTransform, private readonly warehouseDTOTransform: WarehouseTransactionDTOTransform,
private readonly brandingTemplatesTransformer: BrandingTemplateDTOTransformer, private readonly brandingTemplatesTransformer: BrandingTemplateDTOTransformer,
private readonly creditNoteAutoIncrement: CreditNoteAutoIncrementService, private readonly creditNoteAutoIncrement: CreditNoteAutoIncrementService,
) {} ) { }
/** /**
* Transforms the credit/edit DTO to model. * Transforms the credit/edit DTO to model.
@@ -70,7 +71,10 @@ export class CommandCreditNoteDTOTransform {
autoNextNumber; autoNextNumber;
const initialDTO = { const initialDTO = {
...omit(creditNoteDTO, ['open', 'attachments']), ...formatDateFields(
omit(creditNoteDTO, ['open', 'attachments']),
['creditNoteDate'],
),
creditNoteNumber, creditNoteNumber,
amount, amount,
currencyCode: customerCurrencyCode, currencyCode: customerCurrencyCode,
@@ -78,8 +82,8 @@ export class CommandCreditNoteDTOTransform {
entries, entries,
...(creditNoteDTO.open && ...(creditNoteDTO.open &&
!oldCreditNote?.openedAt && { !oldCreditNote?.openedAt && {
openedAt: moment().toMySqlDateTime(), openedAt: moment().toMySqlDateTime(),
}), }),
refundedAmount: 0, refundedAmount: 0,
invoicesAmount: 0, invoicesAmount: 0,
}; };

View File

@@ -185,5 +185,5 @@ export class CommandExpenseDto {
attachments?: AttachmentDto[]; attachments?: AttachmentDto[];
} }
export class CreateExpenseDto extends CommandExpenseDto {} export class CreateExpenseDto extends CommandExpenseDto { }
export class EditExpenseDto extends CommandExpenseDto {} export class EditExpenseDto extends CommandExpenseDto { }

View File

@@ -26,6 +26,7 @@ import { GetCurrentOrganizationService } from './queries/GetCurrentOrganization.
import { UpdateOrganizationService } from './commands/UpdateOrganization.service'; import { UpdateOrganizationService } from './commands/UpdateOrganization.service';
import { IgnoreTenantInitializedRoute } from '../Tenancy/EnsureTenantIsInitialized.guard'; import { IgnoreTenantInitializedRoute } from '../Tenancy/EnsureTenantIsInitialized.guard';
import { IgnoreTenantSeededRoute } from '../Tenancy/EnsureTenantIsSeeded.guards'; import { IgnoreTenantSeededRoute } from '../Tenancy/EnsureTenantIsSeeded.guards';
import { IgnoreTenantModelsInitialize } from '../Tenancy/TenancyInitializeModels.guard';
import { GetBuildOrganizationBuildJob } from './commands/GetBuildOrganizationJob.service'; import { GetBuildOrganizationBuildJob } from './commands/GetBuildOrganizationJob.service';
import { OrganizationBaseCurrencyLocking } from './Organization/OrganizationBaseCurrencyLocking.service'; import { OrganizationBaseCurrencyLocking } from './Organization/OrganizationBaseCurrencyLocking.service';
import { import {
@@ -39,6 +40,7 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
@Controller('organization') @Controller('organization')
@IgnoreTenantInitializedRoute() @IgnoreTenantInitializedRoute()
@IgnoreTenantSeededRoute() @IgnoreTenantSeededRoute()
@IgnoreTenantModelsInitialize()
@ApiExtraModels(GetCurrentOrganizationResponseDto) @ApiExtraModels(GetCurrentOrganizationResponseDto)
@ApiCommonHeaders() @ApiCommonHeaders()
export class OrganizationController { export class OrganizationController {
@@ -48,7 +50,7 @@ export class OrganizationController {
private readonly updateOrganizationService: UpdateOrganizationService, private readonly updateOrganizationService: UpdateOrganizationService,
private readonly getBuildOrganizationJobService: GetBuildOrganizationBuildJob, private readonly getBuildOrganizationJobService: GetBuildOrganizationBuildJob,
private readonly orgBaseCurrencyLockingService: OrganizationBaseCurrencyLocking, private readonly orgBaseCurrencyLockingService: OrganizationBaseCurrencyLocking,
) {} ) { }
@Post('build') @Post('build')
@HttpCode(200) @HttpCode(200)

View File

@@ -18,7 +18,7 @@ export class PaymentsReceivedPagesService {
@Inject(PaymentReceived.name) @Inject(PaymentReceived.name)
private readonly paymentReceived: TenantModelProxy<typeof PaymentReceived>, private readonly paymentReceived: TenantModelProxy<typeof PaymentReceived>,
) {} ) { }
/** /**
* Retrive page invoices entries from the given sale invoices models. * Retrive page invoices entries from the given sale invoices models.
@@ -58,11 +58,10 @@ export class PaymentsReceivedPagesService {
/** /**
* Retrieve the payment receive details of the given id. * Retrieve the payment receive details of the given id.
* @param {number} tenantId - Tenant id. * @param {number} paymentReceiveId - Payment receive id.
* @param {Integer} paymentReceiveId - Payment receive id.
*/ */
public async getPaymentReceiveEditPage(paymentReceiveId: number): Promise<{ public async getPaymentReceiveEditPage(paymentReceiveId: number): Promise<{
paymentReceive: Omit<PaymentReceived, 'entries'>; data: Omit<PaymentReceived, 'entries'>;
entries: IPaymentReceivePageEntry[]; entries: IPaymentReceivePageEntry[];
}> { }> {
// Retrieve payment receive. // Retrieve payment receive.
@@ -100,7 +99,7 @@ export class PaymentsReceivedPagesService {
const entries = [...paymentEntries, ...restReceivableEntries]; const entries = [...paymentEntries, ...restReceivableEntries];
return { return {
paymentReceive: omit(paymentReceive, ['entries']), data: omit(paymentReceive, ['entries']),
entries, entries,
}; };
} }

View File

@@ -17,12 +17,11 @@ import { TenantUser } from '../Tenancy/TenancyModels/models/TenantUser.model';
@Injectable() @Injectable()
export class AuthorizationGuard implements CanActivate { export class AuthorizationGuard implements CanActivate {
constructor( constructor(
private reflector: Reflector,
private readonly clsService: ClsService, private readonly clsService: ClsService,
@Inject(TenantUser.name) @Inject(TenantUser.name)
private readonly tenantUserModel: TenantModelProxy<typeof TenantUser>, private readonly tenantUserModel: TenantModelProxy<typeof TenantUser>,
) {} ) { }
/** /**
* Checks if the user has the required abilities to access the route * Checks if the user has the required abilities to access the route
@@ -31,7 +30,7 @@ export class AuthorizationGuard implements CanActivate {
*/ */
async canActivate(context: ExecutionContext): Promise<boolean> { async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>(); const request = context.switchToHttp().getRequest<Request>();
const { tenantId, user } = request as any; const { user } = request as any;
if (ABILITIES_CACHE.has(user.id)) { if (ABILITIES_CACHE.has(user.id)) {
(request as any).ability = ABILITIES_CACHE.get(user.id); (request as any).ability = ABILITIES_CACHE.get(user.id);
@@ -40,7 +39,6 @@ export class AuthorizationGuard implements CanActivate {
(request as any).ability = ability; (request as any).ability = ability;
ABILITIES_CACHE.set(user.id, ability); ABILITIES_CACHE.set(user.id, ability);
} }
return true; return true;
} }

View File

@@ -21,7 +21,7 @@ enum DiscountType {
Amount = 'amount', Amount = 'amount',
} }
class SaleEstimateEntryDto extends ItemEntryDto {} class SaleEstimateEntryDto extends ItemEntryDto { }
class AttachmentDto { class AttachmentDto {
@IsString() @IsString()
@@ -140,6 +140,7 @@ export class CommandSaleEstimateDto {
}, },
], ],
}) })
attachments?: AttachmentDto[];
@IsOptional() @IsOptional()
@ToNumber() @ToNumber()
@@ -177,5 +178,5 @@ export class CommandSaleEstimateDto {
adjustment?: number; adjustment?: number;
} }
export class CreateSaleEstimateDto extends CommandSaleEstimateDto {} export class CreateSaleEstimateDto extends CommandSaleEstimateDto { }
export class EditSaleEstimateDto extends CommandSaleEstimateDto {} export class EditSaleEstimateDto extends CommandSaleEstimateDto { }

View File

@@ -24,7 +24,7 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
@ApiExtraModels(TaxRateResponseDto) @ApiExtraModels(TaxRateResponseDto)
@ApiCommonHeaders() @ApiCommonHeaders()
export class TaxRatesController { export class TaxRatesController {
constructor(private readonly taxRatesApplication: TaxRatesApplication) {} constructor(private readonly taxRatesApplication: TaxRatesApplication) { }
@Post() @Post()
@ApiOperation({ summary: 'Create a new tax rate.' }) @ApiOperation({ summary: 'Create a new tax rate.' })

View File

@@ -18,7 +18,7 @@ export class EnsureTenantIsInitializedGuard implements CanActivate {
constructor( constructor(
private readonly tenancyContext: TenancyContext, private readonly tenancyContext: TenancyContext,
private reflector: Reflector, private reflector: Reflector,
) {} ) { }
/** /**
* Validate the tenant of the current request is initialized.. * Validate the tenant of the current request is initialized..
@@ -41,6 +41,12 @@ export class EnsureTenantIsInitializedGuard implements CanActivate {
} }
const tenant = await this.tenancyContext.getTenant(); const tenant = await this.tenancyContext.getTenant();
if (!tenant) {
throw new UnauthorizedException({
message: 'Tenant not found.',
errors: [{ type: 'TENANT.NOT.FOUND' }],
});
}
if (!tenant?.initializedAt) { if (!tenant?.initializedAt) {
throw new UnauthorizedException({ throw new UnauthorizedException({
statusCode: 400, statusCode: 400,

View File

@@ -19,7 +19,7 @@ export class EnsureTenantIsSeededGuard implements CanActivate {
constructor( constructor(
private readonly tenancyContext: TenancyContext, private readonly tenancyContext: TenancyContext,
private reflector: Reflector, private reflector: Reflector,
) {} ) { }
/** /**
* Validate the tenant of the current request is seeded. * Validate the tenant of the current request is seeded.
@@ -41,6 +41,12 @@ export class EnsureTenantIsSeededGuard implements CanActivate {
} }
const tenant = await this.tenancyContext.getTenant(); const tenant = await this.tenancyContext.getTenant();
if (!tenant) {
throw new UnauthorizedException({
message: 'Tenant not found.',
errors: [{ type: 'TENANT.NOT.FOUND' }],
});
}
if (!tenant.seededAt) { if (!tenant.seededAt) {
throw new UnauthorizedException({ throw new UnauthorizedException({
message: 'Tenant database is not seeded with initial data yet.', message: 'Tenant database is not seeded with initial data yet.',

View File

@@ -2,6 +2,7 @@ import { Inject, Injectable } from '@nestjs/common';
import { ClsService } from 'nestjs-cls'; import { ClsService } from 'nestjs-cls';
import { SystemUser } from '../System/models/SystemUser'; import { SystemUser } from '../System/models/SystemUser';
import { TenantModel } from '../System/models/TenantModel'; import { TenantModel } from '../System/models/TenantModel';
import { ServiceError } from '../Items/ServiceError';
@Injectable() @Injectable()
export class TenancyContext { export class TenancyContext {
@@ -13,7 +14,7 @@ export class TenancyContext {
@Inject(TenantModel.name) @Inject(TenantModel.name)
private readonly systemTenantModel: typeof TenantModel, private readonly systemTenantModel: typeof TenantModel,
) {} ) { }
/** /**
* Get the current tenant. * Get the current tenant.

View File

@@ -23,7 +23,7 @@ export class TenantDBManager {
@Inject(SystemKnexConnection) @Inject(SystemKnexConnection)
private readonly systemKnex: Knex, private readonly systemKnex: Knex,
) {} ) { }
/** /**
* Retrieves the tenant database name. * Retrieves the tenant database name.
@@ -45,8 +45,8 @@ export class TenantDBManager {
const results = await this.systemKnex.raw( const results = await this.systemKnex.raw(
'SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "' + 'SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "' +
databaseName + databaseName +
'"', '"',
); );
return results[0].length > 0; return results[0].length > 0;
} }
@@ -73,12 +73,12 @@ export class TenantDBManager {
*/ */
public async dropDatabaseIfExists() { public async dropDatabaseIfExists() {
const tenant = await this.tenancyContext.getTenant(); const tenant = await this.tenancyContext.getTenant();
const isExists = await this.databaseExists(tenant); const isExists = await this.databaseExists();
if (!isExists) { if (!isExists) {
return; return;
} }
await this.dropDatabase(tenant); await this.dropDatabase();
} }
/** /**
@@ -115,7 +115,7 @@ export class TenantDBManager {
* @return {Promise<void>} * @return {Promise<void>}
*/ */
async throwErrorIfTenantDBExists(tenant: TenantModel) { async throwErrorIfTenantDBExists(tenant: TenantModel) {
const isExists = await this.databaseExists(tenant); const isExists = await this.databaseExists();
if (isExists) { if (isExists) {
throw new TenantDBAlreadyExists(); throw new TenantDBAlreadyExists();
} }

View File

@@ -8,6 +8,7 @@ import { BranchTransactionDTOTransformer } from '@/modules/Branches/integrations
import { WarehouseTransactionDTOTransform } from '@/modules/Warehouses/Integrations/WarehouseTransactionDTOTransform'; import { WarehouseTransactionDTOTransform } from '@/modules/Warehouses/Integrations/WarehouseTransactionDTOTransform';
import { VendorCredit } from '../models/VendorCredit'; import { VendorCredit } from '../models/VendorCredit';
import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index'; import { assocItemEntriesDefaultIndex } from '@/utils/associate-item-entries-index';
import { formatDateFields } from '@/utils/format-date-fields';
import { VendorCreditAutoIncrementService } from './VendorCreditAutoIncrement.service'; import { VendorCreditAutoIncrementService } from './VendorCreditAutoIncrement.service';
import { ServiceError } from '@/modules/Items/ServiceError'; import { ServiceError } from '@/modules/Items/ServiceError';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
@@ -30,7 +31,7 @@ export class VendorCreditDTOTransformService {
private branchDTOTransform: BranchTransactionDTOTransformer, private branchDTOTransform: BranchTransactionDTOTransformer,
private warehouseDTOTransform: WarehouseTransactionDTOTransform, private warehouseDTOTransform: WarehouseTransactionDTOTransform,
private vendorCreditAutoIncrement: VendorCreditAutoIncrementService, private vendorCreditAutoIncrement: VendorCreditAutoIncrementService,
) {} ) { }
/** /**
* Transforms the credit/edit vendor credit DTO to model. * Transforms the credit/edit vendor credit DTO to model.
@@ -70,7 +71,10 @@ export class VendorCreditDTOTransformService {
autoNextNumber; autoNextNumber;
const initialDTO = { const initialDTO = {
...omit(vendorCreditDTO, ['open', 'attachments']), ...formatDateFields(
omit(vendorCreditDTO, ['open', 'attachments']),
['vendorCreditDate'],
),
amount, amount,
currencyCode: vendorCurrencyCode, currencyCode: vendorCurrencyCode,
exchangeRate: vendorCreditDTO.exchangeRate || 1, exchangeRate: vendorCreditDTO.exchangeRate || 1,
@@ -78,8 +82,8 @@ export class VendorCreditDTOTransformService {
entries, entries,
...(vendorCreditDTO.open && ...(vendorCreditDTO.open &&
!oldVendorCredit?.openedAt && { !oldVendorCredit?.openedAt && {
openedAt: moment().toMySqlDateTime(), openedAt: moment().toMySqlDateTime(),
}), }),
}; };
return composeAsync( return composeAsync(
this.branchDTOTransform.transformDTO<VendorCredit>, this.branchDTOTransform.transformDTO<VendorCredit>,

View File

@@ -102,13 +102,13 @@ export const StatusAccessor = (row) => {
return ( return (
<Choose> <Choose>
<Choose.When condition={!!row.is_published}> <Choose.When condition={!!row.is_published}>
<Tag minimal={true} round={true}> <Tag round>
<T id={'published'} /> <T id={'published'} />
</Tag> </Tag>
</Choose.When> </Choose.When>
<Choose.Otherwise> <Choose.Otherwise>
<Tag minimal={true} intent={Intent.WARNING} round={true}> <Tag intent={Intent.WARNING} round>
<T id={'draft'} /> <T id={'draft'} />
</Tag> </Tag>
</Choose.Otherwise> </Choose.Otherwise>

View File

@@ -42,7 +42,7 @@ export const handleDeleteErrors = (errors) => {
export const AccountCodeAccessor = (row) => export const AccountCodeAccessor = (row) =>
!isBlank(row.code) ? ( !isBlank(row.code) ? (
<Tag minimal={true} round={true} intent={Intent.NONE}> <Tag minimal round intent={Intent.NONE}>
{row.code} {row.code}
</Tag> </Tag>
) : null; ) : null;

View File

@@ -32,13 +32,11 @@ export default function Login() {
email: values.crediential, email: values.crediential,
password: values.password, password: values.password,
}).catch(({ response }) => { }).catch(({ response }) => {
const { const { data: error } = response;
data: { errors }, const toastMessages = transformLoginErrorsToToasts(error);
} = response;
const toastBuilders = transformLoginErrorsToToasts(errors);
toastBuilders.forEach((builder) => { toastMessages.forEach((toastMessage) => {
Toaster.show(builder); Toaster.show(toastMessage);
}); });
setSubmitting(false); setSubmitting(false);
}); });

View File

@@ -35,7 +35,7 @@ export default function SendResetPassword() {
// Handle form submitting. // Handle form submitting.
const handleSubmit = (values, { setSubmitting }) => { const handleSubmit = (values, { setSubmitting }) => {
sendResetPasswordMutate({ email: values.crediential }) sendResetPasswordMutate({ email: values.crediential })
.then((response) => { .then(() => {
AppToaster.show({ AppToaster.show({
message: intl.get('check_your_email_for_a_link_to_reset'), message: intl.get('check_your_email_for_a_link_to_reset'),
intent: Intent.SUCCESS, intent: Intent.SUCCESS,
@@ -43,20 +43,9 @@ export default function SendResetPassword() {
history.push('/auth/login'); history.push('/auth/login');
setSubmitting(false); setSubmitting(false);
}) })
.catch( .catch(() => {
({ setSubmitting(false);
response: { });
data: { errors },
},
}) => {
const toastBuilders = transformSendResetPassErrorsToToasts(errors);
toastBuilders.forEach((builder) => {
AppToaster.show(builder);
});
setSubmitting(false);
},
);
}; };
return ( return (
@@ -82,11 +71,17 @@ function SendResetPasswordFooterLinks() {
<AuthFooterLinks> <AuthFooterLinks>
{!signupDisabled && ( {!signupDisabled && (
<AuthFooterLink> <AuthFooterLink>
<T id={'dont_have_an_account'} /> <Link to={'/auth/register'}><T id={'sign_up'} /></Link> <T id={'dont_have_an_account'} />{' '}
<Link to={'/auth/register'}>
<T id={'sign_up'} />
</Link>
</AuthFooterLink> </AuthFooterLink>
)} )}
<AuthFooterLink> <AuthFooterLink>
<T id={'return_to'} /> <Link to={'/auth/login'}><T id={'sign_in'} /></Link> <T id={'return_to'} />{' '}
<Link to={'/auth/login'}>
<T id={'sign_in'} />
</Link>
</AuthFooterLink> </AuthFooterLink>
</AuthFooterLinks> </AuthFooterLinks>
); );

View File

@@ -13,12 +13,17 @@ export function AuthenticationLoadingOverlay() {
} }
const AuthOverlayRoot = styled.div` const AuthOverlayRoot = styled.div`
--x-color-background: rgba(252, 253, 255, 0.5);
.bp4-dark & {
--x-color-background: rgba(37, 42, 49, 0.60);
}
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
bottom: 0; bottom: 0;
right: 0; right: 0;
background: rgba(252, 253, 255, 0.5); background: var(--x-color-background);
display: flex; display: flex;
justify-content: center; justify-content: center;
`; `;

View File

@@ -45,10 +45,10 @@ export const InviteAcceptSchema = Yup.object().shape({
password: Yup.string().min(4).required().label(intl.get('password')), password: Yup.string().min(4).required().label(intl.get('password')),
}); });
export const transformSendResetPassErrorsToToasts = (errors) => { export const transformSendResetPassErrorsToToasts = (error) => {
const toastBuilders = []; const toastBuilders = [];
if (errors.find((e) => e.type === 'EMAIL.NOT.REGISTERED')) { if (error.code === ERRORS.EMAIL_NOT_REGISTERED) {
toastBuilders.push({ toastBuilders.push({
message: intl.get('we_couldn_t_find_your_account_with_that_email'), message: intl.get('we_couldn_t_find_your_account_with_that_email'),
intent: Intent.DANGER, intent: Intent.DANGER,
@@ -57,38 +57,26 @@ export const transformSendResetPassErrorsToToasts = (errors) => {
return toastBuilders; return toastBuilders;
}; };
export const transformLoginErrorsToToasts = (errors) => { export const transformLoginErrorsToToasts = (error) => {
const toastBuilders = []; const toastBuilders = [];
if (errors.find((e) => e.type === LOGIN_ERRORS.INVALID_DETAILS)) { if (error.code === LOGIN_ERRORS.INVALID_DETAILS) {
toastBuilders.push({ toastBuilders.push({
message: intl.get('email_and_password_entered_did_not_match'), message: intl.get('email_and_password_entered_did_not_match'),
intent: Intent.DANGER, intent: Intent.DANGER,
}); });
} } else if (error.code === LOGIN_ERRORS.USER_INACTIVE) {
if (errors.find((e) => e.type === LOGIN_ERRORS.USER_INACTIVE)) {
toastBuilders.push({ toastBuilders.push({
message: intl.get('the_user_has_been_suspended_from_admin'), message: intl.get('the_user_has_been_suspended_from_admin'),
intent: Intent.DANGER, intent: Intent.DANGER,
}); });
} }
if (errors.find((e) => e.type === LOGIN_ERRORS.LOGIN_TO_MANY_ATTEMPTS)) {
toastBuilders.push({
message: intl.get('your_account_has_been_locked'),
intent: Intent.DANGER,
});
}
return toastBuilders; return toastBuilders;
}; };
export const transformRegisterErrorsToForm = (errors) => { export const transformRegisterErrorsToForm = (errors) => {
const formErrors = {}; const formErrors = {};
if (errors.some((e) => e.type === REGISTER_ERRORS.PHONE_NUMBER_EXISTS)) {
formErrors.phone_number = intl.get(
'the_phone_number_already_used_in_another_account',
);
}
if (errors.some((e) => e.type === REGISTER_ERRORS.EMAIL_EXISTS)) { if (errors.some((e) => e.type === REGISTER_ERRORS.EMAIL_EXISTS)) {
formErrors.email = intl.get('the_email_already_used_in_another_account'); formErrors.email = intl.get('the_email_already_used_in_another_account');
} }

View File

@@ -15,7 +15,7 @@ const applyToTypeAccessor = (rule) => {
}; };
const conditionsAccessor = (rule) => ( const conditionsAccessor = (rule) => (
<span style={{ fontSize: 12, color: '#5F6B7C' }}> <span style={{ fontSize: 12 }}>
{rule.conditions_formatted} {rule.conditions_formatted}
</span> </span>
); );

View File

@@ -2,7 +2,7 @@
--x-border-color: #E1E1E1; --x-border-color: #E1E1E1;
--x-color-placeholder-text: #738091; --x-color-placeholder-text: #738091;
.bp4-dark & { :global(.bp4-dark) & {
--x-border-color: rgba(225, 225, 225, 0.15); --x-border-color: rgba(225, 225, 225, 0.15);
--x-color-placeholder-text: rgba(225, 225, 225, 0.65); --x-color-placeholder-text: rgba(225, 225, 225, 0.65);
} }

View File

@@ -53,7 +53,6 @@ export function CompanyLogoUpload({
const [initialLocalPreview, setInitialLocalPreview] = useState<string | null>( const [initialLocalPreview, setInitialLocalPreview] = useState<string | null>(
initialPreview || null, initialPreview || null,
); );
const openRef = useRef<() => void>(null); const openRef = useRef<() => void>(null);
const handleRemove = () => { const handleRemove = () => {

View File

@@ -101,11 +101,11 @@ export function ActionsCell(props) {
*/ */
export function PublishAccessor(row) { export function PublishAccessor(row) {
return row.is_published ? ( return row.is_published ? (
<Tag round={true} minimal={true}> <Tag round>
<T id={'published'} /> <T id={'published'} />
</Tag> </Tag>
) : ( ) : (
<Tag round={true} minimal={true} intent={Intent.WARNING}> <Tag round minimal intent={Intent.WARNING}>
<T id={'draft'} /> <T id={'draft'} />
</Tag> </Tag>
); );

View File

@@ -72,7 +72,7 @@ export const SellPriceCell = ({ cell: { value } }) => {
export const ItemTypeAccessor = (row) => { export const ItemTypeAccessor = (row) => {
return row.type_formatted ? ( return row.type_formatted ? (
<Tag minimal={true} round={true} intent={Intent.NONE}> <Tag round intent={Intent.NONE}>
{row.type_formatted} {row.type_formatted}
</Tag> </Tag>
) : null; ) : null;

View File

@@ -43,7 +43,7 @@ export function useEditProjectTimeEntry(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`projects/times/${id}`, values), ([id, values]) => apiRequest.put(`projects/times/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Invalidate specific project time entry. // Invalidate specific project time entry.

View File

@@ -39,7 +39,7 @@ export function useEditProject(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`/projects/${id}`, values), ([id, values]) => apiRequest.put(`/projects/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Invalidate specific project. // Invalidate specific project.

View File

@@ -41,7 +41,7 @@ export function useEditProjectTask(props) {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation(([id, values]) => apiRequest.post(`tasks/${id}`, values), { return useMutation(([id, values]) => apiRequest.put(`tasks/${id}`, values), {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Common invalidate queries. // Common invalidate queries.
commonInvalidateQueries(queryClient); commonInvalidateQueries(queryClient);

View File

@@ -46,12 +46,14 @@ function PaymentMadeFormProvider({ query, paymentMadeId, ...props }) {
// Handle fetch specific payment made details. // Handle fetch specific payment made details.
const { const {
data: { paymentMade: paymentMadeEditPage, entries: paymentEntriesEditPage }, data: paymentMadeEditData,
isFetching: isPaymentFetching, isFetching: isPaymentFetching,
isLoading: isPaymentLoading, isLoading: isPaymentLoading,
} = usePaymentMadeEditPage(paymentMadeId, { } = usePaymentMadeEditPage(paymentMadeId, {
enabled: !!paymentMadeId, enabled: !!paymentMadeId,
}); });
const paymentMadeEditPage = paymentMadeEditData?.bill_payment;
const paymentEntriesEditPage = paymentMadeEditData?.entries;
// Fetches the branches list. // Fetches the branches list.
const { const {

View File

@@ -22,27 +22,27 @@ import { safeCallback } from '@/utils';
export const statusAccessor = (row) => ( export const statusAccessor = (row) => (
<Choose> <Choose>
<Choose.When condition={row.is_approved}> <Choose.When condition={row.is_approved}>
<Tag minimal={true} intent={Intent.SUCCESS} round={true}> <Tag intent={Intent.SUCCESS} round>
<T id={'approved'} /> <T id={'approved'} />
</Tag> </Tag>
</Choose.When> </Choose.When>
<Choose.When condition={row.is_rejected}> <Choose.When condition={row.is_rejected}>
<Tag minimal={true} intent={Intent.DANGER} round={true}> <Tag intent={Intent.DANGER} round>
<T id={'rejected'} /> <T id={'rejected'} />
</Tag> </Tag>
</Choose.When> </Choose.When>
<Choose.When condition={row.is_expired}> <Choose.When condition={row.is_expired}>
<Tag minimal={true} intent={Intent.WARNING} round={true}> <Tag intent={Intent.WARNING} round>
<T id={'estimate.status.expired'} /> <T id={'estimate.status.expired'} />
</Tag> </Tag>
</Choose.When> </Choose.When>
<Choose.When condition={row.is_delivered}> <Choose.When condition={row.is_delivered}>
<Tag minimal={true} intent={Intent.SUCCESS} round={true}> <Tag intent={Intent.SUCCESS} round>
<T id={'delivered'} /> <T id={'delivered'} />
</Tag> </Tag>
</Choose.When> </Choose.When>
<Choose.Otherwise> <Choose.Otherwise>
<Tag minimal={true} round={true}> <Tag round>
<T id={'draft'} /> <T id={'draft'} />
</Tag> </Tag>
</Choose.Otherwise> </Choose.Otherwise>

View File

@@ -42,15 +42,15 @@ function PaymentReceiveFormProvider({ query, paymentReceiveId, ...props }) {
// Fetches payment recevie details. // Fetches payment recevie details.
const { const {
data: { data: paymentReceivedEditData,
paymentReceive: paymentReceiveEditPage,
entries: paymentEntriesEditPage,
},
isLoading: isPaymentLoading, isLoading: isPaymentLoading,
isFetching: isPaymentFetching, isFetching: isPaymentFetching,
} = usePaymentReceiveEditPage(paymentReceiveId, { } = usePaymentReceiveEditPage(paymentReceiveId, {
enabled: !!paymentReceiveId, enabled: !!paymentReceiveId,
}); });
const paymentReceiveEditPage = paymentReceivedEditData?.data;
const paymentEntriesEditPage = paymentReceivedEditData?.entries
// Handle fetch accounts data. // Handle fetch accounts data.
const { data: accounts, isLoading: isAccountsLoading } = useAccounts(); const { data: accounts, isLoading: isAccountsLoading } = useAccounts();

View File

@@ -91,7 +91,7 @@ export function useEditAccount(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`accounts/${id}`, values), ([id, values]) => apiRequest.put(`accounts/${id}`, values),
{ {
onSuccess: () => { onSuccess: () => {
// Common invalidate queries. // Common invalidate queries.

View File

@@ -1,7 +1,7 @@
// @ts-nocheck // @ts-nocheck
import { useMutation } from 'react-query'; import { useMutation } from 'react-query';
import { batch } from 'react-redux'; import { batch } from 'react-redux';
import useApiRequest from '../useRequest'; import useApiRequest, { useAuthApiRequest } from '../useRequest';
import { setCookie } from '../../utils'; import { setCookie } from '../../utils';
import { useRequestQuery } from '../useQueryRequest'; import { useRequestQuery } from '../useQueryRequest';
import t from './types'; import t from './types';
@@ -40,7 +40,7 @@ export function setAuthLoginCookies(data) {
* Authentication login. * Authentication login.
*/ */
export const useAuthLogin = (props) => { export const useAuthLogin = (props) => {
const apiRequest = useApiRequest(); const apiRequest = useAuthApiRequest();
const setAuthToken = useSetAuthToken(); const setAuthToken = useSetAuthToken();
const setOrganizationId = useSetOrganizationId(); const setOrganizationId = useSetOrganizationId();
@@ -49,7 +49,6 @@ export const useAuthLogin = (props) => {
const setLocale = useSetLocale(); const setLocale = useSetLocale();
return useMutation((values) => apiRequest.post(AuthRoute.Signin, values), { return useMutation((values) => apiRequest.post(AuthRoute.Signin, values), {
select: (res) => res.data,
onSuccess: (res) => { onSuccess: (res) => {
// Set authentication cookies. // Set authentication cookies.
setAuthLoginCookies(res.data); setAuthLoginCookies(res.data);
@@ -75,7 +74,7 @@ export const useAuthLogin = (props) => {
* Authentication register. * Authentication register.
*/ */
export const useAuthRegister = (props) => { export const useAuthRegister = (props) => {
const apiRequest = useApiRequest(); const apiRequest = useAuthApiRequest();
return useMutation( return useMutation(
(values) => apiRequest.post(AuthRoute.Signup, values), (values) => apiRequest.post(AuthRoute.Signup, values),
@@ -87,7 +86,7 @@ export const useAuthRegister = (props) => {
* Authentication send reset password. * Authentication send reset password.
*/ */
export const useAuthSendResetPassword = (props) => { export const useAuthSendResetPassword = (props) => {
const apiRequest = useApiRequest(); const apiRequest = useAuthApiRequest();
return useMutation( return useMutation(
(values) => apiRequest.post(AuthRoute.SendResetPassword, values), (values) => apiRequest.post(AuthRoute.SendResetPassword, values),
@@ -99,7 +98,7 @@ export const useAuthSendResetPassword = (props) => {
* Authentication reset password. * Authentication reset password.
*/ */
export const useAuthResetPassword = (props) => { export const useAuthResetPassword = (props) => {
const apiRequest = useApiRequest(); const apiRequest = useAuthApiRequest();
return useMutation( return useMutation(
([token, values]) => apiRequest.post(`auth/reset/${token}`, values), ([token, values]) => apiRequest.post(`auth/reset/${token}`, values),
@@ -129,7 +128,7 @@ export const useAuthMetadata = (props = {}) => {
* Resend the mail of signup verification. * Resend the mail of signup verification.
*/ */
export const useAuthSignUpVerifyResendMail = (props) => { export const useAuthSignUpVerifyResendMail = (props) => {
const apiRequest = useApiRequest(); const apiRequest = useAuthApiRequest();
return useMutation( return useMutation(
() => apiRequest.post(AuthRoute.SignupVerifyResend), () => apiRequest.post(AuthRoute.SignupVerifyResend),
@@ -146,7 +145,7 @@ interface AuthSignUpVerifyValues {
* Signup verification. * Signup verification.
*/ */
export const useAuthSignUpVerify = (props) => { export const useAuthSignUpVerify = (props) => {
const apiRequest = useApiRequest(); const apiRequest = useAuthApiRequest();
return useMutation( return useMutation(
(values: AuthSignUpVerifyValues) => (values: AuthSignUpVerifyValues) =>

View File

@@ -69,7 +69,7 @@ export function useEditBill(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`bills/${id}`, values), ([id, values]) => apiRequest.put(`bills/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Common invalidate queries. // Common invalidate queries.

View File

@@ -78,7 +78,7 @@ export function useEditCreditNote(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`credit-notes/${id}`, values), ([id, values]) => apiRequest.put(`credit-notes/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Common invalidate queries. // Common invalidate queries.

View File

@@ -47,7 +47,7 @@ export function useEditEstimate(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`sale-estimates/${id}`, values), ([id, values]) => apiRequest.put(`sale-estimates/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Common invalidate queries. // Common invalidate queries.

View File

@@ -85,7 +85,7 @@ export function useEditInvoice(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`sale-invoices/${id}`, values), ([id, values]) => apiRequest.put(`sale-invoices/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Invalidate specific sale invoice. // Invalidate specific sale invoice.

View File

@@ -1,5 +1,5 @@
// @ts-nocheck // @ts-nocheck
import { useMutation, useQueryClient } from 'react-query'; import { useMutation, useQuery, useQueryClient } from 'react-query';
import { useRequestQuery } from '../useQueryRequest'; import { useRequestQuery } from '../useQueryRequest';
import { transformPagination } from '@/utils'; import { transformPagination } from '@/utils';
import useApiRequest from '../useRequest'; import useApiRequest from '../useRequest';
@@ -66,16 +66,13 @@ export function useCreatePaymentMade(props) {
const client = useQueryClient(); const client = useQueryClient();
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation((values) => apiRequest.post('bill-payments', values), {
(values) => apiRequest.post('bill-payments', values), onSuccess: (res, values) => {
{ // Common invalidation queries.
onSuccess: (res, values) => { commonInvalidateQueries(client);
// Common invalidation queries.
commonInvalidateQueries(client);
},
...props,
}, },
); ...props,
});
} }
/** /**
@@ -86,7 +83,7 @@ export function useEditPaymentMade(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`bill-payments/${id}`, values), ([id, values]) => apiRequest.put(`bill-payments/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Common invalidation queries. // Common invalidation queries.
@@ -107,42 +104,28 @@ export function useDeletePaymentMade(props) {
const client = useQueryClient(); const client = useQueryClient();
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation((id) => apiRequest.delete(`bill-payments/${id}`), {
(id) => apiRequest.delete(`bill-payments/${id}`), onSuccess: (res, id) => {
{ // Common invalidation queries.
onSuccess: (res, id) => { commonInvalidateQueries(client);
// Common invalidation queries.
commonInvalidateQueries(client);
// Invalidate specific payment made. // Invalidate specific payment made.
client.invalidateQueries([t.PAYMENT_MADE, id]); client.invalidateQueries([t.PAYMENT_MADE, id]);
},
...props,
}, },
); ...props,
});
} }
/** /**
* Retrieve specific payment made. * Retrieve specific payment made.
*/ */
export function usePaymentMadeEditPage(id, props) { export function usePaymentMadeEditPage(
return useRequestQuery( id: number,
[t.PAYMENT_MADE_EDIT_PAGE, id], props: UseQueryOptions<any, Error>,
{ ) {
method: 'get', const apiRequest = useApiRequest();
url: `bill-payments/${id}/edit-page`, return useQuery([t.PAYMENT_MADE_EDIT_PAGE, id], () =>
}, apiRequest.get(`bill-payments/${id}/edit-page`).then((res) => res.data),
{
select: (res) => ({
paymentMade: res.data.bill_payment,
entries: res.data.entries,
}),
defaultData: {
paymentMade: {},
entries: [],
},
...props,
},
); );
} }

View File

@@ -111,7 +111,7 @@ export function useEditPaymentReceive(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`payments-received/${id}`, values), ([id, values]) => apiRequest.put(`payments-received/${id}`, values),
{ {
onSuccess: (data, [id, values]) => { onSuccess: (data, [id, values]) => {
// Invalidate specific payment receive. // Invalidate specific payment receive.
@@ -171,20 +171,10 @@ export function usePaymentReceive(id, props) {
* @param {number} id - Payment receive id. * @param {number} id - Payment receive id.
*/ */
export function usePaymentReceiveEditPage(id, props) { export function usePaymentReceiveEditPage(id, props) {
return useRequestQuery( const apiRequest = useApiRequest();
return useQuery(
[t.PAYMENT_RECEIVE_EDIT_PAGE, id], [t.PAYMENT_RECEIVE_EDIT_PAGE, id],
{ method: 'get', url: `payments-received/${id}/edit-page` }, () => apiRequest.get(`payments-received/${id}/edit-page`).then(res => res.data),
{
select: (res) => ({
paymentReceive: res.data,
entries: res.data.entries,
}),
defaultData: {
paymentReceive: {},
entries: [],
},
...props,
},
); );
} }

View File

@@ -71,7 +71,7 @@ export function useEditReceipt(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`sale-receipts/${id}`, values), ([id, values]) => apiRequest.put(`sale-receipts/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Invalidate specific receipt. // Invalidate specific receipt.

View File

@@ -18,7 +18,7 @@ export function useEditRolePermissionSchema(props) {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation(([id, values]) => apiRequest.post(`roles/${id}`, values), { return useMutation(([id, values]) => apiRequest.put(`roles/${id}`, values), {
onSuccess: () => { onSuccess: () => {
// Common invalidate queries. // Common invalidate queries.
commonInvalidateQueries(queryClient); commonInvalidateQueries(queryClient);

View File

@@ -54,7 +54,7 @@ export function useEditTaxRate(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`tax-rates/${id}`, values), ([id, values]) => apiRequest.put(`tax-rates/${id}`, values),
{ {
onSuccess: (res, id) => { onSuccess: (res, id) => {
commonInvalidateQueries(queryClient); commonInvalidateQueries(queryClient);

View File

@@ -35,7 +35,7 @@ export function useEditUser(props) {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation(([id, values]) => apiRequest.post(`users/${id}`, values), { return useMutation(([id, values]) => apiRequest.put(`users/${id}`, values), {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
queryClient.invalidateQueries([t.USER, id]); queryClient.invalidateQueries([t.USER, id]);

View File

@@ -77,7 +77,7 @@ export function useEditVendorCredit(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`vendor-credits/${id}`, values), ([id, values]) => apiRequest.put(`vendor-credits/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Common invalidate queries. // Common invalidate queries.

View File

@@ -45,7 +45,7 @@ export function useEditWarehouseTransfer(props) {
const apiRequest = useApiRequest(); const apiRequest = useApiRequest();
return useMutation( return useMutation(
([id, values]) => apiRequest.post(`warehouse-transfers/${id}`, values), ([id, values]) => apiRequest.put(`warehouse-transfers/${id}`, values),
{ {
onSuccess: (res, [id, values]) => { onSuccess: (res, [id, values]) => {
// Invalidate specific sale invoice. // Invalidate specific sale invoice.

View File

@@ -120,3 +120,35 @@ export default function useApiRequest() {
[http], [http],
); );
} }
export function useAuthApiRequest() {
const http = React.useMemo(() => {
// Axios instance.
return axios.create();
}, []);
return React.useMemo(
() => ({
http,
get(resource, params) {
return http.get(`/api/${resource}`, params);
},
post(resource, params, config) {
return http.post(`/api/${resource}`, params, config);
},
update(resource, slug, params) {
return http.put(`/api/${resource}/${slug}`, params);
},
put(resource, params) {
return http.put(`/api/${resource}`, params);
},
patch(resource, params, config) {
return http.patch(`/api/${resource}`, params, config);
},
delete(resource, params) {
return http.delete(`/api/${resource}`, params);
},
}),
[http],
);
}

286
setup.sh Normal file
View File

@@ -0,0 +1,286 @@
# Initialize the essential variables.
BRANCH=main
CURRENT=$PWD
BIGCAPITAL_INSTALL_DIR=$PWD/bigcapital-$(echo $BRANCH | sed -r 's@(\/|" "|\.)@-@g')
BIGCAPITAL_CLONE_TEMP_DIR=$(mktemp -d)
CPU_ARCH=$(uname -m)
DOCKER_FILE_PATH=./docker-compose.prod.yml
DOCKER_COMPOSE_DIR=docker
DOCKER_ENV_EXAMPLE_PATH=$CURRENT/.env.example
DOCKER_ENV_PATH=$CURRENT/.env
# if docker-compose is installed
if command -v docker-compose &> /dev/null
then
COMPOSE_CMD="docker-compose"
else
COMPOSE_CMD="docker compose"
fi
REPO=https://github.com/bigcapitalhq/bigcapital
# Prints the Bigcapital logo once running the script.
function print_logo() {
clear
cat <<"EOF"
--------------------------------------------
× ≠≠≠≠ ____ _ _ _ _
×××× ≠≠≠≠≠ | __ )(_) __ _ ___ __ _ _ __ (_) |_ __ _| |
××××× ≠≠≠≠≠ | _ \| |/ _` |/ __/ _` | '_ \| | __/ _` | |
××××× ≠≠≠≠≠= | |_) | | (_| | (_| (_| | |_) | | || (_| | |
××××× ≠≠≠≠≠≠ |____/|_|\__, |\___\__,_| .__/|_|\__\__,_|_|
×××× ≠≠≠ |___/ |_|
--------------------------------------------
Self-hosted modern core accounting software
--------------------------------------------
EOF
}
# Downloads /docker folder from Bigcapital repository
clone_github_folder() {
# Create a temporary directory to clone into
temp_dir=$BIGCAPITAL_CLONE_TEMP_DIR
# Clone the repository
git clone --branch=main --depth=1 "$1" "$temp_dir"
echo "The repository has been cloned."
DATE=$(date +%s)
if [ -f "$CURRENT/docker-compose.prod.yml" ]
then
mkdir -p $CURRENT/archive/$DATE
mv $CURRENT/docker-compose.prod.yml $CURRENT/archive/$DATE/docker-compose.prod.yml
fi
if [ -d "$CURRENT/docker" ]
then
mkdir -p $CURRENT/archive/$DATE
mv $CURRENT/docker $CURRENT/archive/$DATE/docker
fi
mv -f "$temp_dir/docker" "$CURRENT"
mv -f "$temp_dir/docker-compose.prod.yml" "$CURRENT"
mv -f "$temp_dir/.env.example" "$CURRENT/"
# Cleanup temporary directory
rm -rf "$temp_dir"
}
setup_env() {
if [ -f $DOCKER_ENV_EXAMPLE_PATH ];
then
cp "$CURRENT/.env.example" "$DOCKER_ENV_PATH"
fi
}
# Prints the main actions men.
function askForAction() {
local DEFAULT_ACTION=$1
if [ -z "$DEFAULT_ACTION" ];
then
echo
echo "Select a Action you want to perform:"
echo " 1) Install (${CPU_ARCH})"
echo " 2) Start"
echo " 3) Stop"
echo " 4) Restart"
echo " 5) Upgrade"
echo " 6) Logs"
echo " 7) Exit"
echo
read -p "Action [2]: " ACTION
until [[ -z "$ACTION" || "$ACTION" =~ ^[1-7]$ ]]; do
echo "$ACTION: invalid selection."
read -p "Action [2]: " ACTION
done
if [ -z "$ACTION" ];
then
ACTION=2
fi
echo
fi
if [ "$ACTION" == "1" ] || [ "$DEFAULT_ACTION" == "install" ]
then
install
askForAction
elif [ "$ACTION" == "2" ] || [ "$DEFAULT_ACTION" == "start" ]
then
startServices
askForAction
elif [ "$ACTION" == "3" ] || [ "$DEFAULT_ACTION" == "stop" ]
then
stopServices
askForAction
elif [ "$ACTION" == "4" ] || [ "$DEFAULT_ACTION" == "restart" ]
then
restartServices
askForAction
elif [ "$ACTION" == "5" ] || [ "$DEFAULT_ACTION" == "upgrade" ]
then
upgrade
askForAction
elif [ "$ACTION" == "6" ] || [ "$DEFAULT_ACTION" == "logs" ]
then
viewLogs $@
askForAction "logs"
elif [ "$ACTION" == "7" ]
then
exit 0
else
echo "Error: Invalid given action"
fi
}
function install() {
echo "Installing Bigcaoital.........."
echo "installing is going to take few mintues..."
download
setup_env
}
function download() {
# Download the docker/, docker-compose file and .env.example
clone_github_folder "https://github.com/bigcapitalhq/bigcapital.git"
/bin/bash -c "$COMPOSE_CMD -f $DOCKER_FILE_PATH --env-file=$DOCKER_ENV_PATH pull"
echo ""
echo "The stable version is now available for you to use"
echo ""
}
function startServices() {
/bin/bash -c "$COMPOSE_CMD -f $DOCKER_FILE_PATH --env-file=$DOCKER_ENV_PATH build"
/bin/bash -c "$COMPOSE_CMD -f $DOCKER_FILE_PATH --env-file=$DOCKER_ENV_PATH up -d"
local migrator_container_id=$(docker container ls -aq -f "name=bigcapital-database-migration")
if [ -n "$migrator_container_id" ]; then
local idx=0
while docker inspect --format='{{.State.Status}}' $migrator_container_id | grep -q "running"; do
local message=">> Waiting for database migration to finish"
local dots=$(printf '%*s' $idx | tr ' ' '.')
echo -ne "\r$message$dots"
((idx++))
sleep 1
done
fi
printf "\r\033[K"
echo ""
echo " Database migration completed successfully ✅"
# if migrator exit status is not 0, show error message and exit
if [ -n "$migrator_container_id" ]; then
local migrator_exit_code=$(docker inspect --format='{{.State.ExitCode}}' $migrator_container_id)
if [ $migrator_exit_code -ne 0 ]; then
echo "Bigcapital Server failed to start ❌"
stopServices
echo
echo "Please check the logs for the 'migrator' service and resolve the issue(s)."
echo "Stop the services by running the command: ./setup.sh stop"
exit 1
fi
fi
local api_container_id=$(docker container ls -q -f "name=bigcapital-server")
local idx2=0
while ! docker logs $api_container_id 2>&1 | grep -m 1 -i "Server listening on port" | grep -q ".";
do
local message=">> Waiting for Bigcapital Server to Start"
local dots=$(printf '%*s' $idx2 | tr ' ' '.')
echo -ne "\r$message$dots"
((idx2++))
sleep 1
done
printf "\r\033[K"
echo " API server started successfully ✅"
source "${DOCKER_ENV_PATH}"
echo " Bigcapital server started successfully ✅"
echo ""
echo " You can access the application at $WEB_URL"
echo ""
}
# Stoppes all the Docker containers.
function stopServices() {
/bin/bash -c "$COMPOSE_CMD -f $DOCKER_FILE_PATH --env-file=$DOCKER_ENV_PATH down"
}
# Restarts all the Docker containers.
function restartServices() {
stopServices
startServices
}
function viewLogs(){
ARG_SERVICE_NAME=$2
echo
echo "Select a Service you want to view the logs for:"
echo " 1) Webapp"
echo " 2) API"
echo " 3) Migration"
echo " 4) Nginx Proxy"
echo " 5) MariaDB"
echo " 0) Back to Main Menu"
echo
read -p "Service: " DOCKER_SERVICE_NAME
until (( DOCKER_SERVICE_NAME >= 0 && DOCKER_SERVICE_NAME <= 5 )); do
echo "Invalid selection. Please enter a number between 1 and 11."
read -p "Service: " DOCKER_SERVICE_NAME
done
if [ -z "$DOCKER_SERVICE_NAME" ];
then
echo "INVALID SERVICE NAME SUPPLIED"
else
case $DOCKER_SERVICE_NAME in
1) viewSpecificLogs "webapp";;
2) viewSpecificLogs "server";;
3) viewSpecificLogs "database_migration";;
4) viewSpecificLogs "nginx";;
5) viewSpecificLogs "mysql";;
0) askForAction;;
*) echo "INVALID SERVICE NAME SUPPLIED";;
esac
fi
}
function viewSpecificLogs(){
local SERVICE_NAME=$1
if /bin/bash -c "$COMPOSE_CMD -f $DOCKER_FILE_PATH ps | grep -q '$SERVICE_NAME'"; then
echo "Service '$SERVICE_NAME' is running."
else
echo "Service '$SERVICE_NAME' is not running."
fi
/bin/bash -c "$COMPOSE_CMD -f $DOCKER_FILE_PATH logs -f $SERVICE_NAME"
}
function upgrade() {
echo "***** STOPPING SERVICES ****"
stopServices
echo
echo "***** DOWNLOADING STABLE VERSION ****"
download
echo "***** PLEASE VALIDATE AND START SERVICES ****"
}
mkdir -p $CURRENT/archive
# Display the header and run the actions menu.
print_logo
askForAction $@