Skip to content
This repository was archived by the owner on Nov 6, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .vscode/settings.json

This file was deleted.

5 changes: 3 additions & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@
"migrateFields": "node_modules/.bin/ts-node src/commands/migrateFields.ts",
"migrateClientPortalUsers": "node_modules/.bin/ts-node src/commands/migrateClientPortalUsers.ts",
"migrateUserMovements": "node_modules/.bin/ts-node src/commands/migrateUserMovements.ts",
"updateUserNames": "node_modules/.bin/ts-node src/commands/updateUserNames.ts"
"updateUserNames": "node_modules/.bin/ts-node src/commands/updateUserNames.ts",
"migratePayment": "node_modules/.bin/ts-node src/commands/migratePayment.ts"
},
"dependencies": {
"agentkeepalive": "^4.3.0",
Expand Down Expand Up @@ -61,7 +62,7 @@
"ts-node": "10.9.1",
"validator": "^9.0.0",
"xlsx-populate": "^1.20.1",
"jimp":"^0.22.10",
"jimp": "^0.22.10",
"tus-js-client": "^3.1.1"
}
}
51 changes: 51 additions & 0 deletions packages/core/src/commands/migratePayment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import * as dotenv from 'dotenv';

dotenv.config();
import { Collection, Db, MongoClient } from 'mongodb';

const { MONGO_URL } = process.env;

if (!MONGO_URL) {
throw new Error(`Environment variable MONGO_URL not set.`);
}

const client = new MongoClient(MONGO_URL);

let db: Db;

let DealCollections: Collection<any>;
const command = async () => {
await client.connect();
db = client.db() as Db;
DealCollections = db.collection('deals');

const deals = await DealCollections.find({}).toArray();

// tslint:disable-next-line:no-shadowed-variable
for (const deal of deals) {
const { _id, ...item } = deal;
const paymentsData = item.paymentsData;

// tslint:disable-next-line:prefer-const
let updatedPaymentsData = { ...paymentsData }; // Create a copy of paymentsData

// tslint:disable-next-line:forin
for (const key in paymentsData) {
updatedPaymentsData[key] = {
...paymentsData[key], // Copy the existing properties of
title: key, // Add the title property with the key as its value
type: key
};
}

await DealCollections.updateOne(
{ _id },
{ $set: { paymentsData: updatedPaymentsData } }
);
}

console.log(`Process finished at: ${new Date()}`);
process.exit();
};

command();
4 changes: 3 additions & 1 deletion packages/plugin-cards-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import exporter from './exporter';
import cronjobs from './cronjobs/common';
import dashboards from './dashboards';
import { NOTIFICATION_MODULES } from './constants';
import payment from './payment';

export let mainDb;
export let graphqlPubsub;
Expand Down Expand Up @@ -59,7 +60,8 @@ export default {
permissions,
documents,
dashboards,
notificationModules: NOTIFICATION_MODULES
notificationModules: NOTIFICATION_MODULES,
payment
},

apolloServerContext: async (context, req, res) => {
Expand Down
9 changes: 7 additions & 2 deletions packages/plugin-cards-api/src/connectionResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,14 @@ import { IPipelineTemplateDocument } from './models/definitions/pipelineTemplate
import { createGenerateModels } from '@erxes/api-utils/src/core';
import { ICostModel } from './models/Costs';
import { ICostDocument } from './models/definitions/costs';

import { IPaymentTypeDocument } from './models/definitions/payments';
import { IPaymentTypeModel, loadPaymentTypeClass } from './models/Payments';
export interface IModels {
Boards: IBoardModel;
Pipelines: IPipelineModel;
Stages: IStageModel;
Costs: ICostModel;
PaymentTypes: IPaymentTypeModel;
Deals: IDealModel;
Purchases: IPurchaseModel;
Tasks: ITaskModel;
Expand Down Expand Up @@ -88,7 +90,10 @@ export const loadClasses = (
'expenses',
loadCostClass(models, subdomain)
);

models.PaymentTypes = db.model<IPaymentTypeDocument, IPaymentTypeModel>(
'payment_types',
loadPaymentTypeClass(models, subdomain)
);
models.Pipelines = db.model<IPipelineDocument, IPipelineModel>(
'pipelines',
loadPipelineClass(models, subdomain)
Expand Down
63 changes: 60 additions & 3 deletions packages/plugin-cards-api/src/graphql/resolvers/mutations/deals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
import { IContext } from '../../../connectionResolver';
import { sendProductsMessage } from '../../../messageBroker';
import { graphqlPubsub } from '../../../configs';

import { IPaymentType } from '../../../models/definitions/payments';
interface IDealsEdit extends IDeal {
_id: string;
}
Expand All @@ -24,6 +24,64 @@ const dealMutations = {
/**
* Creates a new deal
*/

async paymentTypes(
_root,
doc: IPaymentType,
{ models, user, subdomain }: IContext
) {
try {
const oldPaymentTypes = await models.PaymentTypes.find({
status: 'active'
}).lean();

let bulkOps: Array<{
updateOne: {
filter: { _id: string };
update: any;
upsert?: boolean;
};
}> = [];

if (doc._id && doc._id === oldPaymentTypes[0]._id) {
bulkOps.push({
updateOne: {
filter: { _id: doc._id },
update: {
erxesAppToken: doc.erxesAppToken,
paymentIds: doc.paymentIds || [],
paymentTypes: doc.paymentTypes,
status: 'active',
createdBy: user._id,
createdAt: new Date()
},
upsert: true
}
});
} else if (doc._id === undefined) {
bulkOps.push({
updateOne: {
filter: { _id: Math.random().toString() },
update: {
erxesAppToken: doc.erxesAppToken,
paymentIds: doc.paymentIds || [],
paymentTypes: doc.paymentTypes,
status: 'active',
createdBy: user._id,
createdAt: new Date()
},
upsert: true
}
});
}
await models.PaymentTypes.bulkWrite(bulkOps);
return await models.PaymentTypes.find({ status: 'active' }).lean();
} catch (error) {
console.error('Error in paymentTypes:', error);
throw error;
}
},

async dealsAdd(
_root,
doc: IDeal & { proccessId: string; aboveItemId: string },
Expand All @@ -48,7 +106,6 @@ const dealMutations = {
{ user, models, subdomain }: IContext
) {
const oldDeal = await models.Deals.getDeal(_id);

if (doc.assignedUserIds) {
const { removedUserIds } = checkUserIds(
oldDeal.assignedUserIds,
Expand Down Expand Up @@ -158,7 +215,7 @@ const dealMutations = {
proccessId,
'deal',
user,
['productsData', 'paymentsData'],
['productsData', 'paymentsData', 'mobileAmounts'],
models.Deals.createDeal
);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ const dealQueries = {
/**
* Deals list
*/
async paymentTypes(_root, _args, { models, subdomain }: IContext) {
return await models.PaymentTypes.find({ status: 'active' }).lean();
},
async deals(
_root,
args: IDealListParams,
Expand Down
30 changes: 27 additions & 3 deletions packages/plugin-cards-api/src/graphql/schema/deal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,21 @@ export const types = ({ contacts, tags }) => `
products: JSON
productsData: JSON
paymentsData: JSON
mobileAmounts: JSON
paymentTypeData: JSON
${commonTypes}
}

type DealTotalCurrency {
amount: Float
name: String
}

type PaymentType {
_id: String
paymentIds: [String]
paymentTypes: [JSON]
erxesAppToken: String
}
type TotalForType {
_id: String
name: String
Expand All @@ -53,14 +60,26 @@ export const types = ({ contacts, tags }) => `
productId : String
quantity: Int
}

input PaymentObjectInput {
_id: String
paymentIds: [String]
paymentTypes: [JSON]
erxesAppToken: String
}
`;

const dealMutationParams = `
paymentsData: JSON,
productsData: JSON,
mobileAmounts: JSON,
paymentTypeData: JSON,
`;
const paymentCommonFields = `
_id: String
erxesAppToken: String
paymentIds: [String]
paymentTypes: [JSON]
`;

const commonQueryParams = `
_ids: [String]
date: ItemDate
Expand Down Expand Up @@ -144,6 +163,9 @@ export const queries = `
${commonQueryParams}
${conformityQueryFields}
): [TotalForType]
paymentTypes: [JSON]
paymentTotalCount:JSON
paymentDetail(_id: String!): JSON
`;

export const mutations = `
Expand All @@ -157,4 +179,6 @@ export const mutations = `
dealsCreateProductsData(proccessId: String, dealId: String, docs: JSON): JSON
dealsEditProductData(proccessId: String, dealId: String, dataId: String, doc: JSON): JSON
dealsDeleteProductData(proccessId: String, dealId: String, dataId: String): JSON
paymentTypes(${paymentCommonFields}) : PaymentType

`;
67 changes: 67 additions & 0 deletions packages/plugin-cards-api/src/models/Payments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Model } from 'mongoose';
import { IModels } from '../connectionResolver';
import {
IPaymentType,
IPaymentTypeDocument,
paymentTypeSchema
} from './definitions/payments';

export interface IPaymentTypeModel extends Model<IPaymentTypeDocument> {
getPaymentType(_id: string): Promise<IPaymentTypeDocument>;
createPaymentType(user, doc: IPaymentType): Promise<IPaymentTypeDocument>;
updatePaymentType(
_id: string,
doc: IPaymentType
): Promise<IPaymentTypeDocument>;
removePaymentType(_id: string): void;
}

export const loadPaymentTypeClass = (models: IModels, subdomain: string) => {
class PaymentType {
public static async createPaymentType(user, doc: IPaymentType) {
try {
return models.PaymentTypes.create({
...doc,
userId: user._id
});
} catch (e) {
throw new Error(
`Can not create POS integration. Error message: ${e.message}`
);
}
}

public static async getPaymentType(_id: string) {
// tslint:disable-next-line:no-shadowed-variable
const PaymentType = await models.PaymentTypes.findOne({ _id });

if (!PaymentType) {
throw new Error('PaymentType not found');
}
return PaymentType;
}

public static async updatePaymentType(_id: string, doc: IPaymentType) {
await models.PaymentTypes.updateOne(
{ _id },
{ $set: doc },
{ runValidators: true }
);

return models.PaymentTypes.findOne({ _id });
}

public static async removePaymentType(_id: string) {
const data = await models.PaymentTypes.getPaymentType(_id);

if (!data) {
throw new Error(`not found with id ${_id}`);
}
return models.PaymentTypes.remove({ _id });
}
}

paymentTypeSchema.loadClass(PaymentType);

return paymentTypeSchema;
};
17 changes: 15 additions & 2 deletions packages/plugin-cards-api/src/models/definitions/deals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,20 @@ interface IPaymentsData {
[key: string]: {
currency?: string;
amount?: number;
type?: string;
title?: string;
icon?: string;
config?: string;
};
}

export interface IMobileAmounts {
_id?: string;
amount: number;
}
export interface IDeal extends IItemCommonFields {
productsData?: IProductData[];
paymentsData?: IPaymentsData[];
mobileAmounts?: IMobileAmounts[];
}

export interface IDealDocument extends IDeal, Document {
Expand Down Expand Up @@ -72,5 +80,10 @@ export const dealSchema = new Schema({
...commonItemFieldsSchema,

productsData: field({ type: [productDataSchema], label: 'Products' }),
paymentsData: field({ type: Object, optional: true, label: 'Payments' })
paymentsData: field({ type: Object, optional: true, label: 'Payments' }),
mobileAmounts: field({
type: Object,
optional: true,
label: 'Mobile Amounts'
})
});
Loading