Skip to content

Commit

Permalink
TS-936 Municipality
Browse files Browse the repository at this point in the history
  • Loading branch information
birkirkristmunds committed Dec 16, 2024
1 parent 582ac4c commit 4336424
Show file tree
Hide file tree
Showing 17 changed files with 86 additions and 73 deletions.
4 changes: 2 additions & 2 deletions apps/skilavottord/web/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -650,14 +650,14 @@
"view": {
"title": "Municipality",
"breadcrumb": "View",
"info": "Þú getur annaðhvort uppfært eða eytt móttökuaðila. Vinsamlegast staðfestið að upplýsingar fyrirtækis séu rétt slegnar inn.",
"info": "You can update the municipality. Please confirm that the information are correct.",
"updated": "Updated",
"deleted": "Deleted"
},
"add": {
"title": "Add municipality",
"breadcrumb": "Add new",
"info": "Þegar nýju sveitarfélagi er bætt við, verður hann aðgengilegur í aðgangsstýringu. Vinsamlegast staðfestið að upplýsingar fyrirtækis séu rétt slegnar inn.",
"info": "Adding a new municipality will make it available to access control. Please verify that the municipality information is correct.",
"added": "Added"
}
}
Expand Down
3 changes: 2 additions & 1 deletion apps/skilavottord/web/i18n/locales/is.json
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,8 @@
},
"municipality": {
"label": "Sveitarfélag",
"placeholder": "Sveitarfélag"
"placeholder": "Sveitarfélag",
"required": "Skylda að fylla út sveitarfélag"
}
},
"buttons": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,8 @@ const AccessControl: FC<React.PropsWithChildren<unknown>> = () => {
recyclingPartnerLoading ||
accessControlsLoading ||
recyclingPartnerByIdLoading
const isData = !!recyclingPartnerData || !!accessControlsData
const isData =
!!recyclingPartnerData || !!recyclingPartnerByIdData || !!accessControlsData

const {
t: { accessControl: t, routes },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,9 @@ export const AccessControlCreate: FC<
control={control}
errors={errors}
partnerIdRequired={
watch('role')?.value === Role.recyclingCompanyAdmin ||
watch('role')?.value === Role.recyclingCompany
(watch('role')?.value === Role.recyclingCompanyAdmin ||
watch('role')?.value === Role.recyclingCompany) ??
false
}
/>
)
Expand Down
18 changes: 3 additions & 15 deletions apps/skilavottord/web/screens/Overview/Overview.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,15 @@
import React, { FC } from 'react'
import gql from 'graphql-tag'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useQuery } from '@apollo/client'
import gql from 'graphql-tag'
import React, { FC } from 'react'

import {
Box,
Stack,
Text,
BreadcrumbsDeprecated as Breadcrumbs,
SkeletonLoader,
Button,
} from '@island.is/island-ui/core'

import { PageLayout, InlineError } from '@island.is/skilavottord-web/components'
import { PageLayout } from '@island.is/skilavottord-web/components'
import { useI18n } from '@island.is/skilavottord-web/i18n'
import { Query } from '@island.is/skilavottord-web/graphql/schema'

import { filterCarsByStatus } from '@island.is/skilavottord-web/utils'
import { BASE_PATH } from '@island.is/skilavottord/consts'

import { ActionCardContainer, ProgressCardContainer } from './components'
import { RecycleActionTypes } from './types'

const SkilavottordVehiclesQuery = gql`
query skilavottordVehiclesQuery {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,9 @@ const RecyclingCompanyCreate: FC<React.PropsWithChildren<unknown>> = () => {
formState: { errors },
} = useForm({
mode: 'onChange',
defaultValues: {
isMunicipality: isMunicipalityPage,
municipalityId: partnerId,
},
defaultValues: isMunicipalityPage
? { isMunicipalityPage }
: { isMunicipalityPage, municipalityId: partnerId },
})

const [createSkilavottordRecyclingPartner] = useMutation(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ const UpdateSkilavottordRecyclingPartnerMutation = gql`
website
phone
active
municipalityId
}
}
`
Expand Down Expand Up @@ -148,36 +149,35 @@ const RecyclingCompanyUpdate: FC<React.PropsWithChildren<unknown>> = () => {
return <NotFound />
}

const navigateToBaseRoute = () => {
const route = isMunicipalityPage
? routes.municipalities.baseRoute
: routes.recyclingCompanies.baseRoute
return router.push(route)
}

const handleUpdateRecyclingPartner = handleSubmit(async (input) => {
// Not needed to be sent to the backend, causes error if it is sent
delete input.__typename

if (typeof input.municipalityId !== 'string') {
input.municipalityId = input.municipalityId?.value || ''
}
const municipalityId = input.municipalityId
input.municipalityId =
typeof municipalityId === 'object' && municipalityId?.value
? municipalityId.value
: (municipalityId as string) || ''

const { errors } = await updateSkilavottordRecyclingPartner({
variables: { input },
})
if (!errors) {
if (isMunicipalityPage) {
router.push(routes.municipalities.baseRoute).then(() => {
toast.success(t.recyclingCompany.view.updated)
})
} else {
router.push(routes.recyclingCompanies.baseRoute).then(() => {
toast.success(t.recyclingCompany.view.updated)
})
}
navigateToBaseRoute().then(() => {
toast.success(t.recyclingCompany.view.updated)
})
}
})

const handleCancel = () => {
if (isMunicipalityPage) {
router.push(routes.municipalities.baseRoute)
} else {
router.push(routes.recyclingCompanies.baseRoute)
}
navigateToBaseRoute()
}

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,8 @@ import PageHeader from '@island.is/skilavottord-web/components/PageHeader/PageHe
import { CarsTable } from './components'

export const SkilavottordVehiclesQuery = gql`
query skilavottordVehiclesQuery($after: String!, $municipalityId: String!) {
skilavottordAllDeregisteredVehicles(
first: 20
after: $after
municipalityId: $municipalityId
) {
query skilavottordVehiclesQuery($after: String!) {
skilavottordAllDeregisteredVehicles(first: 20, after: $after) {
pageInfo {
endCursor
hasNextPage
Expand Down Expand Up @@ -61,7 +57,7 @@ const Overview: FC<React.PropsWithChildren<unknown>> = () => {
SkilavottordVehiclesQuery,
{
notifyOnNetworkStatusChange: true,
variables: { after: '', municipalityId: '601' },
variables: { after: '' },
},
)
const { pageInfo, items: vehicles } =
Expand Down
6 changes: 3 additions & 3 deletions apps/skilavottord/web/utils/accessUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { Role, SkilavottordUser } from '../graphql/schema'

export const getPartnerId = (
user: SkilavottordUser | undefined,
municipalityId: string,
partnerId: string,
municipalityId: string | null,
partnerId: string | null,
role: Role,
) => {
// If the user has municipality role, then he can only create a new access under the same municipality
Expand All @@ -13,5 +13,5 @@ export const getPartnerId = (
}

// If selected role is municipality, use municipalityId, else use partnerId
return hasMunicipalityRole(role) ? municipalityId : partnerId || null
return hasMunicipalityRole(role) ? municipalityId ?? null : partnerId ?? null
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ module.exports = {
up: (queryInterface) => {
return queryInterface.sequelize.query(`
BEGIN;
ALTER TABLE recycling_partner ADD COLUMN is_municipality BOOLEAN;
ALTER TABLE recycling_partner ADD COLUMN municipality_id VARCHAR;
ALTER TABLE recycling_partner ADD COLUMN is_municipality BOOLEAN NOT NULL DEFAULT FALSE
ALTER TABLE recycling_partner ADD COLUMN municipality_id VARCHAR(50)
CREATE INDEX idx_recycling_partner_is_municipality ON recycling_partner(is_municipality);
COMMIT;
`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,14 @@ export class AccessControlResolver {
const isDeveloper = user.role === Role.developer

if (user.role === Role.municipality) {
return this.accessControlService.findByRecyclingPartner(user.partnerId)
try {
return this.accessControlService.findByRecyclingPartner(user.partnerId)
} catch (error) {
throw new ApolloError(
'Failed to fetch municipality access controls',
'MUNICIPALITY_ACCESS_ERROR',
)
}
}

return this.accessControlService.findAll(isDeveloper)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class UpdateRecyclingPartnerInput {
@Field()
email?: string

@Field()
@Field({ nullable: true })
isMunicipality?: boolean

@Field({ nullable: true })
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { ConflictException, NotFoundException } from '@nestjs/common'
import {
BadRequestException,
ConflictException,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common'
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'

import { Authorize, Role } from '../auth'
Expand Down Expand Up @@ -32,16 +37,22 @@ export class RecyclingPartnerResolver {
@Query(() => [RecyclingPartnerModel], {
name: 'skilavottordRecyclingPartners',
})
async getRecyclingPartners(
async skilavottordRecyclingPartners(
@Args('isMunicipalityPage', { type: () => Boolean, nullable: true })
isMunicipalityPage: boolean,
@Args('municipalityId', { type: () => String, nullable: true })
municipalityId: string | null,
): Promise<RecyclingPartnerModel[]> {
return this.recyclingPartnerService.findRecyclingPartners(
isMunicipalityPage,
municipalityId,
)
try {
return this.recyclingPartnerService.findRecyclingPartners(
isMunicipalityPage,
municipalityId,
)
} catch (error) {
throw new InternalServerErrorException(
`Failed to fetch recycling partners: ${error.message}`,
)
}
}

@Query(() => [RecyclingPartnerModel])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,15 @@ export class RecyclingPartnerService {
* @param companyId
* @returns
*/
async getGetPayingPartnerId(companyId: string): Promise<string> {
async getPayingPartnerId(companyId: string): Promise<string> {
const partner = await this.recyclingPartnerModel.findOne({
where: { companyId },
})

return partner.municipalityId || partner.companyId
if (!partner) {
throw new Error(`Partner not found for company ID: ${companyId}`)
}

return partner.municipalityId ?? partner.companyId
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class RecyclingRequestService {
vehicle: VehicleModel,
) {
const disposalStationId =
await this.recyclingPartnerService.getGetPayingPartnerId(disposalStation)
await this.recyclingPartnerService.getPayingPartnerId(disposalStation)

try {
const { restAuthUrl, restDeRegUrl, restUsername, restPassword } =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export class VehicleResolver {
@CurrentUser() user: User,
@Args('first', { type: () => Int }) first: number,
@Args('after') after: string,
@Args('municipalityId') municipalityId: string,
): Promise<VehicleConnection> {
const { pageInfo, totalCount, data } =
await this.vehicleService.findAllByFilter(first, after, {
Expand Down
20 changes: 13 additions & 7 deletions apps/skilavottord/ws/src/app/modules/vehicle/vehicle.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,20 @@ export class VehicleService {
// else get all
if (filter.partnerId) {
// Get all sub recycling partners of the municipality
const subRecyclingPartners = await RecyclingPartnerModel.findAll({
where: { municipalityId: filter.partnerId },
})
try {
const subRecyclingPartners = await RecyclingPartnerModel.findAll({
where: { municipalityId: filter.partnerId },
attributes: ['companyId'],
})

partnerIds = [
filter.partnerId,
...subRecyclingPartners.map((partner) => partner.companyId),
]
partnerIds = [
filter.partnerId,
...subRecyclingPartners.map((partner) => partner.companyId),
]
} catch (error) {
this.logger.error('Failed to fetch sub-partners:', error)
throw new Error('Failed to process municipality partners')
}
} else {
partnerIds = null
}
Expand Down

0 comments on commit 4336424

Please sign in to comment.