Skip to content

Commit

Permalink
fix(analytics.gblib): Fixes in database storage.
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigorodriguez committed Jan 27, 2020
1 parent 5d6dacc commit 22f4250
Show file tree
Hide file tree
Showing 12 changed files with 173 additions and 124 deletions.
11 changes: 11 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@
"kind": "build",
"isDefault": true
}
},
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"problemMatcher": [
"$tsc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
8 changes: 1 addition & 7 deletions boot.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,9 @@ const { exec } = require('child_process');

// Displays version of Node JS being used at runtime and others attributes.

console.log(`[GB Runtime] version = ${process.version}`);
console.log(`[GB Runtime] env = ${process.env}`);
console.log(`[GB Runtime] NodeJS = ${process.version}`);
console.log(`[GB Runtime] platform = ${process.platform}`);
console.log(`[GB Runtime] release = ${process.release}`);
console.log(`[GB Runtime] argv = ${process.argv}`);
console.log(`[GB Runtime] env.USER = ${process.env.USER}`);
console.log(`[GB Runtime] env.PATH = ${process.env.PATH.split(':').join('\n')}`);
console.log(`[GB Runtime] env.PWD = ${process.env.PWD}`);
console.log(`[GB Runtime] env.HOME = ${process.env.HOME}`);
console.log(`[GB Runtime] debugPort = ${process.debugPort}`);

var now = () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/analytics.gblib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

import { GBDialogStep, GBLog, GBMinInstance, IGBCoreService, IGBPackage } from 'botlib';
import { Sequelize } from 'sequelize-typescript';
import { GuaribasConversation, GuaribasConversationMessage } from './models';

/**
* .gblib Package handler.
Expand All @@ -49,6 +50,8 @@ export class GBAnalyticsPackage implements IGBPackage {
}
public loadPackage(core: IGBCoreService, sequelize: Sequelize): void {
GBLog.verbose(`loadPackage called.`);
core.sequelize.addModels([GuaribasConversation, GuaribasConversationMessage]);

}
public unloadPackage(core: IGBCoreService): void {
GBLog.verbose(`unloadPackage called.`);
Expand Down
81 changes: 40 additions & 41 deletions packages/analytics.gblib/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,94 +58,93 @@ import { GuaribasChannel, GuaribasInstance } from '../../core.gbapp/models/GBMod
import { GuaribasSubject } from '../../kb.gbapp/models';
import { GuaribasUser } from '../../security.gblib/models';


/**
* A single message in a conversation.
* A conversation that groups many messages.
*/
@Table
export class GuaribasConversationMessage extends Model<GuaribasConversationMessage> {
export class GuaribasConversation extends Model<GuaribasConversation> {

@PrimaryKey
@AutoIncrement
@Column
public conversationMessageId: number;
public conversationId: number;

@ForeignKey(() => GuaribasSubject)
@Column
public subjectId: number;
public startSubjectId: number;

@Column(DataType.TEXT)
public content: string;
@BelongsTo(() => GuaribasSubject)
public startSubject: GuaribasSubject;

@ForeignKey(() => GuaribasChannel)
@Column
@CreatedAt
public createdAt: Date;
public channelId: string;

@Column
@UpdatedAt
public updatedAt: Date;
@Column public rateDate: Date;

//tslint:disable-next-line:no-use-before-declare
@ForeignKey(() => GuaribasConversation)
@Column(DataType.FLOAT)
@Column
public conversationId: number;

//tslint:disable-next-line:no-use-before-declare
@BelongsTo(() => GuaribasConversation)
public conversation: GuaribasConversation;
public rate: number;

@ForeignKey(() => GuaribasInstance)
@Column
public instanceId: number;
@CreatedAt
public createdAt: Date;

@Column public text: string;

@ForeignKey(() => GuaribasUser)
@Column
public userId: number;
public startedByUserId: number;

@BelongsTo(() => GuaribasUser)
public user: GuaribasUser;
public startedBy: GuaribasUser;
}


/**
* A conversation that groups many messages.
* A single message in a conversation.
*/
@Table
export class GuaribasConversation extends Model<GuaribasConversation> {
export class GuaribasConversationMessage extends Model<GuaribasConversationMessage> {

@PrimaryKey
@AutoIncrement
@Column
public conversationId: number;
public conversationMessageId: number;

@ForeignKey(() => GuaribasSubject)
@Column
public startSubjectId: number;
public subjectId: number;

@BelongsTo(() => GuaribasSubject)
public startSubject: GuaribasSubject;
@Column(DataType.TEXT)
public content: string;

@ForeignKey(() => GuaribasChannel)
@Column
public channelId: string;

@Column public rateDate: Date;
@CreatedAt
public createdAt: Date;

@Column(DataType.FLOAT)
@Column
public rate: number;
@UpdatedAt
public updatedAt: Date;

//tslint:disable-next-line:no-use-before-declare
@ForeignKey(() => GuaribasConversation)
@Column
@CreatedAt
public createdAt: Date;
public conversationId: number;

@Column public text: string;
//tslint:disable-next-line:no-use-before-declare
@BelongsTo(() => GuaribasConversation)
public conversation: GuaribasConversation;

@HasMany(() => GuaribasConversationMessage)
public conversationMessage: GuaribasConversationMessage[];
@ForeignKey(() => GuaribasInstance)
@Column
public instanceId: number;

@ForeignKey(() => GuaribasUser)
@Column
public startedByUserId: number;
public userId: number;

@BelongsTo(() => GuaribasUser)
public startedBy: GuaribasUser;
public user: GuaribasUser;
}
37 changes: 28 additions & 9 deletions packages/analytics.gblib/services/AnalyticsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,41 @@ export class AnalyticsService {
public async createConversation(
user: GuaribasUser
): Promise<GuaribasConversation> {
const conversation = new GuaribasConversation();
conversation.startedBy = user;
conversation.startedByUserId = user.userId;
const conversation = new GuaribasConversation();
conversation.startedBy = user;
conversation.startedByUserId = user.userId;

return await conversation.save();
return await conversation.save();
}

public async updateConversationRate(
instanceId: number,
conversationId: number,
rate: number
): Promise<GuaribasConversation> {
const options = { where: {} };
// TODO: Filter by instanceId: instanceId
options.where = { conversationId: conversationId };
const item = await GuaribasConversation.findOne(options);
item.rate = rate;
item.rateDate = new Date();
return item.save();
}


public async createMessage(
instanceId: number,
conversation: GuaribasConversation,
user: GuaribasUser,
content: string
): Promise<GuaribasConversationMessage> {
const message = GuaribasConversationMessage.build();
message.conversation = conversation;
message.user = user;
message.content = content;
return await message.save();

const message = GuaribasConversationMessage.build();
message.content = content;
message.instanceId = instanceId;
message.userId = user.userId;
message.conversationId = conversation.conversationId;

return await message.save();
}
}
2 changes: 1 addition & 1 deletion packages/core.gbapp/services/GBCoreService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,11 +382,11 @@ STORAGE_SYNC=true
const sysPackages: IGBPackage[] = [];
[
GBAdminPackage,
GBAnalyticsPackage,
GBCorePackage,
GBSecurityPackage,
GBKBPackage,
GBCustomerSatisfactionPackage,
GBAnalyticsPackage,
GBWhatsappPackage,
GBAzureDeployerPackage,
GBSharePointPackage,
Expand Down
53 changes: 31 additions & 22 deletions packages/core.gbapp/services/GBMinService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,12 @@ import {

import { MicrosoftAppCredentials } from 'botframework-connector';
import { GBServer } from '../../../src/app';
import { GBAnalyticsPackage } from '../../analytics.gblib';
import { GBCorePackage } from '../../core.gbapp';
import { GBCustomerSatisfactionPackage } from '../../customer-satisfaction.gbapp';
import { GBKBPackage } from '../../kb.gbapp';
import { AskDialogArgs } from '../../kb.gbapp/dialogs/AskDialog';
import { GBSecurityPackage } from '../../security.gblib';
import { GBWhatsappPackage } from '../../whatsapp.gblib';
import { Messages } from '../strings';
import { GBAdminPackage } from './../../admin.gbapp/index';
import { GBConfigService } from './GBConfigService';
import { GBDeployer } from './GBDeployer';
import { SecService } from '../../security.gblib/services/SecService';
import { isBreakOrContinueStatement } from 'typescript';
import { AnalyticsService } from '../../analytics.gblib/services/AnalyticsService';

/**
* Minimal service layer for a bot.
Expand Down Expand Up @@ -124,7 +117,7 @@ export class GBMinService {
if (process.env.DISABLE_WEB !== 'true') {
GBServer.globals.server.get('/instances/:botId', (req, res) => {
(async () => {
await this.handleGetInstanceFroClient(req, res);
await this.handleGetInstanceForClient(req, res);
})();
});
}
Expand Down Expand Up @@ -189,7 +182,7 @@ export class GBMinService {
public async mountBot(instance: IGBInstance) {

// Build bot adapter.
const { min, adapter, conversationState } = await this.buildBotAdapter(instance, GBServer.globals.publicAddress, GBServer.globals.sysPackages);
const { min, adapter, conversationState } = await this.buildBotAdapter(instance, GBServer.globals.sysPackages);

if (GBServer.globals.minInstances.length === 0) {
GBServer.globals.minBoot = min;
Expand All @@ -201,7 +194,7 @@ export class GBMinService {
// this.deployer.deployPackage(min, 'packages/default.gbdialog');

// Call the loadBot context.activity for all packages.
this.invokeLoadBot(GBServer.globals.appPackages, GBServer.globals.sysPackages, min, GBServer.globals.server);
this.invokeLoadBot(GBServer.globals.appPackages, GBServer.globals.sysPackages, min);

// Serves individual URL for each bot conversational interface...
const url = `/api/messages/${instance.botId}`;
Expand Down Expand Up @@ -280,7 +273,7 @@ export class GBMinService {
/**
* Returns the instance object to clients requesting bot info.
*/
private async handleGetInstanceFroClient(req: any, res: any) {
private async handleGetInstanceForClient(req: any, res: any) {
let botId = req.params.botId;
if (botId === '[default]' || botId === undefined) {
botId = GBConfigService.get('BOT_ID');
Expand Down Expand Up @@ -365,7 +358,7 @@ export class GBMinService {
}
}

private async buildBotAdapter(instance: any, proxyAddress: string, sysPackages: IGBPackage[]) {
private async buildBotAdapter(instance: any, sysPackages: IGBPackage[]) {
const adapter = new BotFrameworkAdapter({
appId: instance.marketplaceId,
appPassword: instance.marketplacePassword
Expand Down Expand Up @@ -404,11 +397,9 @@ export class GBMinService {
return { min, adapter, conversationState };
}

private invokeLoadBot(appPackages: IGBPackage[], sysPackages: IGBPackage[], min: GBMinInstance, server: any) {
let index = 0;
private invokeLoadBot(appPackages: IGBPackage[], sysPackages: IGBPackage[], min: GBMinInstance) {
sysPackages.forEach(e => {
e.loadBot(min);
index++;
}, this);

appPackages.forEach(p => {
Expand Down Expand Up @@ -456,15 +447,24 @@ export class GBMinService {
user.loaded = true;
user.subjects = [];
user.cb = undefined;
await min.userProfile.set(step.context, user);


if (context.activity.membersAdded !== undefined) {
let sec = new SecService();
const member = context.activity.membersAdded[0];

await sec.ensureUser(instance.instanceId, member.id,
const persistedUser = await sec.ensureUser(instance.instanceId, member.id,
min.botId, member.id, "", "web", member.name, member.id);

const analytics = new AnalyticsService();

user.systemUser = persistedUser;
user.conversation = await analytics.createConversation(persistedUser);

}

await min.userProfile.set(step.context, user);

}

GBLog.info(
Expand Down Expand Up @@ -534,7 +534,17 @@ export class GBMinService {
}

private async processMessageActivity(context, min: GBMinInstance, step: GBDialogStep) {
// Direct script invoking by itent name.

// Adds message to the analytics layer.

const analytics = new AnalyticsService();
const user = await min.userProfile.get(context, {});
analytics.createMessage(min.instance.instanceId,
user.conversation, user.systemUser,
context.activity.text);

// Checks for global exit kewywords cancelling any active dialogs.

const globalQuit = (locale, utterance) => {
return utterance.match(Messages[locale].global_quit);
}
Expand All @@ -543,10 +553,10 @@ export class GBMinService {

const simpleLocale = context.activity.locale.substring(0, 2);
const hasBadWord = wash.check(simpleLocale, context.activity.text);

if (hasBadWord) {
await step.beginDialog('/pleaseNoBadWords');
}else if (isVMCall) {
} else if (isVMCall) {
await GBMinService.callVM(context.activity.text, min, step);
} else if (context.activity.text.charAt(0) === '/') {
await step.beginDialog(context.activity.text);
Expand All @@ -562,7 +572,6 @@ export class GBMinService {
await step.beginDialog('/menu', JSON.parse(context.activity.text));
// Otherwise, continue to the active dialog in the stack.
} else {
const user = await min.userProfile.get(context, {});
if (step.activeDialog !== undefined) {
await step.continueDialog();
} else {
Expand Down

0 comments on commit 22f4250

Please sign in to comment.