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

grooming code #484

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
33 changes: 13 additions & 20 deletions packages/common/src/ResourceSchedule.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { RRule, RRuleSet } from "rrule";
import {
TResource,
TResourceScheduleData,
TScheduleItemOpenClose,
TTimezoneName,
Expand Down Expand Up @@ -69,29 +68,29 @@ export function getScheduleItemPeriod(
): TScheduleItemOpenClose {
const openTimeValue = item.fromTime.value;
const closeTimeValue = item.toTime.value;
const firstOccurenceDate = item.recurrenceRule.all((_, i) => i < 1)[0];
const firstOccurrenceDate = item.recurrenceRule.all((_, i) => i < 1)[0];

const firstCloseDt = makeSchedulePeriodDate(
firstOccurenceDate,
firstOccurrenceDate,
closeTimeValue
);
// rrule doesn't know of the time so its first occurence could be past close
// rrule doesn't know of the time so its first occurrence could be past close
if (firstCloseDt.getTime() > dt.getTime()) {
const openDt = makeSchedulePeriodDate(firstOccurenceDate, openTimeValue);
const openDt = makeSchedulePeriodDate(firstOccurrenceDate, openTimeValue);
return {
open: openDt,
close: firstCloseDt,
};
}

// the first occurence is past close so retrieve first occurence after the given date
const secondOccurenceDate = item.recurrenceRule.after(dt);
// the first occurrence is past close so retrieve first occurrence after the given date
const secondOccurrenceDate = item.recurrenceRule.after(dt);
const secondCloseDt = makeSchedulePeriodDate(
secondOccurenceDate,
secondOccurrenceDate,
closeTimeValue
);
const secondOpenDt = makeSchedulePeriodDate(
secondOccurenceDate,
secondOccurrenceDate,
closeTimeValue
);
return {
Expand All @@ -101,13 +100,13 @@ export function getScheduleItemPeriod(
}

/**
* Represents the reoccuring schedule of a resource (ex: Mon, Wed, Fri from 8am - 10pm)
* Represents the recurring schedule of a resource (ex: Mon, Wed, Fri from 8am - 10pm)
* Based on the iCalendar standard (https://icalendar.org/iCalendar-RFC-5545)
* Wraps the rrule library (https://github.com/jakubroztocil/rrule) in order to add
* comments for schedule rules (ex: Mon 8am-12pm for residents, 1pm-4pm for non-residents)
*/
export default class ResourceSchedule {
private _items: TScheduleItem[];
private readonly _items: TScheduleItem[];
/**
* Whether the Resource is always open.
*/
Expand Down Expand Up @@ -214,11 +213,7 @@ export default class ResourceSchedule {
return null;
}

if (at.getTime() > nextScheduleItemPeriod.open.getTime()) {
return true;
}

return false;
return at.getTime() > nextScheduleItemPeriod.open.getTime();
}

/**
Expand All @@ -244,10 +239,8 @@ export default class ResourceSchedule {
if (!r.toTime || typeof r.toTime !== "string") {
return false;
}
if (r.comment && typeof r.comment !== "string") {
return false;
}
return true;

return !(r.comment && typeof r.comment !== "string");
})
) {
throw new Error(
Expand Down
2 changes: 1 addition & 1 deletion packages/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ This file contains placeholders for various API keys that you may or may not nee
yarn workspace @upswyng/server dev
```

Runs the server in the development mode. Open [http:/localhost:3000](http:/localhost:3000) to view it in the browser.
Runs the server in the development mode. Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

If you want to work on the [provider portal](http://localhost:3000/provider), you can log in with this google user:

Expand Down
9 changes: 4 additions & 5 deletions packages/server/src/models/Category.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import mongoose, { Document, Schema } from "mongoose";
import removeUndefinedFields from "../utility/removeUndefinedFields";
import Subcategory, {
TSubcategoryDocument,
subcategoryDocumentToSubcategory,
} from "./Subcategory";
import { TCategory, TSubcategory } from "@upswyng/types";
import mongoose, { Document, Schema } from "mongoose";

import { ObjectId } from "bson";
import removeUndefinedFields from "../utility/removeUndefinedFields";
import { TCategory } from "@upswyng/types";

export interface TCategoryDocument extends Document {
_id: ObjectId;
Expand Down Expand Up @@ -91,7 +90,7 @@ CategorySchema.statics.findOrCreate = async function(
CategorySchema.statics.getCategoryList = async function(): Promise<
TCategoryDocument[]
> {
return await this.find().populate("subcategories");
return this.find().populate("subcategories");
};

CategorySchema.statics.getByStub = async function(
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/models/Hotline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const HotlineSchema = new Schema(
);

HotlineSchema.statics.getAll = async function(): Promise<THotlineDocument[]> {
return await this.find({});
return this.find({});
};

const HotlineModel = mongoose.model<THotlineDocument>("Hotline", HotlineSchema);
Expand Down
13 changes: 6 additions & 7 deletions packages/server/src/models/Resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
TLegacyResource,
TResource,
TResourceScheduleData,
TSubcategory,
} from "@upswyng/types";
import {
TSubcategoryDocument,
Expand Down Expand Up @@ -49,7 +48,7 @@ export interface TResourceDocument extends Document {

/**
* Convert a resource document from the database into our `TResource` type.
* Explicity enumerate keys so we make TypeScript happy.
* Explicitly enumerate keys so we make TypeScript happy.
*/
export const resourceDocumentToResource = async (
r: TResourceDocument
Expand Down Expand Up @@ -331,7 +330,7 @@ ResourceSchema.statics.getByResourceId = async function(
resourceId: ObjectId,
includeDeleted: boolean = false
): Promise<TResourceDocument | null> {
return await this.findOne({
return this.findOne({
resourceId,
deleted: { $in: [false, includeDeleted] },
})
Expand All @@ -346,7 +345,7 @@ ResourceSchema.statics.getByResourceId = async function(
ResourceSchema.statics.getByRecordId = async function(
_id: ObjectId
): Promise<TResourceDocument | null> {
return await this.findOne({ _id })
return this.findOne({ _id })
.populate({ path: "subcategories", populate: { path: "parentCategory" } })
.populate("createdBy")
.populate("lastModifiedBy");
Expand All @@ -358,7 +357,7 @@ ResourceSchema.statics.getByRecordId = async function(
ResourceSchema.statics.getByResourceIds = async function(
resourceIds: ObjectId[]
): Promise<TResourceDocument[]> {
return await this.find({
return this.find({
resourceId: { $in: resourceIds },
})
.populate({ path: "subcategories", populate: { path: "parentCategory" } })
Expand All @@ -372,7 +371,7 @@ ResourceSchema.statics.getByResourceIds = async function(
ResourceSchema.statics.getAll = async function(
includeDeleted: boolean = false
): Promise<TResourceDocument[]> {
return await this.find({ deleted: { $in: [false, includeDeleted] } })
return this.find({ deleted: { $in: [false, includeDeleted] } })
.populate({ path: "subcategories", populate: { path: "parentCategory" } })
.populate("createdBy")
.populate("lastModifiedBy");
Expand All @@ -384,7 +383,7 @@ ResourceSchema.statics.getAll = async function(
ResourceSchema.statics.getUncategorized = async function(): Promise<
TResourceDocument[]
> {
return await this.find({
return this.find({
"subcategories.0": { $exists: false },
deleted: false,
})
Expand Down
13 changes: 6 additions & 7 deletions packages/server/src/models/ResourceIssue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,23 +104,22 @@ ResourceIssueSchema.statics.newWithoutResourceId = function(
}) as TResourceIssueDocument;
};

const ResourceIssue = mongoose.model<TResourceIssueDocument>(
"ResourceIssue",
ResourceIssueSchema
);

ResourceIssueSchema.statics.getForResource = async function(
resourceId: ObjectId,
includeResolved = false
): Promise<TResourceIssueDocument[]> {
// ensure that a resource exists with this ID
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return await ResourceIssue.find({
return ResourceIssue.find({
resourceId,
resolved: { $in: [false, includeResolved] },
}).sort({ createdAt: -1 });
};

const ResourceIssue = mongoose.model<TResourceIssueDocument>(
"ResourceIssue",
ResourceIssueSchema
);

export default ResourceIssue as typeof ResourceIssue & {
/**
* Creates a new Resource Issue but __does not__ save it. Does not include a Resource ID;
Expand Down
4 changes: 2 additions & 2 deletions packages/server/src/models/Subcategory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,11 @@ SubcategorySchema.statics.getSubcategoryList = async function(
includeResources = false
) {
if (includeResources) {
return await this.find()
return this.find()
.populate("parentCategory")
.populate("resources");
}
return await this.find()
return this.find()
.populate("parentCategory")
.map(r => {
delete r.resources;
Expand Down
10 changes: 4 additions & 6 deletions packages/server/src/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,7 @@ UserSchema.statics.findOrCreateGoogleUser = async function(
} else if (!user) {
try {
const newUser = new self({ google: { sub, email } });
const result = await newUser.save();
return result;
return newUser.save();
} catch (e) {
console.error(`Error creating new user:\t${e}`);
throw e;
Expand All @@ -143,7 +142,7 @@ UserSchema.statics.findOrCreateGoogleUser = async function(
if (email) {
user.google.email = email;
}
return await user.save();
return user.save();
}
return user;
};
Expand All @@ -167,8 +166,7 @@ UserSchema.statics.findOrCreateSlackUser = async function(
const newUser = new self({
slack: { email, name, userId: slackUserId, teamId },
});
const result = await newUser.save();
return result;
return newUser.save();
} catch (e) {
console.error(`Error creating new user:\t${e}`);
throw e;
Expand All @@ -184,7 +182,7 @@ UserSchema.statics.findOrCreateSlackUser = async function(
user.slack.email = email;
user.slack.teamId = teamId;
user.slack.name = name;
return await user.save();
return user.save();
}
return user;
};
Expand Down
7 changes: 6 additions & 1 deletion packages/server/src/routes/api/bot/test-job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@ async function makeTestJob(req, res, _next, user: TUser) {
}
}
// TODO: Better Failure handling
mq.addJobTest(jobName, delay ? delay * 1000 : null, undefined, user._id); // this is taking too long, so don't await it.
await mq.addJobTest(
jobName,
delay ? delay * 1000 : null,
undefined,
user._id
); // this is taking too long, so don't await it.
const blocks = [
{
type: "section",
Expand Down
76 changes: 38 additions & 38 deletions packages/server/src/routes/api/resource/issues/_setResolved.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,47 +56,47 @@ export async function setResolved(resolved: boolean, req, res, next) {
message: `Service Provider issue with _id ${_id} could not be found`,
})
);
} else {
}

try {
issue.resolved = resolved;
await issue.save();
// Create Event Log
try {
issue.resolved = resolved;
await issue.save();
// Create Event Log
try {
const resource = await Resource.getByResourceId(issue.resourceId);
const kind: EventLogKind = resolved
? EventLogKind.ResourceIssueResolved
: EventLogKind.ResourceIssueReopened;
const newDocument = await new EventLog({
actor: user._id,
detail: {
kind,
resourceId: issue.resourceId.toHexString(),
resourceName: resource.name,
resourceIssueSeverity: issue.severity,
resourceIssueKind: issue.kind,
resourceIssueId: issue._id.toHexString(),
},
const resource = await Resource.getByResourceId(issue.resourceId);
const kind: EventLogKind = resolved
? EventLogKind.ResourceIssueResolved
: EventLogKind.ResourceIssueReopened;
const newDocument = await new EventLog({
actor: user._id,
detail: {
kind,
}).save();
await newDocument.populate("actor").execPopulate();
await postEventLogMessage(eventLogDocumentToEventLog(newDocument));
} catch (e) {
console.error(e);
}
res.writeHead(204);
res.end();
resourceId: issue.resourceId.toHexString(),
resourceName: resource.name,
resourceIssueSeverity: issue.severity,
resourceIssueKind: issue.kind,
resourceIssueId: issue._id.toHexString(),
},
kind,
}).save();
await newDocument.populate("actor").execPopulate();
await postEventLogMessage(eventLogDocumentToEventLog(newDocument));
} catch (e) {
res.writeHead(500, {
"Content-Type": "application/json",
});
res.end(
JSON.stringify({
message: `Error setting Service Provider issue with _id ${_id} to ${
resolved ? "resolved" : "unresolved"
}: ${e.message}`,
})
);
return;
console.error(e);
}
res.writeHead(204);
res.end();
} catch (e) {
res.writeHead(500, {
"Content-Type": "application/json",
});
res.end(
JSON.stringify({
message: `Error setting Service Provider issue with _id ${_id} to ${
resolved ? "resolved" : "unresolved"
}: ${e.message}`,
})
);
return;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ import { setResolved } from "../_setResolved";
* API endpoint to set a `ResourceIssue`'s `resolved` field to `true`.
*/
export async function post(req, res, next) {
return await setResolved(true, req, res, next);
return setResolved(true, req, res, next);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ import { setResolved } from "../_setResolved";
* API endpoint to set a `ResourceIssue`'s `resolved` field to `false`.
*/
export async function post(req, res, next) {
return await setResolved(false, req, res, next);
return setResolved(false, req, res, next);
}
2 changes: 1 addition & 1 deletion packages/server/src/routes/provider/alert/create.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</script>

<script>
import { addFlashMessage } from "./../../../utility/flashMessage.ts";
import { addFlashMessage } from "../../../utility/flashMessage";
import { goto, stores } from "@sapper/app";
import { onDestroy, onMount } from "svelte";
import { Time } from "@upswyng/common";
Expand Down
Loading