Skip to content

Commit

Permalink
Merge pull request #128 from HannesOberreiter/beta
Browse files Browse the repository at this point in the history
Beta
  • Loading branch information
HannesOberreiter committed Sep 19, 2023
2 parents 198b3c2 + 3abc3e4 commit 22110c9
Show file tree
Hide file tree
Showing 25 changed files with 458 additions and 379 deletions.
19 changes: 19 additions & 0 deletions db/migrations/20230918081241_alter_payments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
export const up = function (knex) {
return knex.schema.alterTable('payments', (t) => {
t.integer('months').nullable().defaultTo(0);
});
};

/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
export const down = function (knex) {
return knex.schema.alterTable('observations', (t) => {
t.dropColumn('months');
});
};
2 changes: 1 addition & 1 deletion env/ci.env
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ DB_PASSWORD=root
DB_NAME =ci_test
DB_HOSTNAME=127.0.0.1
DB_PORT =3306
DB_POOL_MIN=2
DB_POOL_MIN=0
DB_POOL_MAX=10

# REDIS
Expand Down
2 changes: 1 addition & 1 deletion env/example.env
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ DB_PASSWORD=
DB_NAME =
DB_HOSTNAME=127.0.0.1
DB_PORT =
DB_POOL_MIN=2
DB_POOL_MIN=0
DB_POOL_MAX=10

# REDIS
Expand Down
622 changes: 294 additions & 328 deletions package-lock.json

Large diffs are not rendered by default.

9 changes: 7 additions & 2 deletions src/api/controllers/apiary.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import { Apiary } from '../models/apiary.model.js';
import { HiveLocation } from '../models/hive_location.model.js';
import { Movedate } from '../models/movedate.model.js';
import { limitApiary } from '../utils/premium.util.js';
import Objection from 'objection';

async function isDuplicateApiaryName(
user_id: number,
name: string,
id?: number,
trx: Objection.Transaction = null,
) {
const checkDuplicate = Apiary.query().select('id').findOne({
const checkDuplicate = Apiary.query(trx).select('id').findOne({
user_id,
name,
deleted: false,
Expand Down Expand Up @@ -42,6 +44,7 @@ export default class ApiaryController {
req.session.user.user_id,
body.name,
ids[0],
trx,
)
) {
throw httpErrors.Conflict('name');
Expand Down Expand Up @@ -164,6 +167,8 @@ export default class ApiaryController {
await isDuplicateApiaryName(
req.session.user.user_id,
(req.body as any).name,
null,
trx,
)
) {
throw httpErrors.Conflict('name');
Expand Down Expand Up @@ -200,7 +205,7 @@ export default class ApiaryController {
const restoreDelete = query.restore ? true : false;

const result = await Apiary.transaction(async (trx) => {
const res = await Apiary.query()
const res = await Apiary.query(trx)
.withGraphFetched('hive_count')
.where('user_id', req.session.user.user_id)
.whereIn('id', body.ids);
Expand Down
2 changes: 1 addition & 1 deletion src/api/controllers/charge.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export default class ChargeController {
const restoreDelete = query.restore ? true : false;

const result = await Charge.transaction(async (trx) => {
const res = await Charge.query()
const res = await Charge.query(trx)
.where('user_id', req.session.user.user_id)
.whereIn('id', body.ids);

Expand Down
4 changes: 2 additions & 2 deletions src/api/controllers/company.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,14 +261,14 @@ export default class CompanyController {
delete body.api_change;
}

const res = await company.$query().patchAndFetch({ ...body });
const res = await company.$query(trx).patchAndFetch({ ...body });

if (
api_change ||
(res.api_active && (res.api_key === '' || res.api_key === null))
) {
const apiKey = await randomBytes(25).toString('hex');
await company.$query().patch({
await company.$query(trx).patch({
api_key: apiKey,
});
}
Expand Down
24 changes: 21 additions & 3 deletions src/api/controllers/external.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from '../utils/calendar.util.js';
import { createInvoice } from '../utils/foxyoffice.util.js';
import { SOURCE } from '../../config/constants.config.js';
import { MailService } from '../../services/mail.service.js';

export default class ExternalController {
static async ical(req: FastifyRequest, reply: FastifyReply) {
Expand Down Expand Up @@ -89,15 +90,32 @@ export default class ExternalController {
const event = req.body as Stripe.Event;
const object = event.data.object as Stripe.Checkout.Session;
if (event.type === 'checkout.session.completed') {
const user_id = parseInt(object.client_reference_id);
let user_id: number;
let years = 1;

try {
const reference = JSON.parse(object.client_reference_id);
user_id = reference.user_id;
years = reference.quantity ?? 1;
} catch (e) {
const mailer = MailService.getInstance();
mailer.sendRawMail(
'office@btree.at',
'Failed capture of Stripe Payment',
JSON.stringify(event, null, 2),
);
req.log.error(e);
throw httpErrors.InternalServerError();
}

let amount = 0;
try {
amount = parseFloat(object.amount_total as any) / 100;
} catch (e) {
req.log.error(e);
}
await addPremium(user_id, 12, amount, 'stripe');
createInvoice(object.customer_details.email, amount, 'Stripe');
await addPremium(user_id, 12 * years, amount, 'stripe');
createInvoice(object.customer_details.email, amount, years, 'Stripe');
}
return {};
}
Expand Down
2 changes: 1 addition & 1 deletion src/api/controllers/field_setting.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default class FieldSettingController {
const trx = await FieldSetting.startTransaction();
try {
const settings = JSON.parse(body.settings);
const current = await FieldSetting.query()
const current = await FieldSetting.query(trx)
.first()
.where('bee_id', req.session.user.bee_id);
if (current) {
Expand Down
39 changes: 25 additions & 14 deletions src/api/controllers/hive.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,15 @@ import { Feed } from '../models/feed.model.js';
import { Treatment } from '../models/treatment.model.js';
import { Checkup } from '../models/checkup.model.js';
import { limitHive } from '../utils/premium.util.js';

async function isDuplicateHiveName(user_id: number, name: string, id?: number) {
const checkDuplicate = Hive.query().select('id').findOne({
import Objection from 'objection';

async function isDuplicateHiveName(
user_id: number,
name: string,
id?: number,
trx: Objection.Transaction = null,
) {
const checkDuplicate = Hive.query(trx).select('id').findOne({
user_id,
name,
deleted: false,
Expand Down Expand Up @@ -131,7 +137,9 @@ export default class HiveController {
for (let i = 0; i < repeat; i++) {
const name = repeat > 1 ? body.name + (start + i) : body.name;

if (await isDuplicateHiveName(req.session.user.user_id, name)) {
if (
await isDuplicateHiveName(req.session.user.user_id, name, null, trx)
) {
throw httpErrors.Conflict('name');
}

Expand Down Expand Up @@ -205,11 +213,13 @@ export default class HiveController {
'apiaries.user_id': req.session.user.user_id,
'apiaries.deleted': false,
});
const query_hives = await HiveLocation.query().select('hive_id').where({
apiary_id: id,
hive_deleted: false,
hive_modus: true,
});
const query_hives = await HiveLocation.query(trx)
.select('hive_id')
.where({
apiary_id: id,
hive_deleted: false,
hive_modus: true,
});
hives = query_hives.map((hive) => hive.hive_id);
} else {
await Hive.query(trx).findById(id).throwIfNotFound().where({
Expand All @@ -219,7 +229,7 @@ export default class HiveController {
hives.push(id);
}

const harvest = await Harvest.query()
const harvest = await Harvest.query(trx)
.select('*', Hive.raw('? as kind', ['harvest']))
.withGraphFetched(
'[hive, harvest_apiary, type, creator(identifier), editor(identifier)]',
Expand All @@ -230,7 +240,7 @@ export default class HiveController {
})
.whereRaw('YEAR(date) = ?', year)
.orderBy('date', 'desc');
const feed = await Feed.query()
const feed = await Feed.query(trx)
.select('*', Hive.raw('? as kind', ['feed']))
.withGraphFetched(
'[hive, feed_apiary, type, creator(identifier), editor(identifier)]',
Expand All @@ -241,7 +251,7 @@ export default class HiveController {
})
.whereRaw('YEAR(date) = ?', year)
.orderBy('date', 'desc');
const treatment = await Treatment.query()
const treatment = await Treatment.query(trx)
.select('*', Hive.raw('? as kind', ['treatment']))
.withGraphFetched(
'[hive, treatment_apiary, type, disease, vet, creator(identifier), editor(identifier)]',
Expand All @@ -252,7 +262,7 @@ export default class HiveController {
})
.whereRaw('YEAR(date) = ?', year)
.orderBy('date', 'desc');
const checkup = await Checkup.query()
const checkup = await Checkup.query(trx)
.select('*', Hive.raw('? as kind', ['checkup']))
.withGraphFetched(
'[hive, checkup_apiary, type, creator(identifier), editor(identifier)]',
Expand All @@ -263,7 +273,7 @@ export default class HiveController {
})
.whereRaw('YEAR(date) = ?', year)
.orderBy('date', 'desc');
const movedate = await Movedate.query()
const movedate = await Movedate.query(trx)
.select('*', Hive.raw('? as kind', ['movedate']))
.withGraphFetched(
'[hive, apiary, creator(identifier), editor(identifier)]',
Expand Down Expand Up @@ -297,6 +307,7 @@ export default class HiveController {
req.session.user.user_id,
insert.name,
ids[0],
trx,
)
) {
throw httpErrors.Conflict('name');
Expand Down
2 changes: 1 addition & 1 deletion src/api/controllers/movedate.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export default class MovedateController {
for (let i = 0; i < hive_ids.length; i++) {
const id = hive_ids[i];

await HiveLocation.query()
await HiveLocation.query(trx)
.where({
user_id: req.session.user.user_id,
hive_id: id,
Expand Down
2 changes: 1 addition & 1 deletion src/api/controllers/scale_data.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export default class ScaleDataController {
const currentWeight = parseFloat(q.weight as any);
const checkWeight = Math.abs(lastInsert.weight - currentWeight);
if (checkWeight > 5) {
const user = await User.query()
const user = await User.query(trx)
.leftJoinRelated('company_bee')
.where({
'company_bee.rank': 1,
Expand Down
21 changes: 17 additions & 4 deletions src/api/controllers/service.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import { WizBeeToken } from '../models/wizbee_token.model.js';
import { openAI } from '../../config/environment.config.js';
import { FastifyRequest, FastifyReply } from 'fastify';
import httpErrors from 'http-errors';
import { Observation } from '../models/observation.model.js';
import { raw } from 'objection';

export default class ServiceController {
static async getTemperature(req: FastifyRequest, reply: FastifyReply) {
Expand All @@ -34,6 +32,7 @@ export default class ServiceController {
const order = await paypalCreateOrder(
req.session.user.user_id,
body.amount,
body.quantity,
);
if (order.status !== 'CREATED') {
throw httpErrors.InternalServerError('Could not create order');
Expand All @@ -48,22 +47,35 @@ export default class ServiceController {
throw httpErrors.InternalServerError('Could not capure order');
}
let value = 0;
let years = 1;

const mail = capture.payment_source.paypal.email_address;

try {
value = parseFloat(
capture.purchase_units[0].payments.captures[0].amount.value,
);
} catch (e) {
req.log.error(e);
}

try {
const custom_id = JSON.parse(
capture.purchase_units[0].payments.captures[0].custom_id,
);
years = parseFloat(custom_id.quantity) ?? 1;
} catch (e) {
req.log.error(e);
}

const paid = await addPremium(
req.session.user.user_id,
12,
12 * years,
value,
'paypal',
);

createInvoice(mail, value, 'PayPal');
createInvoice(mail, value, years, 'PayPal');
return { ...capture, paid };
}

Expand All @@ -72,6 +84,7 @@ export default class ServiceController {
const session = await stripeCreateOrder(
req.session.user.user_id,
body.amount,
body.quantity,
);
return session;
}
Expand Down
4 changes: 2 additions & 2 deletions src/api/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export default class UserController {
try {
if ('password' in body) {
try {
await reviewPassword(req.session.user.bee_id, body.password);
await reviewPassword(req.session.user.bee_id, body.password, trx);
} catch (e) {
throw checkMySQLError(e);
}
Expand Down Expand Up @@ -175,7 +175,7 @@ export default class UserController {
const body = req.body as any;
const trx = await User.startTransaction();
try {
await CompanyBee.query()
await CompanyBee.query(trx)
.where('bee_id', req.session.user.bee_id)
.where('user_id', body.saved_company)
.throwIfNotFound();
Expand Down
2 changes: 2 additions & 0 deletions src/api/models/payment.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export class Payment extends BaseModel {
id!: number;
type!: string;
amount!: number;
months!: number;
date!: Date;
user_id!: number;

Expand All @@ -19,6 +20,7 @@ export class Payment extends BaseModel {
id: { type: 'integer' },
type: { type: 'string', minLength: 0, maxLength: 45 },
amount: { type: 'number' },
months: { type: 'integer' },
date: { type: 'string', format: 'date-time' },
user_id: { type: 'integer' }, // Company FK
},
Expand Down
2 changes: 2 additions & 0 deletions src/api/routes/v1/external.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ export default function routes(
{ preHandler: Validator.handleSource },
ExternalController.ical,
);

server.post('/stripe/webhook', {}, ExternalController.stripeWebhook);

server.get(
'/scale/:ident/:api',
{
Expand Down
2 changes: 1 addition & 1 deletion src/api/routes/v1/hive.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { FastifyInstance } from 'fastify';
import { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod';
import HiveController from '../../controllers/hive.controller.js';
import { booleanParamSchema, numberSchema } from '../../utils/zod.util.js';
import { numberSchema } from '../../utils/zod.util.js';

const hiveSchema = z.object({
name: z.string().min(1).max(24).trim(),
Expand Down

0 comments on commit 22110c9

Please sign in to comment.