Skip to content

Commit

Permalink
Merge branch 'integrationTesting' into b20884-INT2-fix_prime_weight_t…
Browse files Browse the repository at this point in the history
…ool_tip
  • Loading branch information
JamesHawks224 authored Oct 11, 2024
2 parents ca512f8 + 64275d6 commit 1d04744
Show file tree
Hide file tree
Showing 11 changed files with 232 additions and 33 deletions.
20 changes: 20 additions & 0 deletions pkg/handlers/ghcapi/mto_shipment.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,11 @@ func (h CreateMTOShipmentHandler) Handle(params mtoshipmentops.CreateMTOShipment
Message: handlers.FmtString(err.Error()),
}
return mtoshipmentops.NewCreateMTOShipmentNotFound().WithPayload(&payload), err
case apperror.EventError:
payload := ghcmessages.Error{
Message: handlers.FmtString(err.Error()),
}
return mtoshipmentops.NewUpdateMTOShipmentBadRequest().WithPayload(&payload), err
case apperror.InvalidInputError:
payload := payloadForValidationError(
"Validation errors",
Expand Down Expand Up @@ -309,6 +314,11 @@ func (h UpdateShipmentHandler) Handle(params mtoshipmentops.UpdateMTOShipmentPar
switch err.(type) {
case apperror.NotFoundError:
return mtoshipmentops.NewUpdateMTOShipmentNotFound(), err
case apperror.EventError:
payload := ghcmessages.Error{
Message: handlers.FmtString(err.Error()),
}
return mtoshipmentops.NewUpdateMTOShipmentBadRequest().WithPayload(&payload), err
default:
msg := fmt.Sprintf("%v | Instance: %v", handlers.FmtString(err.Error()), h.GetTraceIDFromRequest(params.HTTPRequest))

Expand Down Expand Up @@ -338,6 +348,11 @@ func (h UpdateShipmentHandler) Handle(params mtoshipmentops.UpdateMTOShipmentPar
switch e := err.(type) {
case apperror.NotFoundError:
return mtoshipmentops.NewUpdateMTOShipmentNotFound(), err
case apperror.EventError:
payload := ghcmessages.Error{
Message: handlers.FmtString(err.Error()),
}
return mtoshipmentops.NewUpdateMTOShipmentBadRequest().WithPayload(&payload), err
case apperror.ForbiddenError:
msg := fmt.Sprintf("%v | Instance: %v", handlers.FmtString(err.Error()), h.GetTraceIDFromRequest(params.HTTPRequest))
return mtoshipmentops.NewUpdateMTOShipmentForbidden().WithPayload(
Expand Down Expand Up @@ -922,6 +937,11 @@ func (h RequestShipmentReweighHandler) Handle(params shipmentops.RequestShipment
switch err.(type) {
case apperror.NotFoundError:
return mtoshipmentops.NewUpdateMTOShipmentNotFound()
case apperror.EventError:
payload := ghcmessages.Error{
Message: handlers.FmtString(err.Error()),
}
return mtoshipmentops.NewUpdateMTOShipmentBadRequest().WithPayload(&payload)
default:
msg := fmt.Sprintf("%v | Instance: %v", handlers.FmtString(err.Error()), h.GetTraceIDFromRequest(params.HTTPRequest))

Expand Down
7 changes: 7 additions & 0 deletions pkg/handlers/internalapi/mto_shipment.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ func (h CreateMTOShipmentHandler) Handle(params mtoshipmentops.CreateMTOShipment
h.GetTraceIDFromRequest(params.HTTPRequest),
),
), err
case apperror.EventError:
return mtoshipmentops.NewUpdateMTOShipmentBadRequest().WithPayload(
payloads.ClientError(handlers.InternalServerErrMessage,
err.Error(),
h.GetTraceIDFromRequest(params.HTTPRequest),
),
), err
case apperror.InvalidInputError:
return mtoshipmentops.
NewCreateMTOShipmentUnprocessableEntity().
Expand Down
5 changes: 3 additions & 2 deletions pkg/models/us_post_region_city.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ package models

import (
"database/sql"
"fmt"
"time"

"github.com/gobuffalo/pop/v6"
"github.com/gobuffalo/validate/v3"
"github.com/gobuffalo/validate/v3/validators"
"github.com/gofrs/uuid"

"github.com/transcom/mymove/pkg/apperror"
)

// UsPostRegionCity represents postal region information retrieved from TRDM
Expand Down Expand Up @@ -49,7 +50,7 @@ func FindCountyByZipCode(db *pop.Connection, zipCode string) (string, error) {
if err != nil {
switch err {
case sql.ErrNoRows:
return "", fmt.Errorf("No county found for provided zip code %s", zipCode)
return "", apperror.NewEventError("No county found for provided zip code "+zipCode+".", err)
default:
return "", err
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/services/address/address_creator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,6 @@ func (suite *AddressSuite) TestAddressCreator() {

suite.Nil(address)
suite.NotNil(err)
suite.Equal("No county found for provided zip code 11111", err.Error())
suite.Equal("No county found for provided zip code 11111.", err.Error())
})
}
2 changes: 1 addition & 1 deletion pkg/services/address/address_updater_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func (suite *AddressSuite) TestAddressUpdater() {

suite.Nil(updatedAddress)
suite.NotNil(err)
suite.Equal("No county found for provided zip code ", err.Error())
suite.Equal("No county found for provided zip code .", err.Error())
})

suite.Run("Fails to update an address because of invalid ID", func() {
Expand Down
28 changes: 24 additions & 4 deletions pkg/services/ppmshipment/ppm_shipment_creator.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,25 @@ func (f *ppmShipmentCreator) createPPMShipment(appCtx appcontext.AppContext, ppm
if ppmShipment.PickupAddress != nil {
address, err = f.addressCreator.CreateAddress(txnAppCtx, ppmShipment.PickupAddress)
if err != nil {
return fmt.Errorf("failed to create pickup address %e", err)
switch err := err.(type) {
case apperror.EventError:
return err
default:
return fmt.Errorf("failed to create pickup address %e", err)
}
}
ppmShipment.PickupAddressID = &address.ID
}

if ppmShipment.SecondaryPickupAddress != nil {
address, err = f.addressCreator.CreateAddress(txnAppCtx, ppmShipment.SecondaryPickupAddress)
if err != nil {
return fmt.Errorf("failed to create secondary pickup address %e", err)
switch err := err.(type) {
case apperror.EventError:
return err
default:
return fmt.Errorf("failed to create secondary pickup address %e", err)
}
}
ppmShipment.SecondaryPickupAddressID = &address.ID
// ensure HasSecondaryPickupAddress property is set true on create
Expand All @@ -87,15 +97,25 @@ func (f *ppmShipmentCreator) createPPMShipment(appCtx appcontext.AppContext, ppm
if ppmShipment.DestinationAddress != nil {
address, err = f.addressCreator.CreateAddress(txnAppCtx, ppmShipment.DestinationAddress)
if err != nil {
return fmt.Errorf("failed to create destination address %e", err)
switch err := err.(type) {
case apperror.EventError:
return err
default:
return fmt.Errorf("failed to create destination address %e", err)
}
}
ppmShipment.DestinationAddressID = &address.ID
}

if ppmShipment.SecondaryDestinationAddress != nil {
address, err = f.addressCreator.CreateAddress(txnAppCtx, ppmShipment.SecondaryDestinationAddress)
if err != nil {
return fmt.Errorf("failed to create secondary delivery address %e", err)
switch err := err.(type) {
case apperror.EventError:
return err
default:
return fmt.Errorf("failed to create secondary destination address %e", err)
}
}
ppmShipment.SecondaryDestinationAddressID = &address.ID
// ensure HasSecondaryDestinationAddress property is set true on create
Expand Down
56 changes: 39 additions & 17 deletions src/components/Office/ShipmentForm/ShipmentForm.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
import { arrayOf, bool, func, number, shape, string, oneOf } from 'prop-types';
import { Field, Formik } from 'formik';
import { generatePath, useNavigate, useParams } from 'react-router-dom';
import { generatePath, useNavigate, useParams, Link } from 'react-router-dom';
import { useQueryClient, useMutation } from '@tanstack/react-query';
import { Alert, Button, Checkbox, Fieldset, FormGroup, Radio } from '@trussworks/react-uswds';
import classNames from 'classnames';
Expand Down Expand Up @@ -49,7 +49,7 @@ import {
updateMoveCloseoutOffice,
dateSelectionIsWeekendHoliday,
} from 'services/ghcApi';
import { SHIPMENT_OPTIONS, SHIPMENT_TYPES } from 'shared/constants';
import { SHIPMENT_OPTIONS, SHIPMENT_TYPES, technicalHelpDeskURL } from 'shared/constants';
import formStyles from 'styles/form.module.scss';
import { AccountingCodesShape } from 'types/accountingCodes';
import { AddressShape, SimpleAddressShape } from 'types/address';
Expand Down Expand Up @@ -103,6 +103,7 @@ const ShipmentForm = (props) => {

const [datesErrorMessage, setDatesErrorMessage] = useState(null);
const [errorMessage, setErrorMessage] = useState(null);
const [errorCode, setErrorCode] = useState(null);
const [successMessage, setSuccessMessage] = useState(null);
const [shipmentAddressUpdateReviewErrorMessage, setShipmentAddressUpdateReviewErrorMessage] = useState(null);

Expand Down Expand Up @@ -185,6 +186,17 @@ const ShipmentForm = (props) => {
});
};

const handleSetError = (error, defaultError) => {
if (error?.response?.body?.message !== null && error?.response?.body?.message !== undefined) {
if (error?.statusCode !== null && error?.statusCode !== undefined) {
setErrorCode(error.statusCode);
}
setErrorMessage(`${error?.response?.body?.message}`);
} else {
setErrorMessage(defaultError);
}
};

const handleSubmitShipmentAddressUpdateReview = async (
shipmentID,
shipmentETag,
Expand Down Expand Up @@ -398,9 +410,9 @@ const ShipmentForm = (props) => {
setErrorMessage(null);
onUpdate('success');
},
onError: () => {
onError: (error) => {
actions.setSubmitting(false);
setErrorMessage(`Something went wrong, and your changes were not saved. Please try again.`);
handleSetError(error, `Something went wrong, and your changes were not saved. Please try again.`);
},
},
);
Expand All @@ -413,9 +425,9 @@ const ShipmentForm = (props) => {
}
}
},
onError: () => {
onError: (error) => {
actions.setSubmitting(false);
setErrorMessage(`Something went wrong, and your changes were not saved. Please try again.`);
handleSetError(error, `Something went wrong, and your changes were not saved. Please try again.`);
},
},
);
Expand Down Expand Up @@ -461,9 +473,9 @@ const ShipmentForm = (props) => {
navigate(advancePath);
onUpdate('success');
},
onError: () => {
onError: (error) => {
actions.setSubmitting(false);
setErrorMessage(`Something went wrong, and your changes were not saved. Please try again.`);
handleSetError(error, `Something went wrong, and your changes were not saved. Please try again.`);
},
},
);
Expand All @@ -486,9 +498,9 @@ const ShipmentForm = (props) => {
onUpdate('success');
}
},
onError: () => {
onError: (error) => {
actions.setSubmitting(false);
setErrorMessage(`Something went wrong, and your changes were not saved. Please try again.`);
handleSetError(error, `Something went wrong, and your changes were not saved. Please try again.`);
},
});
return;
Expand Down Expand Up @@ -590,8 +602,8 @@ const ShipmentForm = (props) => {
onSuccess: () => {
navigate(moveDetailsPath);
},
onError: () => {
setErrorMessage(`Something went wrong, and your changes were not saved. Please try again.`);
onError: (error) => {
handleSetError(error, `Something went wrong, and your changes were not saved. Please try again.`);
},
},
);
Expand All @@ -604,8 +616,8 @@ const ShipmentForm = (props) => {
navigate(moveDetailsPath);
onUpdate('success');
},
onError: () => {
setErrorMessage(`Something went wrong, and your changes were not saved. Please try again.`);
onError: (error) => {
handleSetError(error, `Something went wrong, and your changes were not saved. Please try again.`);
},
});
}
Expand All @@ -615,8 +627,8 @@ const ShipmentForm = (props) => {
onSuccess: () => {
navigate(moveDetailsPath);
},
onError: () => {
setErrorMessage(`Something went wrong, and your changes were not saved. Please try again.`);
onError: (error) => {
handleSetError(error, `Something went wrong, and your changes were not saved. Please try again.`);
},
});
}
Expand Down Expand Up @@ -803,7 +815,17 @@ const ShipmentForm = (props) => {
<NotificationScrollToTop dependency={errorMessage} />
{errorMessage && (
<Alert data-testid="errorMessage" type="error" headingLevel="h4" heading="An error occurred">
{errorMessage}
{errorCode === 400 ? (
<p>
{errorMessage} If the error persists, please try again later, or contact the&nbsp;
<Link to={technicalHelpDeskURL} target="_blank" rel="noreferrer">
Technical Help Desk
</Link>
.
</p>
) : (
<p>{errorMessage}</p>
)}
</Alert>
)}
<NotificationScrollToTop dependency={successMessage} />
Expand Down
33 changes: 33 additions & 0 deletions src/components/Office/ShipmentForm/ShipmentForm.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -1306,6 +1306,39 @@ describe('ShipmentForm component', () => {
expect(mockNavigate).not.toHaveBeenCalled();
});

it('shows a specific error message if the submitHandler returns a specific error message', async () => {
const mockSpecificMessage = 'The data entered no good.';
const mockSubmitHandler = jest.fn((payload, { onError }) => {
// fire onError handler on form
onError({ response: { body: { message: mockSpecificMessage, status: 400 } } });
});

validatePostalCode.mockImplementation(() => Promise.resolve(false));

renderWithRouter(
<ShipmentForm
{...defaultProps}
shipmentType={SHIPMENT_OPTIONS.PPM}
mtoShipment={mockPPMShipment}
submitHandler={mockSubmitHandler}
isCreatePage={false}
/>,
);

const saveButton = screen.getByRole('button', { name: 'Save and Continue' });
expect(saveButton).not.toBeDisabled();
await act(async () => {
await userEvent.click(saveButton);
});

await waitFor(() => {
expect(mockSubmitHandler).toHaveBeenCalled();
});

expect(await screen.findByText(mockSpecificMessage)).toBeInTheDocument();
expect(mockNavigate).not.toHaveBeenCalled();
});

it('shows an error if the submitHandler returns an error when editing a PPM', async () => {
const mockSubmitHandler = jest.fn((payload, { onError }) => {
// fire onError handler on form
Expand Down
Loading

0 comments on commit 1d04744

Please sign in to comment.