Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stashing for the night -- new direction client side sorting #485

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
8 changes: 8 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ module.exports = {
],
"react/display-name": ["off", { ignoreTranspilerName: true }],
"sort-imports": "error",
"max-len": ["warn", {
code: 100,
ignoreComments: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
tabWidth: 4,
}],

},
settings: {
react: {
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/colors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const colors: Record<string, string> = {
greyDark: "#3c3c3c",
greyMedium: "#707070",
greyLight: "#A2A2A2",
lavendar: "#9F6CBA",
lavender: "#9F6CBA",
orangeDark: "#CE5A30",
orangePrimary: "#F05A28",
orangeSecondary: "#DB5427",
Expand Down
2 changes: 1 addition & 1 deletion packages/native/src/App.styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const colors = {
greyDark: "#3c3c3c",
greyMedium: "#707070",
greyLight: "#A2A2A2",
lavendar: "#9F6CBA",
lavender: "#9F6CBA",
orangeDark: "#CE5A30",
orangePrimary: "#F05A28",
orangeSecondary: "#DB5427",
Expand Down
2 changes: 1 addition & 1 deletion packages/native/src/components/Categories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const categories: Record<TCategoryName, any> = {
],
},
JobTraining: {
color: "lavendar",
color: "lavender",
mainCategory: {
text: "Job Training",
query: "CATEGORY-jobTraining",
Expand Down
2 changes: 1 addition & 1 deletion packages/native/src/components/HomeButtons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ const routerLinkButtons: THomeButtonRouterLink[] = [
text: "Job Training",
icon: BusinessCenterIcon,
linkState: "/job-training",
color: colors.lavendar,
color: colors.lavender,
},
{
text: "Social Services",
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/bin/setupCategories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const categories: {
],
},
{
color: "lavendar",
color: "lavender",
name: "Job Training",
stub: "job_training",
subcategories: [
Expand Down
100 changes: 87 additions & 13 deletions packages/server/src/models/Category.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,25 @@ export interface TCategoryDocument extends Document {
export async function categoryDocumentToCategory(
d: TCategoryDocument
): Promise<TCategory | null> {
let c = d;
if (d.toObject) {
c = d.toObject();
} else {
if (!d || !d.toObject) {
// console.warn(
// `\`categoryToDocumentCategory\` received category which does not appear to be a Mongoose Document [${Object.keys(
// d
// )}]:\n${JSON.stringify(d, null, 2)}`
// );
if (d.hasOwnProperty("_bsontype")) {
// console.warn("This appears to be an ObjectId");
// console.trace();
return null;
}
return null;
} else if (d.hasOwnProperty("_bsontype")) {
// console.warn("This appears to be an ObjectId");
// console.trace();
return null;
}

const result = {
...c,
_id: c._id.toHexString(),
...d,
_id: d._id.toHexString(),
subcategories: (
await Promise.all(
((c.subcategories || []) as TSubcategoryDocument[]).map(
((d.subcategories || []) as TSubcategoryDocument[]).map(
subcategoryDocumentToSubcategory
)
)
Expand Down Expand Up @@ -110,6 +107,72 @@ CategorySchema.statics.getByStub = async function(
return result;
};

CategorySchema.statics.getByStubLocation = async function(
stub: string,
options: {
includeDeleted?: boolean;
latitude: number;
longitude: number;
}
): Promise<TCategoryDocument | null> {
const { includeDeleted = false, latitude, longitude } = options;

const match: {
stub: string;
deleted?: { $ne: true };
} = { stub };

if (!includeDeleted) {
match.deleted = { $ne: true };
}

const result = await this.aggregate([
{ $match: match },
{ $limit: 1 },
{
$lookup: {
from: "subcategories",
as: "subcategories",
let: { subcategories: "$subcategories" },
pipeline: [
{
$lookup: {
localField: "subcategories",
foreignField: "_id",

from: "subcategories",
as: "resources",

// let: { resources: "$resources" },
// pipeline: [{
// $geoNear: {
// near: {
// type: "Point",
// coordinates: [longitude, latitude],
// },
// spherical: true,
// distanceField: "dist",
// },
// }],
},
},
],
},
},
{
$unwind: {
path: `$subcategories`,
preserveNullAndEmptyArrays: false,
},
},
]);

if (result.length) {
return result[0];
}
return null;
};

/**
* Creates or finds an existing subcategory by its name and adds
* it as a child of this category
Expand Down Expand Up @@ -137,5 +200,16 @@ export default Category as typeof Category & {
color?: string
) => Promise<TCategoryDocument>;
getCategoryList: () => Promise<TCategoryDocument[]>;
getByStub: (stub: string) => Promise<TCategoryDocument | null>;
getByStub: (
stub: string,
includeDeletedResources?: boolean
) => Promise<TCategoryDocument | null>;
getByStubLocation: (
stub: string,
options: {
includeDeletedResources?: boolean;
latitude: number;
longitude: number;
}
) => Promise<TCategoryDocument | null>;
};
2 changes: 1 addition & 1 deletion packages/server/src/models/Resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface TResourceDocument extends Document {
lastModifiedAt: Date;
lastModifiedBy: ObjectId | undefined; // always populate
legacyId: string | null | undefined;
location: { type: string; coordinates: number[] };
location: { type: "Point"; coordinates: number[] };
name: string;
phone: string;
schedule: TResourceScheduleData;
Expand Down
36 changes: 28 additions & 8 deletions packages/server/src/routes/api/category/[stub].ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,33 @@ import Category, { categoryDocumentToCategory } from "../../../models/Category";
export async function get(req, res, _next) {
const { stub } = req.params;

const categoryDocument = await Category.getByStub(stub);

if (categoryDocument) {
res.status(200).json({
category: await categoryDocumentToCategory(categoryDocument),
});
} else {
res.status(404).json({ message: `Category ${stub} not found` });
let categoryDocument;
try {
if (req.query.latitude && req.query.longitude) {
categoryDocument = await Category.getByStubLocation(stub, {
latitude: parseInt(req.query.latitude, 10),
longitude: parseInt(req.query.longitude, 10),
});
} else {
categoryDocument = await Category.getByStub(stub);
}

if (categoryDocument) {
console.log(
`\n categoryDocument:\n\n\n\t${JSON.stringify(categoryDocument)}\n\n`
);

res.status(200).json({
category: await categoryDocumentToCategory(categoryDocument),
categoryDocument,
});
} else {
res.status(404).json({ message: `Category ${stub} not found` });
}
} catch (e) {
console.error(e);
return res
.status(500)
.json({ message: `Error retrieving category: ${e.message}` });
}
}
2 changes: 1 addition & 1 deletion packages/web/src/components/Categories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export const categories: Record<TCategoryName, TCategoryDefinition> = {
],
},
JobTraining: {
color: "lavendar",
color: "lavender",
placeholder: BusinessCenterIcon,
mainCategory: {
translationKey: "jobTraining",
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/components/HomeButtons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export const routerLinkButtons: THomeButtonRouterLink[] = [
linkProps: {
to: "/job_training",
},
color: colors.lavendar,
color: colors.lavender,
},
{
text: "Social Services",
Expand Down
13 changes: 12 additions & 1 deletion packages/web/src/components/useResourcesByCategory.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import { TResource } from "@upswyng/types";
import { TResourcesByCategoryPayload } from "../webTypes";
import apiClient from "../utils/apiClient";
import { getUserCoordinates } from "../utils/location";
import { useQuery } from "react-query";

const getResourcesByCategory = async (
_queryKey: string,
params: { category: string }
): Promise<TResourcesByCategoryPayload> => {
console.log(`getResourcesByCategory`);

const userPosition = await getUserCoordinates();

const { data } = await apiClient.get<TResourcesByCategoryPayload>(
`/category/${params.category}`
`/category/${params.category}`,
{
params: {
latitude: userPosition.latitude,
longitude: userPosition.longitude,
},
}
);

if (!data.category) {
Expand Down
10 changes: 10 additions & 0 deletions packages/web/src/utils/location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const getUserCoordinates = async () => {
const pos = (await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
})) as Position;

return {
longitude: pos.coords.longitude,
latitude: pos.coords.latitude,
};
};