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

Session3 #2

Open
wants to merge 7 commits into
base: session_2_solution
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
6 changes: 5 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@ module.exports = {
"no-console": "off",
"@typescript-eslint/camelcase": "off",
"@typescript-eslint/explicit-function-return-type": ["off"],
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],
"@typescript-eslint/no-unused-vars": [
"error",
{ argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
],
"react/prop-types": "off",
"react/display-name": "off",
"no-unused-expressions": "off",
"no-useless-concat": "off",
"no-useless-constructor": "off",
"no-unexpected-multiline": "off",
"default-case": "off",
"no-debugger": "warn",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-interface": "off",
Expand Down
15 changes: 12 additions & 3 deletions i18n/en.pot
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ msgstr ""
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"POT-Creation-Date: 2021-06-16T11:22:27.225Z\n"
"PO-Revision-Date: 2021-06-16T11:22:27.225Z\n"
"POT-Creation-Date: 2021-06-23T06:35:51.611Z\n"
"PO-Revision-Date: 2021-06-23T06:35:51.611Z\n"

msgid "Organisation unit is assigned to more than one option"
msgstr ""
Expand All @@ -29,6 +29,9 @@ msgstr ""
msgid "Unknown group set"
msgstr ""

msgid "Project saved"
msgstr ""

msgid "Organisation unit {{orgUnitId}} not found"
msgstr ""

Expand Down Expand Up @@ -65,11 +68,17 @@ msgstr ""
msgid "Code"
msgstr ""

msgid "Save"
msgstr ""

msgid "Clear form"
msgstr ""

msgid "Back"
msgstr ""

msgid "Help"
msgstr ""

msgid "Training session 2"
msgid "Training session 3"
msgstr ""
13 changes: 11 additions & 2 deletions i18n/es.po
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
msgid ""
msgstr ""
"Project-Id-Version: i18next-conv\n"
"POT-Creation-Date: 2021-06-16T11:22:27.225Z\n"
"POT-Creation-Date: 2021-06-23T06:35:51.611Z\n"
"PO-Revision-Date: 2018-10-25T09:02:35.143Z\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
Expand Down Expand Up @@ -29,6 +29,9 @@ msgstr ""
msgid "Unknown group set"
msgstr ""

msgid "Project saved"
msgstr ""

msgid "Organisation unit {{orgUnitId}} not found"
msgstr ""

Expand Down Expand Up @@ -65,11 +68,17 @@ msgstr ""
msgid "Code"
msgstr ""

msgid "Save"
msgstr ""

msgid "Clear form"
msgstr ""

msgid "Back"
msgstr "Volver"

msgid "Help"
msgstr "Ayuda"

msgid "Training session 2"
msgid "Training session 3"
msgstr ""
2 changes: 2 additions & 0 deletions src/compositionRoot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { GetOrgUnitByIdUseCase } from "./domain/usecases/GetOrgUnitByIdUseCase";
import { GetOrgUnitsByIdsUseCase } from "./domain/usecases/GetOrgUnitsByIdsUseCase";
import { GetOrgUnitsByLevelUseCase } from "./domain/usecases/GetOrgUnitsByLevelUseCase";
import { GetOrgUnitsUseCase } from "./domain/usecases/GetOrgUnitsUseCase";
import { SaveOrgUnitUseCase } from "./domain/usecases/SaveOrgUnitUseCase";
import { D2Api } from "./types/d2-api";

export function getCompositionRoot(api: D2Api) {
Expand All @@ -20,6 +21,7 @@ export function getCompositionRoot(api: D2Api) {
getById: new GetOrgUnitByIdUseCase(orgUnitRepository),
getByIds: new GetOrgUnitsByIdsUseCase(orgUnitRepository),
getByLevel: new GetOrgUnitsByLevelUseCase(orgUnitRepository),
save: new SaveOrgUnitUseCase(orgUnitRepository),
},
groupSets: {
getOptions: new GetGroupSetOptionsUseCase(groupSetRepository),
Expand Down
130 changes: 109 additions & 21 deletions src/data/OrgUnitDHIS2Repository.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
import { Id } from "../domain/entities/Base";
import _ from "lodash";
import { Id, NamedRef } from "../domain/entities/Base";
import { OrgUnit } from "../domain/entities/OrgUnit";
import { OrgUnitRepository } from "../domain/repositories/OrgUnitRepository";
import { D2Api, D2ApiDefinition, D2OrganisationUnitSchema, Model } from "../types/d2-api";
import { D2Api, D2ApiDefinition, D2OrganisationUnitSchema, Model, Ref } from "../types/d2-api";

interface D2OrgUnit {
id: Id;
code: string;
name: string;
shortName: string;
level: number;
path: string;
parent: Ref;
openingDate?: string;
closedDate?: string;
children: NamedRef[];
organisationUnitGroups: NamedRef[];
}

type Options = Pick<
Parameters<Model<D2ApiDefinition, D2OrganisationUnitSchema>["get"]>[0],
"filter"
>;

export class OrgUnitDHIS2Repository implements OrgUnitRepository {
constructor(private api: D2Api) {}
Expand All @@ -23,36 +43,104 @@ export class OrgUnitDHIS2Repository implements OrgUnitRepository {
return this.request({ filter: { level: { eq: `${level}` } } });
}

private async request(
options: Omit<
Parameters<Model<D2ApiDefinition, D2OrganisationUnitSchema>["get"]>[0],
"paging" | "fields"
>
async save(orgUnit: OrgUnit) {
const existingD2OrgUnit = await this.getD2OrgUnitFromId(orgUnit.id);
const orgUnitGroupsToSave = await this.getOrgUnitGroupsToSave(orgUnit, existingD2OrgUnit);
const orgUnitToSave = { ...existingD2OrgUnit, ...this.buildD2OrgUnit(orgUnit) };
const metadata = {
organisationUnits: [orgUnitToSave],
organisationUnitGroups: orgUnitGroupsToSave,
};
const res = await this.api.metadata.post(metadata).getData();

if (res.status !== "OK") throw new Error("Cannot save organisation unit");
}

private async getOrgUnitGroupsToSave(
orgUnit: OrgUnit,
existingD2OrgUnit: D2OrgUnit | undefined
) {
const existingOrgUnitGroups = await this.getOrgUnitGroups(orgUnit, existingD2OrgUnit);

const orgUnitGroupsUpdated = existingOrgUnitGroups.map(ouGroup => {
const ouWasInGroup = _(ouGroup.organisationUnits).some(ou => ou.id === orgUnit.id);
const ouInGroup = _(orgUnit.organisationUnitGroups).some(oug => oug.id === ouGroup.id);
const orgUnitGroupHasChanged = ouWasInGroup !== ouInGroup;

if (!orgUnitGroupHasChanged) {
// As there are no changes, there is no need to save this org unit group.
return null;
} else {
const organisationUnitsUpdated = ouInGroup
? ouGroup.organisationUnits.concat([orgUnit])
: ouGroup.organisationUnits.filter(ou => ou.id !== orgUnit.id);

return { ...ouGroup, organisationUnits: organisationUnitsUpdated };
}
});

return _.compact(orgUnitGroupsUpdated);
}

/* Get the union of org unit groups both for the existing org unit and the unsaved record */
private async getOrgUnitGroups(orgUnit: OrgUnit, existingD2OrgUnit: D2OrgUnit | undefined) {
const existingOrgUnitGroupRefs = existingD2OrgUnit
? existingD2OrgUnit.organisationUnitGroups
: [];
const newOrgUnitGroupRefs = orgUnit.organisationUnitGroups;
const allOrgUnitGroupRefs = _.concat(existingOrgUnitGroupRefs, newOrgUnitGroupRefs);

const { organisationUnitGroups } = await this.api.metadata
.get({
organisationUnitGroups: {
fields: { $owner: true },
filter: { id: { in: _.uniq(allOrgUnitGroupRefs.map(oug => oug.id)) } },
},
})
.getData();

return organisationUnitGroups;
}

private async getD2OrgUnits(options: Options): Promise<D2OrgUnit[]> {
const { objects } = await this.api.models.organisationUnits
.get({
...options,
fields: {
id: true,
code: true,
name: true,
level: true,
openingDate: true,
closedDate: true,
parent: { id: true, name: true },
$owner: true,
children: { id: true, name: true },
organisationUnitGroups: { id: true, name: true },
},
paging: false,
})
.getData();

return objects.map(data =>
OrgUnit.create({
...data,
openingDate: data.openingDate ? new Date(data.openingDate) : undefined,
closedDate: data.closedDate ? new Date(data.closedDate) : undefined,
})
);
return objects;
}

private async getD2OrgUnitFromId(id: Id): Promise<D2OrgUnit | undefined> {
const orgUnits = await this.getD2OrgUnits({ filter: { id: { eq: id } } });
return _.first(orgUnits);
}

private async request(options: Options): Promise<OrgUnit[]> {
const d2OrgUnits = await this.getD2OrgUnits(options);
return d2OrgUnits.map(data => this.buildOrgUnit(data));
}

private buildOrgUnit(d2OrgUnit: D2OrgUnit): OrgUnit {
return OrgUnit.create({
...d2OrgUnit,
openingDate: d2OrgUnit.openingDate ? new Date(d2OrgUnit.openingDate) : undefined,
closedDate: d2OrgUnit.closedDate ? new Date(d2OrgUnit.closedDate) : undefined,
});
}

private buildD2OrgUnit(orgUnit: OrgUnit): Partial<D2OrgUnit> {
return {
...orgUnit,
openingDate: orgUnit.openingDate?.toISOString(),
closedDate: orgUnit.closedDate?.toISOString(),
};
}
}
14 changes: 14 additions & 0 deletions src/domain/entities/OrgUnit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,18 @@ export class OrgUnit {
static create(data: OrgUnitData) {
return new OrgUnit(data);
}

set<T extends keyof OrgUnitData>(key: T, value: OrgUnitData[T]): OrgUnit {
return OrgUnit.create({ ...this, [key]: value });
}

setOrganisationUnitGroups(selected: NamedRef[], unselected: NamedRef[]): OrgUnit {
const selectedIds = new Set(selected.map(group => group.id));
const unselectedIds = new Set(unselected.map(group => group.id));
const newOrgUnitGroups = _(this.organisationUnitGroups)
.filter(group => !unselectedIds.has(group.id) && !selectedIds.has(group.id))
.concat(selected)
.value();
return OrgUnit.create({ ...this, organisationUnitGroups: newOrgUnitGroups });
}
}
1 change: 1 addition & 0 deletions src/domain/repositories/OrgUnitRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export interface OrgUnitRepository {
getById(id: Id): Promise<OrgUnit | undefined>;
getByIds(ids: Id[]): Promise<OrgUnit[]>;
getByLevel(level: number): Promise<OrgUnit[]>;
save(orgUnit: OrgUnit): Promise<void>;
}
10 changes: 10 additions & 0 deletions src/domain/usecases/SaveOrgUnitUseCase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { OrgUnit } from "../entities/OrgUnit";
import { OrgUnitRepository } from "../repositories/OrgUnitRepository";

export class SaveOrgUnitUseCase {
constructor(private orgUnitRepository: OrgUnitRepository) {}

async execute(orgUnit: OrgUnit) {
return this.orgUnitRepository.save(orgUnit);
}
}
20 changes: 16 additions & 4 deletions src/webapp/components/group-set-dropdown/GroupSetDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,34 +13,46 @@ export interface GroupSetDropdownProps {
groupSet: OrgUnitGroupSet;
orgUnit: OrgUnit;
disabled?: boolean;
onChange?(selectedGroups: NamedRef[], unselectedGroups: NamedRef[]): void;
}

export const GroupSetDropdown: React.FC<GroupSetDropdownProps> = ({
groupSet,
orgUnit,
disabled,
onChange,
}) => {
const { compositionRoot } = useAppContext();

const [groupOptions, setGroupOptions] = useState<DropdownItem[]>([]);
const [groups, setGroups] = useState<NamedRef[]>([]);

const groupOptions = namedRefToOption(groups);

const intersection = _.intersection(
orgUnit.organisationUnitGroups.map(({ id }) => id),
groupOptions.map(({ value }) => value)
);

useEffect(() => {
compositionRoot.groupSets.getOptions.execute(groupSet).then(options => {
setGroupOptions(namedRefToOption(options));
compositionRoot.groupSets.getOptions.execute(groupSet).then(groups => {
setGroups(groups);
});
}, [compositionRoot, groupSet]);

function notifyChange(groupId: string | undefined) {
if (!onChange) return;
const selectedGroup = groups.filter(group => group.id === groupId);
const unselectedGroups = groups.filter(group => group.id !== groupId);
onChange(selectedGroup, unselectedGroups);
}

return (
<React.Fragment>
<GroupInput
label={formatOrgUnitGroupSet(groupSet)}
value={intersection[0]}
items={groupOptions}
onChange={_.noop}
onChange={notifyChange}
disabled={disabled}
/>

Expand Down
Loading