Просмотр исходного кода

Merge pull request #4223 from weseek/feat/7281-rewrite-cache-crud

Feat/7281 rewrite cache crud
Yuki Takei 4 лет назад
Родитель
Сommit
16bd3aca58

+ 27 - 39
packages/app/src/server/routes/apiv3/slack-integration-settings.js

@@ -400,24 +400,18 @@ module.exports = (crowi) => {
    *            description: Succeeded to create slack app integration
    *            description: Succeeded to create slack app integration
    */
    */
   router.put('/slack-app-integrations', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
   router.put('/slack-app-integrations', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
-    const SlackAppIntegrationRecordsNum = await SlackAppIntegration.countDocuments();
-    if (SlackAppIntegrationRecordsNum >= 10) {
+    const SlackAppIntegrationMock = mongoose.model('SlackAppIntegrationMock');
+    const SlackAppIntegrationMockRecordsNum = await SlackAppIntegrationMock.countDocuments();
+    if (SlackAppIntegrationMockRecordsNum >= 10) {
       const msg = 'Not be able to create more than 10 slack workspace integration settings';
       const msg = 'Not be able to create more than 10 slack workspace integration settings';
       logger.error('Error', msg);
       logger.error('Error', msg);
       return res.apiv3Err(new ErrorV3(msg, 'create-slackAppIntegeration-failed'), 500);
       return res.apiv3Err(new ErrorV3(msg, 'create-slackAppIntegeration-failed'), 500);
     }
     }
 
 
-    const { tokenGtoP, tokenPtoG } = await SlackAppIntegration.generateUniqueAccessTokens();
+    const { tokenGtoP, tokenPtoG } = await SlackAppIntegrationMock.generateUniqueAccessTokens();
     try {
     try {
-      const slackAppTokens = await SlackAppIntegration.create({
-        tokenGtoP,
-        tokenPtoG,
-        supportedCommandsForBroadcastUse: defaultSupportedCommandsNameForBroadcastUse,
-        supportedCommandsForSingleUse: defaultSupportedCommandsNameForSingleUse,
-      });
       // MOCK DATA DELETE THIS GW-6972 ---------------
       // MOCK DATA DELETE THIS GW-6972 ---------------
       /* This code represents the creation of the new SlackAppIntegration model instance. */
       /* This code represents the creation of the new SlackAppIntegration model instance. */
-      const SlackAppIntegrationMock = mongoose.model('SlackAppIntegrationMock');
       const initialSupportedCommandsForBroadcastUse = new Map();
       const initialSupportedCommandsForBroadcastUse = new Map();
       const initialSupportedCommandsForSingleUse = new Map();
       const initialSupportedCommandsForSingleUse = new Map();
       defaultSupportedCommandsNameForBroadcastUse.forEach((commandName) => {
       defaultSupportedCommandsNameForBroadcastUse.forEach((commandName) => {
@@ -426,14 +420,14 @@ module.exports = (crowi) => {
       defaultSupportedCommandsNameForSingleUse.forEach((commandName) => {
       defaultSupportedCommandsNameForSingleUse.forEach((commandName) => {
         initialSupportedCommandsForSingleUse.set(commandName, true);
         initialSupportedCommandsForSingleUse.set(commandName, true);
       });
       });
-      const MOCK = await SlackAppIntegrationMock.create({
+      const slackAppTokensMOCK = await SlackAppIntegrationMock.create({
         tokenGtoP,
         tokenGtoP,
         tokenPtoG,
         tokenPtoG,
         permissionsForBroadcastUseCommands: initialSupportedCommandsForBroadcastUse,
         permissionsForBroadcastUseCommands: initialSupportedCommandsForBroadcastUse,
         permissionsForSingleUseCommands: initialSupportedCommandsForSingleUse,
         permissionsForSingleUseCommands: initialSupportedCommandsForSingleUse,
       });
       });
       // MOCK DATA DELETE THIS GW-6972 ---------------
       // MOCK DATA DELETE THIS GW-6972 ---------------
-      return res.apiv3(slackAppTokens, 200);
+      return res.apiv3(slackAppTokensMOCK, 200);
     }
     }
     catch (error) {
     catch (error) {
       const msg = 'Error occurred during creating slack integration settings procedure';
       const msg = 'Error occurred during creating slack integration settings procedure';
@@ -535,25 +529,14 @@ module.exports = (crowi) => {
     const { id } = req.params;
     const { id } = req.params;
 
 
     try {
     try {
+      // NOT MOCK DATA BUT REFER THIS GW-7006
       const slackAppIntegration = await SlackAppIntegration.findByIdAndUpdate(
       const slackAppIntegration = await SlackAppIntegration.findByIdAndUpdate(
         id,
         id,
         { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse },
         { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse },
         { new: true },
         { new: true },
       );
       );
 
 
-      // await requestToProxyServer(
-      //   slackAppIntegration.tokenGtoP,
-      //   'put',
-      //   '/g2s/supported-commands',
-      //   {
-      //     supportedCommandsForBroadcastUse: slackAppIntegration.supportedCommandsForBroadcastUse,
-      //     supportedCommandsForSingleUse: slackAppIntegration.supportedCommandsForSingleUse,
-      //   },
-      // );
-
-      // return res.apiv3({ slackAppIntegration });
-
-      // MOCK DATA DELETE THIS GW-6972 ---------------
+      // MOCK DATA MODIFY THIS GW-6972 ---------------
       /**
       /**
        * this code represents the update operation using request from client (slackapp integration settings page)
        * this code represents the update operation using request from client (slackapp integration settings page)
        * , then send request to proxy to update cache
        * , then send request to proxy to update cache
@@ -561,15 +544,18 @@ module.exports = (crowi) => {
        */
        */
       const SlackAppIntegrationMock = mongoose.model('SlackAppIntegrationMock');
       const SlackAppIntegrationMock = mongoose.model('SlackAppIntegrationMock');
       // MOCK DATA FROM CLIENT assume that these data were sent from client
       // MOCK DATA FROM CLIENT assume that these data were sent from client
-      const permittedChannelsForEachCommandFromClient = {
-        channelsObject: { search: ['random'] },
+      const permissionsForBroadcastUseCommandsFromClient = {
+        search: false,
+      };
+      const permissionsForSingleUseCommandsFromClient = {
+        create: ['random'],
       };
       };
       const slackAppIntegrationMock = await SlackAppIntegrationMock.findOneAndUpdate(
       const slackAppIntegrationMock = await SlackAppIntegrationMock.findOneAndUpdate(
+        // MOCK DATA USE id IN req.params LIKE ABOVE
         { tokenPtoG: slackAppIntegration.tokenPtoG },
         { tokenPtoG: slackAppIntegration.tokenPtoG },
         {
         {
-          supportedCommandsForBroadcastUse,
-          supportedCommandsForSingleUse,
-          permittedChannelsForEachCommand: permittedChannelsForEachCommandFromClient,
+          permissionsForBroadcastUseCommands: permissionsForBroadcastUseCommandsFromClient,
+          permissionsForSingleUseCommands: permissionsForSingleUseCommandsFromClient,
         },
         },
         { new: true },
         { new: true },
       );
       );
@@ -579,12 +565,11 @@ module.exports = (crowi) => {
         'put',
         'put',
         '/g2s/supported-commands',
         '/g2s/supported-commands',
         {
         {
-          supportedCommandsForBroadcastUse: slackAppIntegrationMock.supportedCommandsForBroadcastUse,
-          supportedCommandsForSingleUse: slackAppIntegrationMock.supportedCommandsForSingleUse,
-          permittedChannelsForEachCommand: slackAppIntegrationMock.permittedChannelsForEachCommand,
+          permissionsForBroadcastUseCommands: slackAppIntegrationMock.permissionsForBroadcastUseCommands,
+          permissionsForSingleUseCommands: slackAppIntegrationMock.permissionsForSingleUseCommands,
         },
         },
       );
       );
-      // MOCK DATA DELETE THIS GW-6972 ---------------
+      // MOCK DATA MODIFY THIS GW-6972 ---------------
 
 
       return res.apiv3({ slackAppIntegrationMock });
       return res.apiv3({ slackAppIntegrationMock });
     }
     }
@@ -625,20 +610,23 @@ module.exports = (crowi) => {
     const { slackAppIntegrationId } = req.body;
     const { slackAppIntegrationId } = req.body;
     let slackBotToken;
     let slackBotToken;
     try {
     try {
-      const slackAppIntegration = await SlackAppIntegration.findOne({ _id: slackAppIntegrationId });
-      if (slackAppIntegration == null) {
+      // MOCK DATA DELETE THIS GW-6972 ---------------
+      const SlackAppIntegrationMock = mongoose.model('SlackAppIntegrationMock');
+      const slackAppIntegrationMock = await SlackAppIntegrationMock.findOne({ _id: slackAppIntegrationId });
+      // MOCK DATA DELETE THIS GW-6972 ---------------
+      if (slackAppIntegrationMock == null) {
         const msg = 'Could not find SlackAppIntegration by id';
         const msg = 'Could not find SlackAppIntegration by id';
         return res.apiv3Err(new ErrorV3(msg, 'find-slackAppIntegration-failed'), 400);
         return res.apiv3Err(new ErrorV3(msg, 'find-slackAppIntegration-failed'), 400);
       }
       }
 
 
       // USE MOCK DATA HERE FOR cache creation at /relation-test GW-7021
       // USE MOCK DATA HERE FOR cache creation at /relation-test GW-7021
       const result = await requestToProxyServer(
       const result = await requestToProxyServer(
-        slackAppIntegration.tokenGtoP,
+        slackAppIntegrationMock.tokenGtoP,
         'post',
         'post',
         '/g2s/relation-test',
         '/g2s/relation-test',
         {
         {
-          supportedCommandsForBroadcastUse: slackAppIntegration.supportedCommandsForBroadcastUse,
-          supportedCommandsForSingleUse: slackAppIntegration.supportedCommandsForSingleUse,
+          permissionsForBroadcastUseCommands: slackAppIntegrationMock.permissionsForBroadcastUseCommands,
+          permissionsForSingleUseCommands: slackAppIntegrationMock.permissionsForSingleUseCommands,
         },
         },
       );
       );
 
 

+ 8 - 5
packages/app/src/server/routes/apiv3/slack-integration.js

@@ -8,7 +8,8 @@ const { verifySlackRequest, generateWebClient, getSupportedGrowiActionsRegExps }
 
 
 const logger = loggerFactory('growi:routes:apiv3:slack-integration');
 const logger = loggerFactory('growi:routes:apiv3:slack-integration');
 const router = express.Router();
 const router = express.Router();
-const SlackAppIntegration = mongoose.model('SlackAppIntegration');
+const SlackAppIntegration = mongoose.model('SlackAppIntegrationMock');
+const SlackAppIntegrationMock = mongoose.model('SlackAppIntegrationMock');
 const { respondIfSlackbotError } = require('../../service/slack-command-handler/respond-if-slackbot-error');
 const { respondIfSlackbotError } = require('../../service/slack-command-handler/respond-if-slackbot-error');
 
 
 module.exports = (crowi) => {
 module.exports = (crowi) => {
@@ -26,14 +27,15 @@ module.exports = (crowi) => {
       return res.status(400).send({ message });
       return res.status(400).send({ message });
     }
     }
 
 
-    const slackAppIntegrationCount = await SlackAppIntegration.countDocuments({ tokenPtoG });
+    // MOCK DATA MODIFY THIS WITH SlackAppIntegration GW-7006 --------------
+    const slackAppIntegrationMockCount = await SlackAppIntegrationMock.countDocuments({ tokenPtoG });
 
 
     logger.debug('verifyAccessTokenFromProxy', {
     logger.debug('verifyAccessTokenFromProxy', {
       tokenPtoG,
       tokenPtoG,
-      slackAppIntegrationCount,
+      slackAppIntegrationMockCount,
     });
     });
 
 
-    if (slackAppIntegrationCount === 0) {
+    if (slackAppIntegrationMockCount === 0) {
       return res.status(403).send({
       return res.status(403).send({
         message: 'The access token that identifies the request source is slackbot-proxy is invalid. Did you setup with `/growi register`.\n'
         message: 'The access token that identifies the request source is slackbot-proxy is invalid. Did you setup with `/growi register`.\n'
         + 'Or did you delete registration for GROWI ? if so, the link with GROWI has been disconnected. '
         + 'Or did you delete registration for GROWI ? if so, the link with GROWI has been disconnected. '
@@ -260,7 +262,8 @@ module.exports = (crowi) => {
     // MOCK DATA DELETE THIS GW-6972 ---------
     // MOCK DATA DELETE THIS GW-6972 ---------
     const SlackAppIntegrationMock = mongoose.model('SlackAppIntegrationMock');
     const SlackAppIntegrationMock = mongoose.model('SlackAppIntegrationMock');
     const slackAppIntegrationMock = await SlackAppIntegrationMock.findOne({ tokenPtoG });
     const slackAppIntegrationMock = await SlackAppIntegrationMock.findOne({ tokenPtoG });
-    return res.apiv3({ slackAppIntegrationMock });
+    const { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands } = slackAppIntegrationMock;
+    return res.apiv3({ permissionsForBroadcastUseCommands, permissionsForSingleUseCommands });
     // MOCK DATA DELETE THIS GW-6972 ---------
     // MOCK DATA DELETE THIS GW-6972 ---------
 
 
     // const slackAppIntegration = await SlackAppIntegration.findOne({ tokenPtoG });
     // const slackAppIntegration = await SlackAppIntegration.findOne({ tokenPtoG });

+ 1 - 1
packages/slack/src/middlewares/verify-growi-to-slack-request.ts

@@ -4,7 +4,7 @@ import createError from 'http-errors';
 import loggerFactory from '../utils/logger';
 import loggerFactory from '../utils/logger';
 import { RequestFromGrowi } from '../interfaces/request-between-growi-and-proxy';
 import { RequestFromGrowi } from '../interfaces/request-between-growi-and-proxy';
 
 
-const logger = loggerFactory('@growi/slack:middlewares:verify-slack-request');
+const logger = loggerFactory('@growi/slack:middlewares:verify-growi-to-slack-request');
 
 
 /**
 /**
  * Verify if the request came from slack
  * Verify if the request came from slack

+ 15 - 39
packages/slackbot-proxy/src/controllers/growi-to-slack.ts

@@ -102,24 +102,21 @@ export class GrowiToSlackCtrl {
     // asserted (tokenGtoPs.length > 0) by verifyGrowiToSlackRequest
     // asserted (tokenGtoPs.length > 0) by verifyGrowiToSlackRequest
     const { tokenGtoPs } = req;
     const { tokenGtoPs } = req;
 
 
-    // const { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse } = req.body;
-
-    // MOCK DATA DELETE THIS GW 6972 -----------
-    const { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse, permittedChannelsForEachCommand } = req.body;
-    // MOCK DATA DELETE THIS GW 6972 -----------
+    // MOCK DATA SO FAR BUT THIS CAN BE USED AS AN ACTUAL CODE AS WELL GW 6972 -----------
+    const { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands } = req.body;
+    // MOCK DATA SO FAR BUT THIS CAN BE USED AS AN ACTUAL CODE AS WELL GW 6972 -----------
 
 
     if (tokenGtoPs.length !== 1) {
     if (tokenGtoPs.length !== 1) {
       throw createError(400, 'installation is invalid');
       throw createError(400, 'installation is invalid');
     }
     }
 
 
     const tokenGtoP = tokenGtoPs[0];
     const tokenGtoP = tokenGtoPs[0];
-    // const relation = await this.relationRepository.update({ tokenGtoP }, { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse });
 
 
-    // MOCK DATA DELETE THIS GW 6972 -----------
+    // MOCK DATA MODIFY THIS GW 6972 -----------
     const relation = await this.relationMockRepository.update(
     const relation = await this.relationMockRepository.update(
-      { tokenGtoP }, { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse, permittedChannelsForEachCommand },
+      { tokenGtoP }, { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands },
     );
     );
-    // MOCK DATA DELETE THIS GW 6972 -----------
+    // MOCK DATA MODIFY THIS GW 6972 -----------
 
 
     return res.send({ relation });
     return res.send({ relation });
   }
   }
@@ -136,7 +133,7 @@ export class GrowiToSlackCtrl {
     const tokenGtoP = tokenGtoPs[0];
     const tokenGtoP = tokenGtoPs[0];
 
 
     // retrieve relation with Installation
     // retrieve relation with Installation
-    const relation = await this.relationRepository.createQueryBuilder('relation')
+    const relation = await this.relationMockRepository.createQueryBuilder('relation')
       .where('tokenGtoP = :token', { token: tokenGtoP })
       .where('tokenGtoP = :token', { token: tokenGtoP })
       .leftJoinAndSelect('relation.installation', 'installation')
       .leftJoinAndSelect('relation.installation', 'installation')
       .getOne();
       .getOne();
@@ -203,55 +200,34 @@ export class GrowiToSlackCtrl {
     // temporary cache for 48 hours
     // temporary cache for 48 hours
     const expiredAtCommands = addHours(new Date(), 48);
     const expiredAtCommands = addHours(new Date(), 48);
 
 
-    // Transaction is not considered because it is used infrequently,
-    const response = await this.relationRepository.createQueryBuilder('relation')
-      .insert()
-      .values({
-        installation: order.installation,
-        tokenGtoP: order.tokenGtoP,
-        tokenPtoG: order.tokenPtoG,
-        growiUri: order.growiUrl,
-        supportedCommandsForBroadcastUse: req.body.supportedCommandsForBroadcastUse,
-        supportedCommandsForSingleUse: req.body.supportedCommandsForSingleUse,
-        expiredAtCommands,
-      })
-      // https://github.com/typeorm/typeorm/issues/1090#issuecomment-634391487
-      .orUpdate({
-        conflict_target: ['installation', 'growiUri'],
-        overwrite: ['tokenGtoP', 'tokenPtoG', 'supportedCommandsForBroadcastUse', 'supportedCommandsForSingleUse'],
-      })
-      .execute();
-
     // MOCK DATA DELETE THIS GW-6972 7004 ---------------
     // MOCK DATA DELETE THIS GW-6972 7004 ---------------
     /**
     /**
      * this code represents the creation of cache (Relation schema) using request from GROWI
      * this code represents the creation of cache (Relation schema) using request from GROWI
      */
      */
-    await this.relationMockRepository.createQueryBuilder('relation_mock')
+    // Transaction is not considered because it is used infrequently
+    const response = await this.relationMockRepository.createQueryBuilder('relation')
       .insert()
       .insert()
       .values({
       .values({
         installation: order.installation,
         installation: order.installation,
         tokenGtoP: order.tokenGtoP,
         tokenGtoP: order.tokenGtoP,
         tokenPtoG: order.tokenPtoG,
         tokenPtoG: order.tokenPtoG,
         growiUri: order.growiUrl,
         growiUri: order.growiUrl,
-        supportedCommandsForBroadcastUse: req.body.supportedCommandsForBroadcastUse,
-        supportedCommandsForSingleUse: req.body.supportedCommandsForSingleUse,
-        permittedChannelsForEachCommand: {
-          channelsObject: {},
-        },
+        permissionsForBroadcastUseCommands: req.body.permissionsForBroadcastUseCommands,
+        permissionsForSingleUseCommands: req.body.permissionsForSingleUseCommands,
         expiredAtCommands,
         expiredAtCommands,
       })
       })
       // https://github.com/typeorm/typeorm/issues/1090#issuecomment-634391487
       // https://github.com/typeorm/typeorm/issues/1090#issuecomment-634391487
       .orUpdate({
       .orUpdate({
         conflict_target: ['installation', 'growiUri'],
         conflict_target: ['installation', 'growiUri'],
-        overwrite: ['tokenGtoP', 'tokenPtoG', 'supportedCommandsForBroadcastUse', 'supportedCommandsForSingleUse'],
+        overwrite: ['tokenGtoP', 'tokenPtoG', 'permissionsForBroadcastUseCommands', 'permissionsForSingleUseCommands'],
       })
       })
       .execute();
       .execute();
     // MOCK DATA DELETE THIS GW-6972 7004 ---------------
     // MOCK DATA DELETE THIS GW-6972 7004 ---------------
 
 
     // Find the generated relation
     // Find the generated relation
-    const generatedRelation = await this.relationRepository.findOne({ id: response.identifiers[0].id });
+    const generatedRelationMock = await this.relationMockRepository.findOne({ id: response.identifiers[0].id });
 
 
-    return res.send({ relation: generatedRelation, slackBotToken: token });
+    return res.send({ relation: generatedRelationMock, slackBotToken: token });
   }
   }
 
 
   injectGrowiUri(req: GrowiReq, growiUri: string): void {
   injectGrowiUri(req: GrowiReq, growiUri: string): void {
@@ -298,7 +274,7 @@ export class GrowiToSlackCtrl {
     const tokenGtoP = tokenGtoPs[0];
     const tokenGtoP = tokenGtoPs[0];
 
 
     // retrieve relation with Installation
     // retrieve relation with Installation
-    const relation = await this.relationRepository.createQueryBuilder('relation')
+    const relation = await this.relationMockRepository.createQueryBuilder('relation')
       .where('tokenGtoP = :token', { token: tokenGtoP })
       .where('tokenGtoP = :token', { token: tokenGtoP })
       .leftJoinAndSelect('relation.installation', 'installation')
       .leftJoinAndSelect('relation.installation', 'installation')
       .getOne();
       .getOne();

+ 9 - 8
packages/slackbot-proxy/src/controllers/slack.ts

@@ -13,7 +13,8 @@ import {
 import { Relation } from '~/entities/relation';
 import { Relation } from '~/entities/relation';
 import { SlackOauthReq } from '~/interfaces/slack-to-growi/slack-oauth-req';
 import { SlackOauthReq } from '~/interfaces/slack-to-growi/slack-oauth-req';
 import { InstallationRepository } from '~/repositories/installation';
 import { InstallationRepository } from '~/repositories/installation';
-import { RelationRepository } from '~/repositories/relation';
+import { RelationMock } from '~/entities/relation-mock';
+import { RelationMockRepository } from '~/repositories/relation-mock';
 import { OrderRepository } from '~/repositories/order';
 import { OrderRepository } from '~/repositories/order';
 import { AddSigningSecretToReq } from '~/middlewares/slack-to-growi/add-signing-secret-to-req';
 import { AddSigningSecretToReq } from '~/middlewares/slack-to-growi/add-signing-secret-to-req';
 import { AuthorizeCommandMiddleware, AuthorizeInteractionMiddleware } from '~/middlewares/slack-to-growi/authorizer';
 import { AuthorizeCommandMiddleware, AuthorizeInteractionMiddleware } from '~/middlewares/slack-to-growi/authorizer';
@@ -40,7 +41,7 @@ export class SlackCtrl {
   installationRepository: InstallationRepository;
   installationRepository: InstallationRepository;
 
 
   @Inject()
   @Inject()
-  relationRepository: RelationRepository;
+  relationMockRepository: RelationMockRepository;
 
 
   @Inject()
   @Inject()
   orderRepository: OrderRepository;
   orderRepository: OrderRepository;
@@ -64,13 +65,13 @@ export class SlackCtrl {
    * @param body
    * @param body
    * @returns
    * @returns
    */
    */
-  private async sendCommand(growiCommand: GrowiCommand, relations: Relation[], body: any) {
+  private async sendCommand(growiCommand: GrowiCommand, relations: RelationMock[], body: any) {
     if (relations.length === 0) {
     if (relations.length === 0) {
       throw new Error('relations must be set');
       throw new Error('relations must be set');
     }
     }
     const botToken = relations[0].installation?.data.bot?.token; // relations[0] should be exist
     const botToken = relations[0].installation?.data.bot?.token; // relations[0] should be exist
 
 
-    const promises = relations.map((relation: Relation) => {
+    const promises = relations.map((relation: RelationMock) => {
       // generate API URL
       // generate API URL
       const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
       const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
       return axios.post(url.toString(), {
       return axios.post(url.toString(), {
@@ -135,7 +136,7 @@ export class SlackCtrl {
     const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
     const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
     const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
     const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
-    const relations = await this.relationRepository.createQueryBuilder('relation')
+    const relations = await this.relationMockRepository.createQueryBuilder('relation')
       .where('relation.installationId = :id', { id: installation?.id })
       .where('relation.installationId = :id', { id: installation?.id })
       .leftJoinAndSelect('relation.installation', 'installation')
       .leftJoinAndSelect('relation.installation', 'installation')
       .getMany();
       .getMany();
@@ -165,7 +166,7 @@ export class SlackCtrl {
 
 
     const baseDate = new Date();
     const baseDate = new Date();
 
 
-    const relationsForSingleUse:Relation[] = [];
+    const relationsForSingleUse:RelationMock[] = [];
     await Promise.all(relations.map(async(relation) => {
     await Promise.all(relations.map(async(relation) => {
       const isSupported = await this.relationsService.isSupportedGrowiCommandForSingleUse(relation, growiCommand.growiCommandType, baseDate);
       const isSupported = await this.relationsService.isSupportedGrowiCommandForSingleUse(relation, growiCommand.growiCommandType, baseDate);
       if (isSupported) {
       if (isSupported) {
@@ -181,7 +182,7 @@ export class SlackCtrl {
       return this.selectGrowiService.process(growiCommand, authorizeResult, body);
       return this.selectGrowiService.process(growiCommand, authorizeResult, body);
     }
     }
 
 
-    const relationsForBroadcastUse:Relation[] = [];
+    const relationsForBroadcastUse:RelationMock[] = [];
     await Promise.all(relations.map(async(relation) => {
     await Promise.all(relations.map(async(relation) => {
       const isSupported = await this.relationsService.isSupportedGrowiCommandForBroadcastUse(relation, growiCommand.growiCommandType, baseDate);
       const isSupported = await this.relationsService.isSupportedGrowiCommandForBroadcastUse(relation, growiCommand.growiCommandType, baseDate);
       if (isSupported) {
       if (isSupported) {
@@ -270,7 +271,7 @@ export class SlackCtrl {
     /*
     /*
     * forward to GROWI server
     * forward to GROWI server
     */
     */
-    const relation = await this.relationRepository.findOne({ installation, growiUri: req.growiUri });
+    const relation = await this.relationMockRepository.findOne({ installation, growiUri: req.growiUri });
 
 
     if (relation == null) {
     if (relation == null) {
       logger.error('*No relation found.*');
       logger.error('*No relation found.*');

+ 24 - 48
packages/slackbot-proxy/src/services/RelationsService.ts

@@ -2,9 +2,6 @@ import { Inject, Service } from '@tsed/di';
 import axios from 'axios';
 import axios from 'axios';
 import { addHours } from 'date-fns';
 import { addHours } from 'date-fns';
 
 
-import { Relation } from '~/entities/relation';
-import { RelationRepository } from '~/repositories/relation';
-
 import { RelationMock } from '~/entities/relation-mock';
 import { RelationMock } from '~/entities/relation-mock';
 import { RelationMockRepository } from '~/repositories/relation-mock';
 import { RelationMockRepository } from '~/repositories/relation-mock';
 
 
@@ -15,21 +12,10 @@ const logger = loggerFactory('slackbot-proxy:services:RelationsService');
 @Service()
 @Service()
 export class RelationsService {
 export class RelationsService {
 
 
-  @Inject()
-  relationRepository: RelationRepository;
-
   @Inject()
   @Inject()
   relationMockRepository: RelationMockRepository;
   relationMockRepository: RelationMockRepository;
 
 
-  // MOCK DATA DELETE THIS METHOD GW-6972
-  async getMockFromRelation(relation: Relation): Promise<RelationMock|null> {
-    const tokenGtoP = relation.tokenGtoP;
-    const relationMock = await this.relationMockRepository.findOne({ where: [{ tokenGtoP }] });
-
-    return relationMock || null;
-  }
-
-  async getSupportedGrowiCommands(relation:Relation):Promise<any> {
+  async getSupportedGrowiCommands(relation:RelationMock):Promise<any> {
     // generate API URL
     // generate API URL
     const url = new URL('/_api/v3/slack-integration/supported-commands', relation.growiUri);
     const url = new URL('/_api/v3/slack-integration/supported-commands', relation.growiUri);
     return axios.get(url.toString(), {
     return axios.get(url.toString(), {
@@ -39,49 +25,33 @@ export class RelationsService {
     });
     });
   }
   }
 
 
-  async syncSupportedGrowiCommands(relation:Relation): Promise<RelationMock> {
+  async syncSupportedGrowiCommands(relation:RelationMock): Promise<RelationMock> {
     const res = await this.getSupportedGrowiCommands(relation);
     const res = await this.getSupportedGrowiCommands(relation);
-    // const { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse } = res.data;
-    // relation.supportedCommandsForBroadcastUse = supportedCommandsForBroadcastUse;
-    // relation.supportedCommandsForSingleUse = supportedCommandsForSingleUse;
-    // relation.expiredAtCommands = addHours(new Date(), 48);
-
-    // return this.relationRepository.save(relation);
 
 
     // MOCK DATA MODIFY THIS GW-6972 ---------------
     // MOCK DATA MODIFY THIS GW-6972 ---------------
     /**
     /**
      * this code represents the update of cache (Relation schema) using request from GROWI
      * this code represents the update of cache (Relation schema) using request from GROWI
      */
      */
-    const relationMock = await this.getMockFromRelation(relation);
-    const { supportedCommandsForBroadcastUse, supportedCommandsForSingleUse, permittedChannelsForEachCommand } = res.data;
-    if (relationMock !== null) {
-      relationMock.supportedCommandsForBroadcastUse = supportedCommandsForBroadcastUse;
-      relationMock.supportedCommandsForSingleUse = supportedCommandsForSingleUse;
-      relationMock.permittedChannelsForEachCommand = permittedChannelsForEachCommand;
-      relationMock.expiredAtCommands = addHours(new Date(), 48);
-
-      // NOT MOCK DATA MODIFY THIS ORIGINAL OPERATION GW-6972
-      relation.supportedCommandsForBroadcastUse = supportedCommandsForBroadcastUse;
-      relation.supportedCommandsForSingleUse = supportedCommandsForSingleUse;
+    const { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands } = res.data.data;
+    if (relation !== null) {
+      relation.permissionsForBroadcastUseCommands = permissionsForBroadcastUseCommands;
+      relation.permissionsForSingleUseCommands = permissionsForSingleUseCommands;
       relation.expiredAtCommands = addHours(new Date(), 48);
       relation.expiredAtCommands = addHours(new Date(), 48);
-      this.relationRepository.save(relation);
-
-      return this.relationMockRepository.save(relationMock);
+      return this.relationMockRepository.save(relation);
     }
     }
-    throw Error('No relation mock exists.');
+    throw Error('No relation exists.');
     // MOCK DATA MODIFY THIS GW-6972 ---------------
     // MOCK DATA MODIFY THIS GW-6972 ---------------
   }
   }
 
 
   // MODIFY THIS METHOD USING ORIGINAL RELATION MODEL GW-6972
   // MODIFY THIS METHOD USING ORIGINAL RELATION MODEL GW-6972
-  async syncRelation(relation:Relation, baseDate:Date):Promise<RelationMock|null> {
-    const relationMock = await this.getMockFromRelation(relation);
-    if (relationMock == null) return null;
+  async syncRelation(relation:RelationMock, baseDate:Date):Promise<RelationMock|null> {
+    if (relation == null) return null;
 
 
-    const distanceMillisecondsToExpiredAt = relationMock.getDistanceInMillisecondsToExpiredAt(baseDate);
+    const distanceMillisecondsToExpiredAt = relation.getDistanceInMillisecondsToExpiredAt(baseDate);
 
 
     if (distanceMillisecondsToExpiredAt < 0) {
     if (distanceMillisecondsToExpiredAt < 0) {
       try {
       try {
-        return await this.syncSupportedGrowiCommands(relationMock);
+        return await this.syncSupportedGrowiCommands(relation);
       }
       }
       catch (err) {
       catch (err) {
         logger.error(err);
         logger.error(err);
@@ -92,30 +62,36 @@ export class RelationsService {
     // 24 hours
     // 24 hours
     if (distanceMillisecondsToExpiredAt < 24 * 60 * 60 * 1000) {
     if (distanceMillisecondsToExpiredAt < 24 * 60 * 60 * 1000) {
       try {
       try {
-        this.syncSupportedGrowiCommands(relationMock);
+        this.syncSupportedGrowiCommands(relation);
       }
       }
       catch (err) {
       catch (err) {
         logger.error(err);
         logger.error(err);
       }
       }
     }
     }
 
 
-    return relationMock;
+    return relation;
   }
   }
 
 
-  async isSupportedGrowiCommandForSingleUse(relation:Relation, growiCommandType:string, baseDate:Date):Promise<boolean> {
+  async isSupportedGrowiCommandForSingleUse(relation:RelationMock, growiCommandType:string, baseDate:Date):Promise<boolean> {
     const syncedRelation = await this.syncRelation(relation, baseDate);
     const syncedRelation = await this.syncRelation(relation, baseDate);
     if (syncedRelation == null) {
     if (syncedRelation == null) {
       return false;
       return false;
     }
     }
-    return relation.supportedCommandsForSingleUse.includes(growiCommandType);
+    // MOCK DATA THIS CODE SHOULD BE IMPLEMENTED IN GW-7017
+    // return relationMock.supportedCommandsForSingleUse.includes(growiCommandType);
+    return false;
+    // MOCK DATA THIS CODE SHOULD BE IMPLEMENTED IN GW-7017
   }
   }
 
 
-  async isSupportedGrowiCommandForBroadcastUse(relation:Relation, growiCommandType:string, baseDate:Date):Promise<boolean> {
+  async isSupportedGrowiCommandForBroadcastUse(relation:RelationMock, growiCommandType:string, baseDate:Date):Promise<boolean> {
     const syncedRelation = await this.syncRelation(relation, baseDate);
     const syncedRelation = await this.syncRelation(relation, baseDate);
     if (syncedRelation == null) {
     if (syncedRelation == null) {
       return false;
       return false;
     }
     }
-    return relation.supportedCommandsForBroadcastUse.includes(growiCommandType);
+    // MOCK DATA THIS CODE SHOULD BE IMPLEMENTED IN GW-7017
+    // return relationMock.supportedCommandsForBroadcastUse.includes(growiCommandType);
+    return true;
+    // MOCK DATA THIS CODE SHOULD BE IMPLEMENTED IN GW-7017
   }
   }
 
 
 }
 }

+ 5 - 5
packages/slackbot-proxy/src/services/SelectGrowiService.ts

@@ -5,12 +5,12 @@ import { AuthorizeResult } from '@slack/oauth';
 
 
 import { GrowiCommandProcessor } from '~/interfaces/slack-to-growi/growi-command-processor';
 import { GrowiCommandProcessor } from '~/interfaces/slack-to-growi/growi-command-processor';
 import { Installation } from '~/entities/installation';
 import { Installation } from '~/entities/installation';
-import { Relation } from '~/entities/relation';
-import { RelationRepository } from '~/repositories/relation';
+import { RelationMock } from '~/entities/relation-mock';
+import { RelationMockRepository } from '~/repositories/relation-mock';
 
 
 
 
 export type SelectedGrowiInformation = {
 export type SelectedGrowiInformation = {
-  relation: Relation,
+  relation: RelationMock,
   growiCommand: GrowiCommand,
   growiCommand: GrowiCommand,
   sendCommandBody: any,
   sendCommandBody: any,
 }
 }
@@ -19,7 +19,7 @@ export type SelectedGrowiInformation = {
 export class SelectGrowiService implements GrowiCommandProcessor {
 export class SelectGrowiService implements GrowiCommandProcessor {
 
 
   @Inject()
   @Inject()
-  relationRepository: RelationRepository;
+  relationMockRepository: RelationMockRepository;
 
 
   async process(growiCommand: GrowiCommand, authorizeResult: AuthorizeResult, body: {[key:string]:string } & {growiUrisForSingleUse:string[]}): Promise<void> {
   async process(growiCommand: GrowiCommand, authorizeResult: AuthorizeResult, body: {[key:string]:string } & {growiUrisForSingleUse:string[]}): Promise<void> {
     const { botToken } = authorizeResult;
     const { botToken } = authorizeResult;
@@ -93,7 +93,7 @@ export class SelectGrowiService implements GrowiCommandProcessor {
     // ovverride trigger_id
     // ovverride trigger_id
     sendCommandBody.trigger_id = triggerId;
     sendCommandBody.trigger_id = triggerId;
 
 
-    const relation = await this.relationRepository.createQueryBuilder('relation')
+    const relation = await this.relationMockRepository.createQueryBuilder('relation')
       .where('relation.growiUri =:growiUri', { growiUri })
       .where('relation.growiUri =:growiUri', { growiUri })
       .andWhere('relation.installationId = :id', { id: installation?.id })
       .andWhere('relation.installationId = :id', { id: installation?.id })
       .leftJoinAndSelect('relation.installation', 'installation')
       .leftJoinAndSelect('relation.installation', 'installation')