Browse Source

feat(core): Constrain channel-aware queries by channelId

Relates to #12
Michael Bromley 6 years ago
parent
commit
51c1b07f13

+ 2 - 2
packages/core/src/api/resolvers/admin/promotion.resolver.ts

@@ -27,7 +27,7 @@ export class PromotionResolver {
         @Ctx() ctx: RequestContext,
         @Args() args: QueryPromotionsArgs,
     ): Promise<PaginatedList<Promotion>> {
-        return this.promotionService.findAll(args.options || undefined).then(res => {
+        return this.promotionService.findAll(ctx, args.options || undefined).then(res => {
             res.items.forEach(this.encodeConditionsAndActions);
             return res;
         });
@@ -36,7 +36,7 @@ export class PromotionResolver {
     @Query()
     @Allow(Permission.ReadPromotion)
     promotion(@Ctx() ctx: RequestContext, @Args() args: QueryPromotionArgs): Promise<Promotion | undefined> {
-        return this.promotionService.findOne(args.id).then(this.encodeConditionsAndActions);
+        return this.promotionService.findOne(ctx, args.id).then(this.encodeConditionsAndActions);
     }
 
     @Query()

+ 20 - 8
packages/core/src/api/resolvers/admin/shipping-method.resolver.ts

@@ -29,14 +29,20 @@ export class ShippingMethodResolver {
 
     @Query()
     @Allow(Permission.ReadSettings)
-    shippingMethods(@Args() args: QueryShippingMethodsArgs): Promise<PaginatedList<ShippingMethod>> {
-        return this.shippingMethodService.findAll(args.options || undefined);
+    shippingMethods(
+        @Ctx() ctx: RequestContext,
+        @Args() args: QueryShippingMethodsArgs,
+    ): Promise<PaginatedList<ShippingMethod>> {
+        return this.shippingMethodService.findAll(ctx, args.options || undefined);
     }
 
     @Query()
     @Allow(Permission.ReadSettings)
-    shippingMethod(@Args() args: QueryShippingMethodArgs): Promise<ShippingMethod | undefined> {
-        return this.shippingMethodService.findOne(args.id);
+    shippingMethod(
+        @Ctx() ctx: RequestContext,
+        @Args() args: QueryShippingMethodArgs,
+    ): Promise<ShippingMethod | undefined> {
+        return this.shippingMethodService.findOne(ctx, args.id);
     }
 
     @Query()
@@ -53,16 +59,22 @@ export class ShippingMethodResolver {
 
     @Mutation()
     @Allow(Permission.CreateSettings)
-    createShippingMethod(@Args() args: MutationCreateShippingMethodArgs): Promise<ShippingMethod> {
+    createShippingMethod(
+        @Ctx() ctx: RequestContext,
+        @Args() args: MutationCreateShippingMethodArgs,
+    ): Promise<ShippingMethod> {
         const { input } = args;
-        return this.shippingMethodService.create(input);
+        return this.shippingMethodService.create(ctx, input);
     }
 
     @Mutation()
     @Allow(Permission.UpdateSettings)
-    updateShippingMethod(@Args() args: MutationUpdateShippingMethodArgs): Promise<ShippingMethod> {
+    updateShippingMethod(
+        @Ctx() ctx: RequestContext,
+        @Args() args: MutationUpdateShippingMethodArgs,
+    ): Promise<ShippingMethod> {
         const { input } = args;
-        return this.shippingMethodService.update(input);
+        return this.shippingMethodService.update(ctx, input);
     }
 
     @Mutation()

+ 4 - 2
packages/core/src/api/resolvers/entity/order-entity.resolver.ts

@@ -6,7 +6,9 @@ import { HistoryService } from '../../../service/services/history.service';
 import { OrderService } from '../../../service/services/order.service';
 import { ShippingMethodService } from '../../../service/services/shipping-method.service';
 import { ApiType } from '../../common/get-api-type';
+import { RequestContext } from '../../common/request-context';
 import { Api } from '../../decorators/api.decorator';
+import { Ctx } from '../../decorators/request-context.decorator';
 
 @Resolver('Order')
 export class OrderEntityResolver {
@@ -25,12 +27,12 @@ export class OrderEntityResolver {
     }
 
     @ResolveProperty()
-    async shippingMethod(@Parent() order: Order) {
+    async shippingMethod(@Ctx() ctx: RequestContext, @Parent() order: Order) {
         if (order.shippingMethodId) {
             // Does not need to be decoded because it is an internal property
             // which is never exposed to the outside world.
             const shippingMethodId = order.shippingMethodId;
-            return this.shippingMethodService.findOne(shippingMethodId);
+            return this.shippingMethodService.findOne(ctx, shippingMethodId);
         } else {
             return null;
         }

+ 1 - 1
packages/core/src/data-import/providers/populator/populator.ts

@@ -197,7 +197,7 @@ export class Populator {
         shippingMethods: Array<{ name: string; price: number }>,
     ) {
         for (const method of shippingMethods) {
-            await this.shippingMethodService.create({
+            await this.shippingMethodService.create(ctx, {
                 checker: {
                     code: defaultShippingEligibilityChecker.code,
                     arguments: [{ name: 'orderMinimum', value: '0', type: 'int' }],

+ 1 - 0
packages/core/src/entity/promotion/promotion.entity.ts

@@ -87,6 +87,7 @@ export class Promotion extends AdjustmentSource implements ChannelAware, SoftDel
     @Column('simple-json') actions: ConfigurableOperation[];
 
     /**
+     * @description
      * The PriorityScore is used to determine the sequence in which multiple promotions are tested
      * on a given order. A higher number moves the Promotion towards the end of the sequence.
      *

+ 3 - 2
packages/core/src/service/services/collection.service.ts

@@ -37,6 +37,7 @@ import { CollectionModificationEvent } from '../../event-bus/events/collection-m
 import { WorkerService } from '../../worker/worker.service';
 import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder';
 import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver';
+import { findOneInChannel } from '../helpers/utils/channel-aware-orm-utils';
 import { getEntityOrThrow } from '../helpers/utils/get-entity-or-throw';
 import { moveToIndex } from '../helpers/utils/move-to-index';
 import { translateDeep } from '../helpers/utils/translate-entity';
@@ -103,9 +104,9 @@ export class CollectionService implements OnModuleInit {
             });
     }
 
-    async findOne(ctx: RequestContext, productId: ID): Promise<Translated<Collection> | undefined> {
+    async findOne(ctx: RequestContext, collectionId: ID): Promise<Translated<Collection> | undefined> {
         const relations = ['featuredAsset', 'assets', 'channels', 'parent'];
-        const collection = await this.connection.getRepository(Collection).findOne(productId, {
+        const collection = await findOneInChannel(this.connection, Collection, collectionId, ctx.channelId, {
             relations,
         });
         if (!collection) {

+ 13 - 6
packages/core/src/service/services/promotion.service.ts

@@ -33,6 +33,7 @@ import { PromotionCondition } from '../../config/promotion/promotion-condition';
 import { Order } from '../../entity/order/order.entity';
 import { Promotion } from '../../entity/promotion/promotion.entity';
 import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder';
+import { findOneInChannel } from '../helpers/utils/channel-aware-orm-utils';
 import { getEntityOrThrow } from '../helpers/utils/get-entity-or-throw';
 import { patchEntity } from '../helpers/utils/patch-entity';
 
@@ -59,9 +60,13 @@ export class PromotionService {
         this.availableActions = this.configService.promotionOptions.promotionActions || [];
     }
 
-    findAll(options?: ListQueryOptions<Promotion>): Promise<PaginatedList<Promotion>> {
+    findAll(ctx: RequestContext, options?: ListQueryOptions<Promotion>): Promise<PaginatedList<Promotion>> {
         return this.listQueryBuilder
-            .build(Promotion, options, { where: { deletedAt: null } })
+            .build(Promotion, options, {
+                where: { deletedAt: null },
+                channelId: ctx.channelId,
+                relations: ['channels'],
+            })
             .getManyAndCount()
             .then(([items, totalItems]) => ({
                 items,
@@ -69,8 +74,10 @@ export class PromotionService {
             }));
     }
 
-    async findOne(adjustmentSourceId: ID): Promise<Promotion | undefined> {
-        return this.connection.manager.findOne(Promotion, adjustmentSourceId, { where: { deletedAt: null } });
+    async findOne(ctx: RequestContext, adjustmentSourceId: ID): Promise<Promotion | undefined> {
+        return findOneInChannel(this.connection, Promotion, adjustmentSourceId, ctx.channelId, {
+            where: { deletedAt: null },
+        });
     }
 
     getPromotionConditions(ctx: RequestContext): ConfigurableOperationDefinition[] {
@@ -107,7 +114,7 @@ export class PromotionService {
         this.channelService.assignToCurrentChannel(promotion, ctx);
         const newPromotion = await this.connection.manager.save(promotion);
         await this.updatePromotions();
-        return assertFound(this.findOne(newPromotion.id));
+        return assertFound(this.findOne(ctx, newPromotion.id));
     }
 
     async updatePromotion(ctx: RequestContext, input: UpdatePromotionInput): Promise<Promotion> {
@@ -123,7 +130,7 @@ export class PromotionService {
         (promotion.priorityScore = this.calculatePriorityScore(input)),
             await this.connection.manager.save(updatedPromotion);
         await this.updatePromotions();
-        return assertFound(this.findOne(updatedPromotion.id));
+        return assertFound(this.findOne(ctx, updatedPromotion.id));
     }
 
     async softDeletePromotion(promotionId: ID): Promise<DeletionResponse> {

+ 14 - 9
packages/core/src/service/services/shipping-method.service.ts

@@ -21,6 +21,7 @@ import { Channel } from '../../entity/channel/channel.entity';
 import { ShippingMethod } from '../../entity/shipping-method/shipping-method.entity';
 import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder';
 import { ShippingConfiguration } from '../helpers/shipping-configuration/shipping-configuration';
+import { findOneInChannel } from '../helpers/utils/channel-aware-orm-utils';
 import { getEntityOrThrow } from '../helpers/utils/get-entity-or-throw';
 import { patchEntity } from '../helpers/utils/patch-entity';
 
@@ -42,11 +43,15 @@ export class ShippingMethodService {
         await this.updateActiveShippingMethods();
     }
 
-    findAll(options?: ListQueryOptions<ShippingMethod>): Promise<PaginatedList<ShippingMethod>> {
+    findAll(
+        ctx: RequestContext,
+        options?: ListQueryOptions<ShippingMethod>,
+    ): Promise<PaginatedList<ShippingMethod>> {
         return this.listQueryBuilder
             .build(ShippingMethod, options, {
                 relations: ['channels'],
                 where: { deletedAt: null },
+                channelId: ctx.channelId,
             })
             .getManyAndCount()
             .then(([items, totalItems]) => ({
@@ -55,28 +60,28 @@ export class ShippingMethodService {
             }));
     }
 
-    findOne(shippingMethodId: ID): Promise<ShippingMethod | undefined> {
-        return this.connection.manager.findOne(ShippingMethod, shippingMethodId, {
+    findOne(ctx: RequestContext, shippingMethodId: ID): Promise<ShippingMethod | undefined> {
+        return findOneInChannel(this.connection, ShippingMethod, shippingMethodId, ctx.channelId, {
             relations: ['channels'],
             where: { deletedAt: null },
         });
     }
 
-    async create(input: CreateShippingMethodInput): Promise<ShippingMethod> {
+    async create(ctx: RequestContext, input: CreateShippingMethodInput): Promise<ShippingMethod> {
         const shippingMethod = new ShippingMethod({
             code: input.code,
             description: input.description,
             checker: this.shippingConfiguration.parseCheckerInput(input.checker),
             calculator: this.shippingConfiguration.parseCalculatorInput(input.calculator),
         });
-        shippingMethod.channels = [this.channelService.getDefaultChannel()];
+        this.channelService.assignToCurrentChannel(shippingMethod, ctx);
         const newShippingMethod = await this.connection.manager.save(shippingMethod);
         await this.updateActiveShippingMethods();
-        return assertFound(this.findOne(newShippingMethod.id));
+        return assertFound(this.findOne(ctx, newShippingMethod.id));
     }
 
-    async update(input: UpdateShippingMethodInput): Promise<ShippingMethod> {
-        const shippingMethod = await this.findOne(input.id);
+    async update(ctx: RequestContext, input: UpdateShippingMethodInput): Promise<ShippingMethod> {
+        const shippingMethod = await this.findOne(ctx, input.id);
         if (!shippingMethod) {
             throw new EntityNotFoundError('ShippingMethod', input.id);
         }
@@ -91,7 +96,7 @@ export class ShippingMethodService {
         }
         await this.connection.manager.save(updatedShippingMethod);
         await this.updateActiveShippingMethods();
-        return assertFound(this.findOne(shippingMethod.id));
+        return assertFound(this.findOne(ctx, shippingMethod.id));
     }
 
     async softDelete(ctx: RequestContext, id: ID): Promise<DeletionResponse> {