Skip to content

Instantly share code, notes, and snippets.

@dcluna
Created November 29, 2017 21:00
Show Gist options
  • Save dcluna/af33b175329ec0ba6427b63d2e79679a to your computer and use it in GitHub Desktop.
Save dcluna/af33b175329ec0ba6427b63d2e79679a to your computer and use it in GitHub Desktop.
"use strict";
import * as Promise from "bluebird";
import createDeal from "../../deal/operations/create";
import stopEmails from "./stop-lease-end-emails";
import { createActivity, setCurrentApplication } from "./create";
import { emitApplicationCreated } from "../events/emitter";
import { models, withTransaction } from "../../models";
import {
Application,
ApplicationAttrs,
internalRenewalQuestionnaireType,
renewalStarted
} from "../../application/model";
import { Building } from "../../building/model";
import { User } from "../../user/model";
const excludeAttrs = [
"bondNumber",
"bondVersion",
"createdAt",
"dateClosed",
"dealId",
"freeMonth2End",
"freeMonth2Start",
"freeMonthEnd",
"freeMonthStart",
"freeMonths",
"id",
"leaseEnd",
"leaseEndsNotificationSentDate",
"leaseStart",
"paymentMethod",
"questionnaireType",
"reasonLost",
"renewingWithBuilding",
"renterLeaseEndsNotificationSentDate",
"status",
"updatedAt"
];
export default function duplicateApplication(
id: number,
creator: User
): Promise<Application> {
return withTransaction(() => {
return models.Application
.scope({ method: ["withBuilding", false] })
.findByIdRequired(id, { attributes: { exclude: excludeAttrs } })
.tap(() => stopEmails(id))
.then(application => getNewApplicationAttrs(application, id))
.then(newApplicationAttrs => models.Application.create(newApplicationAttrs))
.tap(newApplication => createDeal(newApplication))
.tap(newApplication => newApplication.getApplicant()
.tap(applicant => setCurrentApplication(applicant)(newApplication))
.tap(applicant => createActivity(applicant)(newApplication))
)
.then(newApplication => newApplication.reload())
.tap(application => emitApplicationCreated(application, "Renewal", creator));
});
}
function getNewApplicationAttrs(
application: Application,
id: number
): ApplicationAttrs {
const building = application.building;
const attrs: ApplicationAttrs = {
...application.get({ plain: true }),
renewParentApplicationId: id,
version: application.version + 1,
questionnaireType: internalRenewalQuestionnaireType,
status: renewalStarted
};
if (building) {
return {
...attrs,
addressStreet: formatAddress(
building.addressStreet,
application.apartmentNumber
),
addressCity: building.addressCity,
addressState: building.addressState,
addressZip: building.zipCode
};
}
return attrs;
}
function formatAddress(
addressStreet: string,
apartmentNumber: string
): string {
return `${addressStreet} Apt ${apartmentNumber}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment