Skip to content

Commit

Permalink
update location metafield
Browse files Browse the repository at this point in the history
  • Loading branch information
jamalsoueidan committed May 19, 2024
1 parent e7edb7d commit ab6bc3e
Show file tree
Hide file tree
Showing 3 changed files with 179 additions and 8 deletions.
85 changes: 80 additions & 5 deletions src/functions/customer/services/location/update.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { faker } from "@faker-js/faker";
import { LocationServiceGetCoordinates } from "~/functions/location/services/get-coordinates";
import { createLocation } from "~/library/jest/helpers/location";
import { ensureType } from "~/library/jest/helpers/mock";
import { shopifyAdmin } from "~/library/shopify";
import { UpdateLocationMetaobjectMutation } from "~/types/admin.generated";
import { CustomerLocationServiceUpdate } from "./update";

require("~/library/jest/mongoose/mongodb.jest");
Expand All @@ -9,6 +12,14 @@ jest.mock("~/functions/location/services/get-coordinates", () => ({
LocationServiceGetCoordinates: jest.fn(),
}));

jest.mock("@shopify/admin-api-client", () => ({
createAdminApiClient: () => ({
request: jest.fn(),
}),
}));

const mockRequest = shopifyAdmin.request as jest.Mock;

type LocationServiceGetCoordinatesMock = jest.Mock<
Promise<{
longitude: number;
Expand All @@ -24,33 +35,97 @@ const mockGetCoordinates =

describe("CustomerLocationServiceUpdate", () => {
beforeEach(() => {
mockGetCoordinates.mockClear();
jest.clearAllMocks();
});

it("update should be able to update destination", async () => {
const customerId = faker.number.int();

const document = await createLocation({ customerId });

mockGetCoordinates.mockResolvedValue({
const coordinates = {
longitude: 10.12961271,
latitude: 56.15563438,
fullAddress: "Sigridsvej 45, 1. th, 8220 Brabrand",
fullAddress: "Sigridsvej 4, 1. th, 8220 Brabrand",
city: "Aarhus",
country: "Denmark",
};

mockGetCoordinates.mockResolvedValue(coordinates);

mockRequest.mockResolvedValueOnce({
data: ensureType<UpdateLocationMetaobjectMutation>({
metaobjectUpdate: {
metaobject: {
fields: [
{
value: document.locationType,
key: "location_type",
},
{
value: document.name,
key: "name",
},
{
value: coordinates.fullAddress,
key: "full_address",
},
{
value: coordinates.city,
key: "city",
},
{
value: coordinates.country,
key: "country",
},
{
value: document.originType,
key: "origin_type",
},
{
value: document.distanceForFree.toString(),
key: "distance_for_free",
},
{
value: document.distanceHourlyRate.toString(),
key: "distance_hourly_rate",
},
{
value: document.fixedRatePerKm.toString(),
key: "fixed_rate_per_km",
},
{
value: document.minDriveDistance.toString(),
key: "min_drive_distance",
},
{
value: document.maxDriveDistance.toString(),
key: "max_drive_distance",
},
{
value: document.startFee.toString(),
key: "start_fee",
},
],
},
},
}),
});

const update = await CustomerLocationServiceUpdate(
{ locationId: document._id, customerId },
{
name: "test",
fullAddress: "Sigridsvej 45, 1. th, 8220 Brabrand",
fullAddress: coordinates.fullAddress,
distanceHourlyRate: 5,
fixedRatePerKm: 5,
distanceForFree: 5,
}
);

expect(update.geoLocation.coordinates).toEqual([10.12961271, 56.15563438]);
expect(update.geoLocation.coordinates).toEqual([
coordinates.longitude,
coordinates.latitude,
]);
});
});
93 changes: 90 additions & 3 deletions src/functions/customer/services/location/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import mongoose from "mongoose";
import { ILocation, LocationModel } from "~/functions/location";
import { LocationServiceGetCoordinates } from "~/functions/location/services/get-coordinates";
import { NotFoundError } from "~/library/handler";
import { shopifyAdmin } from "~/library/shopify";
import { StringOrObjectIdType } from "~/library/zod";

export type CustomerLocationUpdateFilterProps = {
Expand All @@ -15,7 +16,20 @@ export const CustomerLocationServiceUpdate = async (
filter: CustomerLocationUpdateFilterProps,
body: CustomerLocationUpdateBody
) => {
if (body.fullAddress) {
const location = await LocationModel.findOne({
_id: new mongoose.Types.ObjectId(filter.locationId),
customerId: filter.customerId,
}).orFail(
new NotFoundError([
{
code: "custom",
message: "LOCATION_NOT_FOUND",
path: ["location"],
},
])
);

if (body.fullAddress && body.fullAddress !== location.fullAddress) {
const result = await LocationServiceGetCoordinates({
fullAddress: body.fullAddress,
});
Expand All @@ -32,13 +46,13 @@ export const CustomerLocationServiceUpdate = async (
};
}

return LocationModel.findOneAndUpdate(
const updateLocation = await LocationModel.findOneAndUpdate(
{
_id: new mongoose.Types.ObjectId(filter.locationId),
customerId: filter.customerId,
},
body,
{ new: true }
{ returnOriginal: false }
).orFail(
new NotFoundError([
{
Expand All @@ -48,4 +62,77 @@ export const CustomerLocationServiceUpdate = async (
},
])
);

if (body.metafieldId) {
await shopifyAdmin.request(UPDATE_LOCATION_METAOBJECT, {
variables: {
id: updateLocation.metafieldId || "",
fields: [
{
key: "location_type",
value: updateLocation.locationType,
},
{
key: "name",
value: updateLocation.name,
},
{
key: "full_address",
value: updateLocation.fullAddress,
},
{
key: "city",
value: updateLocation.city,
},
{
key: "country",
value: updateLocation.country,
},
{
key: "origin_type",
value: updateLocation.originType,
},
{
key: "distance_for_free",
value: updateLocation.distanceForFree.toString(),
},
{
key: "distance_hourly_rate",
value: updateLocation.distanceHourlyRate.toString(),
},
{
key: "fixed_rate_per_km",
value: updateLocation.fixedRatePerKm.toString(),
},
{
key: "min_drive_distance",
value: updateLocation.minDriveDistance.toString(),
},
{
key: "max_drive_distance",
value: updateLocation.maxDriveDistance.toString(),
},
{
key: "start_fee",
value: updateLocation.startFee.toString(),
},
],
},
});
}

return updateLocation;
};

export const UPDATE_LOCATION_METAOBJECT = `#graphql
mutation UpdateLocationMetaobject($id: ID!, $fields: [MetaobjectFieldInput!]!) {
metaobjectUpdate(id: $id, metaobject: {fields: $fields}) {
metaobject {
fields {
value
key
}
}
}
}
` as const;
9 changes: 9 additions & 0 deletions src/types/admin.generated.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ export type CreateLocationMetaobjectMutation = { metaobjectCreate?: AdminTypes.M
& { fields: Array<Pick<AdminTypes.MetaobjectField, 'value' | 'key'>> }
)> }> };

export type UpdateLocationMetaobjectMutationVariables = AdminTypes.Exact<{
id: AdminTypes.Scalars['ID']['input'];
fields: Array<AdminTypes.MetaobjectFieldInput> | AdminTypes.MetaobjectFieldInput;
}>;


export type UpdateLocationMetaobjectMutation = { metaobjectUpdate?: AdminTypes.Maybe<{ metaobject?: AdminTypes.Maybe<{ fields: Array<Pick<AdminTypes.MetaobjectField, 'value' | 'key'>> }> }> };

export type ProductOptionFragmentFragment = (
Pick<AdminTypes.Product, 'id' | 'title' | 'handle' | 'tags'>
& { parentId?: AdminTypes.Maybe<Pick<AdminTypes.Metafield, 'id' | 'value'>>, variants: { nodes: Array<(
Expand Down Expand Up @@ -219,6 +227,7 @@ interface GeneratedMutationTypes {
"#graphql\n mutation CreateUserMetaobject($handle: String!, $fields: [MetaobjectFieldInput!]) {\n metaobjectCreate(\n metaobject: {type: \"user\", fields: $fields, handle: $handle, capabilities: {publishable: {status: ACTIVE}}}\n ) {\n metaobject {\n id\n type\n fields {\n value\n key\n }\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n": {return: CreateUserMetaobjectMutation, variables: CreateUserMetaobjectMutationVariables},
"#graphql\n mutation UpdateUserMetaobject($id: ID!, $fields: [MetaobjectFieldInput!]!) {\n metaobjectUpdate(id: $id, metaobject: {fields: $fields}) {\n metaobject {\n fields {\n value\n key\n }\n }\n }\n }\n": {return: UpdateUserMetaobjectMutation, variables: UpdateUserMetaobjectMutationVariables},
"#graphql\n mutation CreateLocationMetaobject($handle: String!, $fields: [MetaobjectFieldInput!]) {\n metaobjectCreate(\n metaobject: {type: \"location\", fields: $fields, handle: $handle, capabilities: {publishable: {status: ACTIVE}}}\n ) {\n metaobject {\n id\n type\n fields {\n value\n key\n }\n }\n }\n }\n": {return: CreateLocationMetaobjectMutation, variables: CreateLocationMetaobjectMutationVariables},
"#graphql\n mutation UpdateLocationMetaobject($id: ID!, $fields: [MetaobjectFieldInput!]!) {\n metaobjectUpdate(id: $id, metaobject: {fields: $fields}) {\n metaobject {\n fields {\n value\n key\n }\n }\n }\n }\n": {return: UpdateLocationMetaobjectMutation, variables: UpdateLocationMetaobjectMutationVariables},
"#graphql\n #graphql\n fragment ProductOptionFragment on Product {\n id\n title\n handle\n tags\n parentId: metafield(key: \"parentId\", namespace: \"booking\") {\n id\n value\n }\n variants(first: 5) {\n nodes {\n id\n title\n price\n duration: metafield(key: \"duration\", namespace: \"booking\") {\n id\n value\n }\n }\n }\n }\n\n mutation productOptionDuplicate($productId: ID!, $title: String!) {\n productDuplicate(newTitle: $title, productId: $productId) {\n newProduct {\n ...ProductOptionFragment\n }\n }\n }\n": {return: ProductOptionDuplicateMutation, variables: ProductOptionDuplicateMutationVariables},
"#graphql\n #graphql\n fragment ProductOptionFragment on Product {\n id\n title\n handle\n tags\n parentId: metafield(key: \"parentId\", namespace: \"booking\") {\n id\n value\n }\n variants(first: 5) {\n nodes {\n id\n title\n price\n duration: metafield(key: \"duration\", namespace: \"booking\") {\n id\n value\n }\n }\n }\n }\n\n mutation ProductOptionAdd($id: ID!, $metafields: [MetafieldInput!]!, $tags: [String!]!) {\n productUpdate(input: {id: $id, metafields: $metafields, tags: $tags}) {\n product {\n ...ProductOptionFragment\n }\n }\n }\n": {return: ProductOptionAddMutation, variables: ProductOptionAddMutationVariables},
"#graphql\n mutation ProductParentUpdate($id: ID, $metafields: [MetafieldInput!]) {\n productUpdate(input: {id: $id, metafields: $metafields}) {\n product {\n options: metafield(key: \"options\", namespace: \"booking\") {\n id\n }\n }\n }\n }\n": {return: ProductParentUpdateMutation, variables: ProductParentUpdateMutationVariables},
Expand Down

0 comments on commit ab6bc3e

Please sign in to comment.