Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e26e89a
LF-4995 Migration to add market_directory_info permissions
SayakaOno Oct 24, 2025
2c1e1b6
LF-4995 Add POST API skeleton for market directory info
SayakaOno Oct 24, 2025
f4cd6fb
LF-4995 Add validation functions
SayakaOno Oct 27, 2025
093be65
LF-4995 Add email validation function
SayakaOno Oct 27, 2025
05f7dd2
LF-4995 Add shared validation functions
SayakaOno Oct 27, 2025
da19ee7
LF-4995 Move util functions
SayakaOno Oct 28, 2025
9e7783e
LF-4995 Update LiteFarmRequest interface
SayakaOno Oct 28, 2025
a103b03
LF-4995 Add getAddressComponents
SayakaOno Oct 28, 2025
4d977a5
LF-4995 Add isValidAddress function
SayakaOno Oct 28, 2025
183913b
LF-4995 Add isValidAddress function
SayakaOno Oct 28, 2025
f68a0b8
LF-4995 Update marketDirectoryInfo validation middleware
SayakaOno Oct 28, 2025
ad5ad3b
LF-4995 Update addMarketDirectoryInfo method
SayakaOno Oct 28, 2025
f5001c5
LF-4995 Update checkAndTransformMarketDirectoryInfo
SayakaOno Oct 28, 2025
f02ae7f
LF-4995 Update mock factories and tableCleanup
SayakaOno Oct 28, 2025
47773c7
LF-4995 Fix checkAndTransformMarketDirectoryInfo
SayakaOno Oct 28, 2025
627fa6d
LF-4995 Update marketDirectoryInfo properties maxLength in model
SayakaOno Oct 29, 2025
be5ca92
LF-4995 Fix typo in mock factories
SayakaOno Oct 29, 2025
8e62955
LF-4995 Add createUserFarmIds, HeadersParams for tests
SayakaOno Oct 29, 2025
f46d09d
LF-4995 Add tests for 'Post Market Directory Info'
SayakaOno Oct 29, 2025
8737b50
LF-4995 Add permission for get:market_directory_info
SayakaOno Oct 29, 2025
3ded73e
LF-4995 Update social validation
SayakaOno Nov 4, 2025
c720489
LF-4995 Add tests for validateSocialAndExtractUsername
SayakaOno Nov 4, 2025
fb4edc8
LF-4995 Update tsconfig to exclude test files
SayakaOno Nov 4, 2025
8990ace
LF-4995 Move test file
SayakaOno Nov 4, 2025
fb9be43
Revert "LF-4995 Update tsconfig to exclude test files"
SayakaOno Nov 4, 2025
74e1b14
LF-4995 Improve tests
SayakaOno Nov 4, 2025
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 2025 LiteFarm.org
* This file is part of LiteFarm.
*
* LiteFarm is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiteFarm is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details, see <https://www.gnu.org/licenses/>.
*/

/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/

export const up = async function (knex) {
await knex('permissions').insert([
{
permission_id: 179,
name: 'add:market_directory_info',
description: 'add market_directory_info',
},
{
permission_id: 180,
name: 'edit:market_directory_info',
description: 'edit market_directory_info',
},
{
permission_id: 181,
name: 'delete:market_directory_info',
description: 'delete market_directory_info',
},
{
permission_id: 182,
name: 'get:market_directory_info',
description: 'get market_directory_info',
},
]);
await knex('rolePermissions').insert([
{ role_id: 1, permission_id: 179 },
{ role_id: 2, permission_id: 179 },
{ role_id: 5, permission_id: 179 },
{ role_id: 1, permission_id: 180 },
{ role_id: 2, permission_id: 180 },
{ role_id: 5, permission_id: 180 },
{ role_id: 1, permission_id: 181 },
{ role_id: 2, permission_id: 181 },
{ role_id: 5, permission_id: 181 },
{ role_id: 1, permission_id: 182 },
{ role_id: 2, permission_id: 182 },
{ role_id: 5, permission_id: 182 },
]);
};

/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
export const down = function (knex) {
const permissions = [179, 180, 181, 182];
return Promise.all([
knex('rolePermissions').whereIn('permission_id', permissions).del(),
knex('permissions').whereIn('permission_id', permissions).del(),
]);
};
50 changes: 50 additions & 0 deletions packages/api/src/controllers/marketDirectoryInfoController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2025 LiteFarm.org
* This file is part of LiteFarm.
*
* LiteFarm is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiteFarm is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details, see <https://www.gnu.org/licenses/>.
*/

import { Response } from 'express';
import baseController from './baseController.js';
import MarketDirectoryInfoModel from '../models/marketDirectoryInfoModel.js';
import { MarketDirectoryInfoReqBody } from '../middleware/validation/checkMarketDirectoryInfo.js';
import { HttpError, LiteFarmRequest } from '../types.js';

const marketDirectoryInfoController = {
addMarketDirectoryInfo() {
return async (
req: LiteFarmRequest<unknown, unknown, unknown, MarketDirectoryInfoReqBody>,
res: Response,
) => {
const { farm_id } = req.headers;

try {
const result = await baseController.post(
MarketDirectoryInfoModel,
{ ...req.body, farm_id },
req,
);

return res.status(201).send(result);
} catch (error: unknown) {
console.error(error);
const err = error as HttpError;
const status = err.status || err.code || 500;
return res.status(status).json({
error: err.message || err,
});
}
};
},
};

export default marketDirectoryInfoController;
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright 2025 LiteFarm.org
* This file is part of LiteFarm.
*
* LiteFarm is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiteFarm is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details, see <https://www.gnu.org/licenses/>.
*/

import { Response, NextFunction } from 'express';
import { LiteFarmRequest } from '../../types.js';
import { isValidAddress, isValidEmail } from '../../util/validation.js';
import { isValidUrl } from '../../util/url.js';
import { SOCIALS, validateAndExtractUsernameOrUrl } from '../../util/socials.js';
import MarketDirectoryInfoModel from '../../models/marketDirectoryInfoModel.js';

export interface MarketDirectoryInfoReqBody {
farm_name?: string;
logo?: string;
about?: string;
contact_first_name?: string;
contact_last_name?: string;
contact_email?: string;
email?: string;
country_code?: number;
phone_number?: string;
address?: string;
website?: string;
instagram?: string;
facebook?: string;
x?: string;
}

export function checkAndTransformMarketDirectoryInfo() {
return async (
req: LiteFarmRequest<unknown, unknown, unknown, MarketDirectoryInfoReqBody>,
res: Response,
next: NextFunction,
) => {
if (req.method === 'POST') {
// @ts-expect-error: TS doesn't see query() through softDelete HOC; safe at runtime
const record = await MarketDirectoryInfoModel.query()
.where({ farm_id: req.headers.farm_id })
.first();

if (record) {
return res.status(409).send('Market directory info for this farm already exists');
}
}

const { address, website } = req.body;

for (const emailProperty of ['contact_email', 'email'] as const) {
if (req.body[emailProperty] && !isValidEmail(req.body[emailProperty])) {
return res.status(400).send(`Invalid ${emailProperty}`);
}
}

if (address && !(await isValidAddress(address))) {
return res.status(400).send('Invalid address');
}

if (website && !(await isValidUrl(website)) /* TODO: LF-5011 */) {
return res.status(400).send('Invalid website');
}

const invalidSocials = (
await Promise.all(
SOCIALS.filter((social) => req.body[social]?.trim()).map(async (social) => {
const formattedSocial = await validateAndExtractUsernameOrUrl(social, req.body[social]!);

if (formattedSocial) {
req.body[social] = formattedSocial;
return null;
}
return social;
}),
)
).filter((social) => social !== null);

if (invalidSocials.length) {
return res.status(400).send(`Invalid ${invalidSocials.join(', ')}`);
}

next();
};
}
33 changes: 31 additions & 2 deletions packages/api/src/models/marketDirectoryInfoModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/

import baseModel from './baseModel.js';
import { checkAndTrimString } from '../util/util.js';

class MarketDirectoryInfo extends baseModel {
static get tableName() {
Expand All @@ -24,6 +25,34 @@ class MarketDirectoryInfo extends baseModel {
return 'id';
}

static get stringProperties() {
const stringProperties = [];
for (const [key, value] of Object.entries(this.jsonSchema.properties)) {
if (value.type.includes('string')) {
stringProperties.push(key);
}
}
return stringProperties;
}

async $beforeInsert(queryContext) {
await super.$beforeInsert(queryContext);
this.trimStringProperties();
}

async $beforeUpdate(opt, queryContext) {
await super.$beforeUpdate(opt, queryContext);
this.trimStringProperties();
}

trimStringProperties() {
for (const key of this.constructor.stringProperties) {
if (key in this) {
this[key] = checkAndTrimString(this[key]);
}
}
}

// Optional JSON schema. This is not the database schema! Nothing is generated
// based on this. This is only used for validation. Whenever a model instance
// is created it is checked against this schema. http://json-schema.org/.
Expand All @@ -36,15 +65,15 @@ class MarketDirectoryInfo extends baseModel {
farm_id: { type: 'string' },
farm_name: { type: 'string', minLength: 1, maxLength: 255 },
logo: { type: ['string', 'null'], maxLength: 255 },
about: { type: ['string', 'null'] },
about: { type: ['string', 'null'], maxLength: 3000 },
contact_first_name: { type: 'string', minLength: 1, maxLength: 255 },
contact_last_name: { type: ['string', 'null'], maxLength: 255 },
contact_email: { type: 'string', minLength: 1, maxLength: 255 },
email: { type: ['string', 'null'], maxLength: 255 },
country_code: { type: ['integer', 'null'], minimum: 1, maximum: 999 },
phone_number: { type: ['string', 'null'], maxLength: 255 },
address: { type: 'string', minLength: 1, maxLength: 255 },
website: { type: ['string', 'null'] },
website: { type: ['string', 'null'], maxLength: 2000 },
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instagram: { type: ['string', 'null'], maxLength: 255 },
facebook: { type: ['string', 'null'], maxLength: 255 },
x: { type: ['string', 'null'], maxLength: 255 },
Expand Down
30 changes: 30 additions & 0 deletions packages/api/src/routes/marketDirectoryInfoRoute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright 2025 LiteFarm.org
* This file is part of LiteFarm.
*
* LiteFarm is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiteFarm is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details, see <https://www.gnu.org/licenses/>.
*/

import express from 'express';
import checkScope from '../middleware/acl/checkScope.js';
import { checkAndTransformMarketDirectoryInfo } from '../middleware/validation/checkMarketDirectoryInfo.js';
import MarketDirectoryInfoController from '../controllers/marketDirectoryInfoController.js';

const router = express.Router();

router.post(
'/',
checkScope(['add:market_directory_info']),
checkAndTransformMarketDirectoryInfo(),
MarketDirectoryInfoController.addMarketDirectoryInfo(),
);

export default router;
4 changes: 3 additions & 1 deletion packages/api/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ import farmAddonRoute from './routes/farmAddonRoute.js';
import weatherRoute from './routes/weatherRoute.js';
import irrigationPrescriptionRoute from './routes/irrigationPrescriptionRoute.js';
import irrigationPrescriptionRequestRoute from './routes/irrigationPrescriptionRequestRoute.js';
import marketDirectoryInfoRoute from './routes/marketDirectoryInfoRoute.js';

// register API
const router = promiseRouter();
Expand Down Expand Up @@ -343,7 +344,8 @@ app
.use('/farm_addon', farmAddonRoute)
.use('/weather', weatherRoute)
.use('/irrigation_prescriptions', irrigationPrescriptionRoute)
.use('/irrigation_prescription_request', irrigationPrescriptionRequestRoute);
.use('/irrigation_prescription_request', irrigationPrescriptionRequestRoute)
.use('/market_directory_info', marketDirectoryInfoRoute);

// Allow a 1MB limit on sensors to match incoming Ensemble data
app.use('/sensor', express.json({ limit: '1MB' }), rejectBodyInGetAndDelete, sensorRoute);
Expand Down
8 changes: 6 additions & 2 deletions packages/api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ export interface HttpError extends Error {
}

// TODO: Remove farm_id conditional and cast this in a checkScope() that takes the function and casts this to req
export interface LiteFarmRequest<QueryParams = unknown, RouteParams = unknown>
extends Request<RouteParams, unknown, unknown, QueryParams> {
export interface LiteFarmRequest<
QueryParams = unknown,
RouteParams = unknown,
ResBody = unknown,
ReqBody = unknown,
> extends Request<RouteParams, ResBody, ReqBody, QueryParams> {
headers: Request['headers'] & {
farm_id?: string;
};
Expand Down
31 changes: 31 additions & 0 deletions packages/api/src/util/googleMaps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright 2025 LiteFarm.org
* This file is part of LiteFarm.
*
* LiteFarm is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiteFarm is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details, see <https://www.gnu.org/licenses/>.
*/

import { Client } from '@googlemaps/google-maps-services-js';
const googleClient = new Client({});

export async function getAddressComponents(address: string) {
try {
const response = await googleClient.geocode({
params: {
address,
key: process.env.GOOGLE_API_KEY!,
},
});
return response.data.results[0]?.address_components;
} catch (error) {
console.error(error);
}
}
Loading