Skip to content

Commit

Permalink
Manual corrections
Browse files Browse the repository at this point in the history
  • Loading branch information
kennsippell committed Jan 21, 2024
1 parent 5326cc8 commit a22e911
Show file tree
Hide file tree
Showing 20 changed files with 87 additions and 52 deletions.
5 changes: 4 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"extends": "@medic",
"env": {
"node": true
},
"parserOptions": {
"ecmaVersion": 6
},
Expand All @@ -19,7 +22,6 @@
"dot-location": ["error", "property"],
"dot-notation": ["error", { "allowKeywords": true }],
"func-call-spacing": ["error", "never"],
"func-style": ["error", "expression"],
"function-call-argument-newline": ["error", "consistent"],
"function-paren-newline": ["error", "consistent"],
"implicit-arrow-linebreak": ["error", "beside"],
Expand All @@ -37,6 +39,7 @@
"no-useless-rename": "error",
"no-whitespace-before-property": "error",
"node/no-exports-assign": "error",
"max-len": ["error", { "code": 150 }],
"rest-spread-spacing": ["error", "never"],
"semi-spacing": ["error", { "before": false, "after": true }],
"semi-style": ["error", "last"],
Expand Down
13 changes: 11 additions & 2 deletions src/lib/cht-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,18 @@ export class ChtApi {
};

getParentAndSibling = async (parentId: string, contactType: ContactType): Promise<{ parent: any; sibling: any }> => {
const url = `${this.protocolAndHost}/medic/_design/medic/_view/contacts_by_depth?keys=[[%22${parentId}%22,0],[%22${parentId}%22,1]]&include_docs=true`;
const url = `${this.protocolAndHost}/medic/_design/medic/_view/contacts_by_depth`;
console.log('axios.get', url);
const resp = await axios.get(url, this.authorizationOptions());
const resp = await axios.get(url, {
...this.authorizationOptions(),
params: {
keys: JSON.stringify([
[parentId, 0],
[parentId, 1]
]),
include_docs: true,
},
});
const docs = resp.data?.rows?.map((row: any) => row.doc) || [];
const parentType = Config.getParentProperty(contactType).contact_type;
const parent = docs.find((d: any) => d.contact_type === parentType);
Expand Down
2 changes: 0 additions & 2 deletions src/lib/move.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import _ from 'lodash';

import { ContactType } from '../config';
import SessionCache from '../services/session-cache';
import { ChtApi } from '../lib/cht-api';
Expand Down
8 changes: 7 additions & 1 deletion src/lib/remote-place-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,13 @@ function pickFromMapOptimistic(map: RemotePlaceMap, placeName: string, fuzzFunct
return optimisticResult || result || fuzzyResult;
}

function findLocalPlaces(name: string, type: string, sessionCache: SessionCache, options: PlaceResolverOptions | undefined, fuzzFunction: (key: string) => string): RemotePlace | undefined {
function findLocalPlaces(
name: string,
type: string,
sessionCache: SessionCache,
options: PlaceResolverOptions | undefined,
fuzzFunction: (key: string) => string
): RemotePlace | undefined {
let places = sessionCache.getPlaces({ type, nameExact: name });

if (options?.fuzz && !places.length) {
Expand Down
22 changes: 17 additions & 5 deletions src/lib/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ import { Config, ContactType, HierarchyConstraint } from '../config';
import Place from '../services/place';

export default class SearchLib {
public static search = async (contactType: ContactType, formData: any, dataPrefix: string, hierarchyLevel: HierarchyConstraint, chtApi: ChtApi, sessionCache: SessionCache | undefined)
: Promise<RemotePlace[]> => {
public static search = async (
contactType: ContactType,
formData: any,
dataPrefix: string,
hierarchyLevel: HierarchyConstraint,
chtApi: ChtApi,
sessionCache: SessionCache | undefined
) : Promise<RemotePlace[]> => {
const searchString: string = formData[`${dataPrefix}${hierarchyLevel?.property_name}`]?.toLowerCase();

const localResults: Place[] = sessionCache ? await getLocalResults(hierarchyLevel, sessionCache, searchString) : [];
Expand All @@ -29,7 +35,7 @@ export default class SearchLib {

async function getLocalResults(hierarchyLevel: HierarchyConstraint, sessionCache: SessionCache, searchString: string)
: Promise<Place[]> {
if (hierarchyLevel.level == 0) {
if (hierarchyLevel.level === 0) {
return [];
}

Expand All @@ -42,8 +48,14 @@ async function getLocalResults(hierarchyLevel: HierarchyConstraint, sessionCache
return _.sortBy(result, 'name');
}

async function getRemoteResults(searchString: string, hierarchyLevel: HierarchyConstraint, contactType: ContactType, formData: any, chtApi: ChtApi, dataPrefix: string)
: Promise<RemotePlace[]> {
async function getRemoteResults(
searchString: string,
hierarchyLevel: HierarchyConstraint,
contactType: ContactType,
formData: any,
chtApi: ChtApi,
dataPrefix: string
) : Promise<RemotePlace[]> {
const topDownHierarchy = Config.getHierarchyWithReplacement(contactType, 'desc');
const allResults = await RemotePlaceCache.getPlacesWithType(chtApi, hierarchyLevel.contact_type);
let remoteResults = allResults.filter(place => place.name.includes(searchString));
Expand Down
16 changes: 12 additions & 4 deletions src/lib/validation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import _ from 'lodash';

import { Config, ContactProperty } from '../config';

import ValidatorString from './validator-string';
Expand Down Expand Up @@ -100,7 +98,12 @@ export class Validation {
return result;
}

private static validateProperties(obj : any, properties : ContactProperty[], requiredProperties: ContactProperty[], prefix: string) : ValidationError[] {
private static validateProperties(
obj : any,
properties : ContactProperty[],
requiredProperties: ContactProperty[],
prefix: string
) : ValidationError[] {
const invalid: ValidationError[] = [];

for (const property of properties) {
Expand Down Expand Up @@ -150,7 +153,12 @@ export class Validation {
return validator;
}

private static describeInvalidRemotePlace(remotePlace: RemotePlace | undefined, friendlyType: string, searchStr?: string, requiredParent?: string): string {
private static describeInvalidRemotePlace(
remotePlace: RemotePlace | undefined,
friendlyType: string,
searchStr?: string,
requiredParent?: string
): string {
if (!searchStr) {
return `Cannot find ${friendlyType} because the search string is empty`;
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib/validator-skip.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IValidator } from './validation';

export default class ValidatorSkip implements IValidator {
isValid(input: string) : boolean | string {
isValid() : boolean | string {
return true;
}

Expand Down
13 changes: 6 additions & 7 deletions src/routes/add-place.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Config } from '../config';
import { ChtApi } from '../lib/cht-api';
import PlaceFactory from '../services/place-factory';
import SessionCache from '../services/session-cache';
import { PlaceUploadState } from '../services/place';
import RemotePlaceResolver from '../lib/remote-place-resolver';
import { UploadManager } from '../services/upload-manager';
import RemotePlaceCache from '../lib/remote-place-cache';
Expand Down Expand Up @@ -109,7 +108,7 @@ export default async function addPlace(fastify: FastifyInstance) {
resp.header('HX-Redirect', `/`);
});

fastify.post('/place/refresh/:id', async (req, resp) => {
fastify.post('/place/refresh/:id', async (req) => {
const { id } = req.params as any;
const sessionCache: SessionCache = req.sessionCache;
const place = sessionCache.getPlace(id);
Expand All @@ -122,10 +121,10 @@ export default async function addPlace(fastify: FastifyInstance) {
await RemotePlaceResolver.resolveOne(place, sessionCache, chtApi, { fuzz: true });
place.validate();

fastify.uploadManager.refresh(req.sessionCache, PlaceUploadState.PENDING);
fastify.uploadManager.refresh(req.sessionCache);
});

fastify.post('/place/upload/:id', async (req, resp) => {
fastify.post('/place/upload/:id', async (req) => {
const { id } = req.params as any;
const sessionCache: SessionCache = req.sessionCache;
const place = sessionCache.getPlace(id);
Expand All @@ -136,13 +135,13 @@ export default async function addPlace(fastify: FastifyInstance) {
const chtApi = new ChtApi(req.chtSession);
const uploadManager: UploadManager = fastify.uploadManager;
await uploadManager.doUpload([place], chtApi);
fastify.uploadManager.refresh(req.sessionCache, PlaceUploadState.PENDING);
fastify.uploadManager.refresh(req.sessionCache);
});

fastify.post('/place/remove/:id', async (req, resp) => {
fastify.post('/place/remove/:id', async (req) => {
const { id } = req.params as any;
const sessionCache: SessionCache = req.sessionCache;
sessionCache.removePlace(id);
fastify.uploadManager.refresh(req.sessionCache, PlaceUploadState.PENDING);
fastify.uploadManager.refresh(req.sessionCache);
});
}
6 changes: 3 additions & 3 deletions src/routes/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@ export default async function sessionCache(fastify: FastifyInstance) {
return resp.view('src/public/app/view.html', tmplData);
});

fastify.post('/app/remove-all', async (req, resp) => {
fastify.post('/app/remove-all', async (req) => {
const sessionCache: SessionCache = req.sessionCache;
sessionCache.removeAll();
fastify.uploadManager.refresh(req.sessionCache, PlaceUploadState.PENDING);
fastify.uploadManager.refresh(req.sessionCache);
});

fastify.post('/app/refresh-all', async (req, resp) => {
fastify.post('/app/refresh-all', async (req) => {
const sessionCache: SessionCache = req.sessionCache;
const chtApi = new ChtApi(req.chtSession);

Expand Down
3 changes: 0 additions & 3 deletions src/routes/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ export default async function authentication(fastify: FastifyInstance) {
let session;
try {
session = await ChtApi.createSession(authInfo, username, password);
if (!session.sessionToken) {
throw 'login fail'; ``;
}
} catch (e: any) {
return resp.view('src/public/auth/authentication_form.html', {
domains: Config.getDomains,
Expand Down
4 changes: 2 additions & 2 deletions src/routes/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import SessionCache from '../services/session-cache';
import Place from '../services/place';

export default async function files(fastify: FastifyInstance) {
fastify.get('/files/template/:placeType', async (req, resp) => {
fastify.get('/files/template/:placeType', async (req) => {
const params: any = req.params;
const placeType = params.placeType;
const placeTypeConfig = Config.getContactType(placeType);
Expand All @@ -20,7 +20,7 @@ export default async function files(fastify: FastifyInstance) {
return stringify([columns]);
});

fastify.get('/files/credentials', async (req, resp) => {
fastify.get('/files/credentials', async (req) => {
const sessionCache: SessionCache = req.sessionCache;
const places = sessionCache.getPlaces();
const refinedRecords = transform(places, (place: Place) => {
Expand Down
13 changes: 6 additions & 7 deletions src/routes/search.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import _ from 'lodash';
import { FastifyInstance } from 'fastify';

import { Config } from '../config';
Expand All @@ -16,9 +15,9 @@ export default async function place(fastify: FastifyInstance) {
op,
place_id: placeId,
type,
level,
prefix: dataPrefix
} = queryParams;
const level = parseInt(queryParams.level);

const data: any = req.body;

Expand All @@ -30,7 +29,7 @@ export default async function place(fastify: FastifyInstance) {
}

const chtApi = new ChtApi(req.chtSession);
const hierarchyLevel = Config.getHierarchyWithReplacement(contactType).find(hierarchy => hierarchy.level == level);
const hierarchyLevel = Config.getHierarchyWithReplacement(contactType).find(hierarchy => hierarchy.level === level);
if (!hierarchyLevel) {
throw Error(`not hierarchy constraint at ${level}`);
}
Expand All @@ -48,14 +47,14 @@ export default async function place(fastify: FastifyInstance) {
// when we select a place from search results
fastify.post('/search/select', async (req, resp) => {
const data: any = req.body;
const params: any = req.query;
const queryParams: any = req.query;
const {
op = 'new',
place_id: placeId,
result_name: resultName,
level,
prefix: dataPrefix,
} = params;
} = queryParams;
const level = parseInt(queryParams.level);

const sessionCache: SessionCache = req.sessionCache;
const place = sessionCache.getPlace(placeId);
Expand All @@ -65,7 +64,7 @@ export default async function place(fastify: FastifyInstance) {

const contactType = Config.getContactType(data.place_type);
const moveModel = moveViewModel(contactType);
const hierarchyLevel = Config.getHierarchyWithReplacement(contactType).find(hierarchy => hierarchy.level == level);
const hierarchyLevel = Config.getHierarchyWithReplacement(contactType).find(hierarchy => hierarchy.level === level);
if (!hierarchyLevel) {
throw Error(`not hierarchy constraint at ${level}`);
}
Expand Down
2 changes: 0 additions & 2 deletions src/services/place-factory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import _ from 'lodash';
import { once } from 'events';
import { parse } from 'csv';

import { ChtApi } from '../lib/cht-api';
Expand Down
2 changes: 0 additions & 2 deletions src/services/session-cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import _ from 'lodash';

import Place, { PlaceUploadState } from './place';
import { ChtSession } from '../lib/cht-api';

Expand Down
2 changes: 1 addition & 1 deletion src/services/upload.new.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class UploadNewPlace implements Uploader {
this.chtApi = chtApi;
}

handleContact = async function (payload: PlacePayload): Promise<string | undefined> {
handleContact = async function (): Promise<string | undefined> {
return;
};

Expand Down
2 changes: 1 addition & 1 deletion src/types/fastify/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FastifyInstance } from 'fastify';
import { ChtSession } from '../../lib/cht-api';
import SessionCache from '../../services/session-cache';
import { UploadManager } from '../../services/upload-manager';

declare module 'fastify' {
interface FastifyInstance {
Expand Down
4 changes: 2 additions & 2 deletions test/lib/search.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { expect } from 'chai';
import sinon from 'sinon';

import { ChtApi, RemotePlace } from '../../src/lib/cht-api';
import { RemotePlace } from '../../src/lib/cht-api';
import RemotePlaceCache from '../../src/lib/remote-place-cache';
import SearchLib from '../../src/lib/search';
import { mockPlace, mockSimpleContactType, mockValidContactType } from '../mocks';
import { mockValidContactType } from '../mocks';
import SessionCache from '../../src/services/session-cache';
import { Config } from '../../src/config';

Expand Down
2 changes: 1 addition & 1 deletion test/lib/validation.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect } from 'chai';

import { Validation } from '../../src/lib/validation';
import { mockSimpleContactType, mockPlace, expectInvalidProperties } from '../mocks';
import { mockSimpleContactType, mockPlace } from '../mocks';

type Scenario = {
type: string;
Expand Down
16 changes: 12 additions & 4 deletions test/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ export const mockChtApi: ChtApi = (first: RemotePlace[] = [], second: RemotePlac
getPlacesWithType: Sinon.stub().resolves(first).onSecondCall().resolves(second),
});

export const mockSimpleContactType = (propertyType = 'string', propertyValidator: string | string[] | undefined, errorDescription?: string) : ContactType => {
export const mockSimpleContactType = (
propertyType,
propertyValidator: string | string[] | undefined,
errorDescription?: string
) : ContactType => {
const mockedProperty = mockProperty(propertyType, propertyValidator);
mockedProperty.errorDescription = errorDescription;
return {
Expand All @@ -59,7 +63,7 @@ export const mockSimpleContactType = (propertyType = 'string', propertyValidator
};
};

export const mockValidContactType = (propertyType = 'string', propertyValidator: string | string[] | undefined) : ContactType => ({
export const mockValidContactType = (propertyType, propertyValidator: string | string[] | undefined) : ContactType => ({
name: 'contacttype-name',
friendly: 'friendly',
contact_type: 'contact-type',
Expand Down Expand Up @@ -94,7 +98,7 @@ export const mockParentPlace = (parentPlaceType: ContactType, parentName: string
return place;
};

export const mockProperty = (type = 'string', parameter: string | string[] | undefined, property_name: string = 'prop'): ContactProperty => ({
export const mockProperty = (type, parameter: string | string[] | undefined, property_name: string = 'prop'): ContactProperty => ({
friendly_name: 'csv',
property_name,
type,
Expand All @@ -112,7 +116,11 @@ export const mockChtSession = () : ChtSession => ({
username: 'username',
});

export function expectInvalidProperties(validationErrors: { [key: string]: string } | undefined, expectedProperties: string[], expectedError?: string): void {
export function expectInvalidProperties(
validationErrors: { [key: string]: string } | undefined,
expectedProperties: string[],
expectedError?: string
): void {
expect(Object.keys(validationErrors as any)).to.deep.eq(expectedProperties);

if (expectedError) {
Expand Down
Loading

0 comments on commit a22e911

Please sign in to comment.