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

(feat): 4246 nnnnat new mocks factory #4276

Merged
merged 26 commits into from
Jun 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
cf5fdac
feat: added simpl-schema-mockdoc as devDep
nnnnat May 18, 2018
9a91ae9
feat: added dataFactory method and object to test-utils
nnnnat May 18, 2018
22d35fc
feat: started creating non-meteor factory utils, added the new util t…
nnnnat May 21, 2018
379256f
feat: removing lodash from dataFactory
nnnnat May 22, 2018
217b304
Merge branch 'feat-4263-nnnnat-non-meteor-schemas' into feat-4246-nnn…
nnnnat May 24, 2018
ac4b0c0
refactor: removed data-facotry code form the Tags schema
nnnnat May 24, 2018
d48d905
refactor: added schema index helper that extends our simple schema op…
nnnnat May 25, 2018
5c793f6
chore: commented out unused schema helper functions, should be remove…
nnnnat May 25, 2018
448e37d
feat: cleaned up temp dataFactory code, created a new factory test-ut…
nnnnat May 25, 2018
4256f62
test: testing out the new Factory mock
nnnnat May 25, 2018
94ff006
refactor: removed seed from getMockDoc helper function so _id will be…
nnnnat May 25, 2018
3fa9865
test: replaced old mock tags setup with the new Factory.Tag.makeMany,…
nnnnat May 25, 2018
1b0075a
Merge branch 'release-2.0.0' into feat-4246-nnnnat-new-mocks-factory
nnnnat May 25, 2018
b69793c
feat: updated Factory makeOne function to call a provided function as…
nnnnat May 29, 2018
37c7660
test: tags integration test now using mockTags from the Factory object
nnnnat May 29, 2018
c77c81a
feat: added product cart orders inventory schemas back to the main sc…
nnnnat May 30, 2018
9f5c09b
refactor: removed Reaction.getSlug call for handl updates from produc…
nnnnat May 30, 2018
b16c535
feat: created a new catalog util function that returns true if a prod…
nnnnat May 30, 2018
bfbd042
refactor: removed custom function for inventoryQuantity from Product …
nnnnat May 30, 2018
be0308c
test: Tags integration & query test now using the mocks Factory test …
nnnnat May 30, 2018
206dc2a
chore: fixed linting issues
nnnnat May 30, 2018
3654f68
refactor: removed the Reaction.getSlug calls to just use the provided…
nnnnat Jun 1, 2018
50b0197
chore: removed temp data-factory code, added @reactioncommerce/data-f…
nnnnat Jun 1, 2018
291faa4
Merge branch 'release-1.13.0' into feat-4246-nnnnat-new-mocks-factory
nnnnat Jun 1, 2018
1f43f71
refactor: removed autoValue helper functions from schemas/helpers.js
nnnnat Jun 2, 2018
c9117f7
docs: updated comments in a few files, removed unneeded test
nnnnat Jun 4, 2018
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
82 changes: 1 addition & 81 deletions imports/collections/schemas/helpers.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import Random from "@reactioncommerce/random";
import { Meteor } from "meteor/meteor";
import { Reaction } from "/lib/api";
import { Shops } from "/lib/collections";

/**
* @name createdAtAutoValue
Expand Down Expand Up @@ -37,48 +35,6 @@ export function updatedAtAutoValue() {
return new Date();
}

/**
* @name shopIdAutoValue
* @memberof Schemas
* @method
* @summary Helper method used for schema injection autoValue
* @example autoValue: shopIdAutoValue
* @return {String} current shopId
*/
export function shopIdAutoValue() {
// we should always have a shopId
if (this.isSet && Meteor.isServer) {
return this.value;
} else if ((Meteor.isServer && !this.isUpdate) || (Meteor.isClient && this.isInsert)) {
return Reaction.getShopId();
}
return this.unset();
}

/**
* @name shopIdAutoValueForCart
* @memberof Schemas
* @method
* @summary Helper method copy of shopIdAutoValue with modification for Cart
* @example autoValue: shopIdAutoValue
* @return {String} shopId
*/
export function shopIdAutoValueForCart() {
// we should always have a shopId
if (this.isSet && Meteor.isServer) {
return this.value;
} else if ((Meteor.isServer && !this.isUpdate) || (Meteor.isClient && this.isInsert)) {
let shopId = Reaction.getPrimaryShopId();
const marketplaceSettings = Reaction.getMarketplaceSettings();

if (marketplaceSettings && marketplaceSettings.public && marketplaceSettings.public.merchantCart === true) {
shopId = Reaction.getShopId();
}
return shopId;
}
return this.unset();
}

/**
* @name schemaIdAutoValue
* @memberof Schemas
Expand All @@ -90,44 +46,8 @@ export function shopIdAutoValueForCart() {
export function schemaIdAutoValue() {
if (this.isSet && Meteor.isServer) {
return this.value;
} else if ((Meteor.isServer && this.operator !== "$pull") ||
(Meteor.isClient && this.isInsert)) {
} else if ((Meteor.isServer && this.operator !== "$pull") || (Meteor.isClient && this.isInsert)) {
return Random.id();
}
return this.unset();
}

/**
* @name shopDefaultCountry
* @memberof Schemas
* @method
* @summary Helper method used for schema injection autoValue
* @example autoValue: shopDefaultCountry
* @return {String} country value from default shop
*/
export function shopDefaultCountry() {
try {
// Check to see if this is client or server, and the type of update being performed
if (this.isSet && Meteor.isServer) {
return this.value;
} else if ((Meteor.isServer && !this.isUpdate) || (Meteor.isClient && this.isInsert)) {
// Find the current shop
const shop = Shops.findOne({
_id: Reaction.getShopId()
});

// Find the current shops primary shipping address
if (shop && shop.addressBook) {
const defaultShippingAddress = shop.addressBook.find((address) => address.isShippingDefault === true);

// return the shops country to auto-populate the Country of Origin field in the scheme
return defaultShippingAddress.country;
}

return this.value;
}
return this.unset();
} catch (e) {
return this.value;
}
}
2 changes: 2 additions & 0 deletions imports/collections/schemas/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
* @namespace Schemas
*/

import "./schemaIndex";

export * from "./accounts";
export * from "./address";
export * from "./assets";
Expand Down
12 changes: 1 addition & 11 deletions imports/collections/schemas/products.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import SimpleSchema from "simpl-schema";
import { Meteor } from "meteor/meteor";
import { registerSchema } from "@reactioncommerce/schemas";
import { ReactionProduct } from "/lib/api";
import { createdAtAutoValue, updatedAtAutoValue } from "./helpers";
import { Event } from "./event";
import { Metafield } from "./metafield";
Expand Down Expand Up @@ -243,16 +242,7 @@ export const ProductVariant = new SimpleSchema({
type: SimpleSchema.Integer,
label: "Quantity",
optional: true,
defaultValue: 0,
custom() {
if (Meteor.isClient) {
if (this.siblingField("type").value !== "inventory") {
if (ReactionProduct.checkChildVariants(this.docId) === 0 && !this.value) {
return SimpleSchema.ErrorTypes.REQUIRED;
}
}
}
}
defaultValue: 0
},
"minOrderQuantity": {
label: "Minimum order quantity",
Expand Down
9 changes: 9 additions & 0 deletions imports/collections/schemas/schemaIndex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import SimpleSchema from "simpl-schema";

// These options are added by the `aldeed:schema-index` Meteor package, but because that
// is a Meteor package and we also load the schemas in a non-Meteor Node app, we need to do it here.
SimpleSchema.extendOptions([
"index", // one of Number, String, Boolean
"unique", // Boolean
"sparse" // Boolean
]);
21 changes: 18 additions & 3 deletions imports/plugins/core/catalog/server/methods/catalog.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Media } from "/imports/plugins/core/files/server";
import rawCollections from "/imports/collections/rawCollections";
import getProductPriceRange from "../no-meteor/utils/getProductPriceRange";
import getVariants from "../no-meteor/utils/getVariants";
import hasChildVariant from "../no-meteor/utils/hasChildVariant";
import isSoldOut from "../no-meteor/utils/isSoldOut";
import isLowQuantity from "../no-meteor/utils/isLowQuantity";
import isBackorder from "../no-meteor/utils/isBackorder";
Expand Down Expand Up @@ -314,11 +315,20 @@ function flushQuantity(id) {
* @return {Object} product - new product
*/
function createProduct(props = null) {
const finalProps = props || {};
if (finalProps.type !== "variant" && !finalProps.handle) {
if (typeof finalProps.title === "string" && finalProps.title.length) {
finalProps.handle = Reaction.getSlug(finalProps.title);
} else {
finalProps.handle = Random.id();
}
}

const _id = Products.insert(
{
shopId: Reaction.getShopId(),
type: "simple",
...props
...finalProps
},
{
validate: false
Expand Down Expand Up @@ -963,6 +973,12 @@ Meteor.methods({
throw new Meteor.Error("access-denied", "Access Denied");
}

if (field === "inventoryQuantity" && value === "") {
if (!Promise.await(hasChildVariant(_id, rawCollections))) {
throw new Meteor.Error("invalid", "Inventory Quantity is required when no child variants");
}
}

const { type } = doc;
let update;
// handle booleans with correct typing
Expand All @@ -973,7 +989,7 @@ Meteor.methods({
update = {
// TODO: write function to ensure new handle is unique.
// Should be a call similar to the line below.
[field]: createHandle(value, _id) // handle should be unique
[field]: createHandle(Reaction.getSlug(value), _id) // handle should be unique
};
} else if (field === "title" && doc.handle === doc._id) {
// update handle once title is set
Expand All @@ -989,7 +1005,6 @@ Meteor.methods({

// we need to use sync mode here, to return correct error and result to UI
let result;

try {
result = updateCatalogProduct(
this.userId,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
*
* @method hasChildVariant
* @summary Return true if a Product or Variant has at least 1 child Product that is visible and not deleted.
* @param {string} productOrVariantId - A Product or Product Variant ID.
* @param {Object} collections - Raw mongo collections.
* @return {Promise<boolean>} True if Product has a child.
*/
export default async function hasChildVariant(productOrVariantId, collections) {
const { Products } = collections;
const child = await Products.findOne({
ancestors: productOrVariantId,
type: "variant",
isVisible: true,
isDeleted: { $ne: true }
});
return !!child;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import mockContext from "/imports/test-utils/helpers/mockContext";
import hasChildVariant from "./hasChildVariant";

const mockCollections = { ...mockContext.collections };

const internalShopId = "123";
const internalCatalogProductId = "999";
const internalProductId = "999";
const internalVariantIds = ["875", "874"];

const createdAt = new Date("2018-04-16T15:34:28.043Z");
const updatedAt = new Date("2018-04-17T15:34:28.043Z");

const mockVariants = [
{
_id: internalVariantIds[0],
ancestors: [internalCatalogProductId],
barcode: "barcode",
createdAt,
height: 0,
index: 0,
inventoryManagement: true,
inventoryPolicy: false,
isLowQuantity: true,
isSoldOut: false,
isDeleted: false,
isVisible: true,
length: 0,
lowInventoryWarningThreshold: 0,
metafields: [
{
value: "value",
namespace: "namespace",
description: "description",
valueType: "valueType",
scope: "scope",
key: "key"
}
],
minOrderQuantity: 0,
optionTitle: "Untitled Option",
originCountry: "US",
price: 0,
shopId: internalShopId,
sku: "sku",
taxable: true,
taxCode: "0000",
taxDescription: "taxDescription",
title: "Small Concrete Pizza",
updatedAt,
variantId: internalVariantIds[0],
weight: 0,
width: 0
},
{
_id: internalVariantIds[1],
ancestors: [internalCatalogProductId, internalVariantIds[0]],
barcode: "barcode",
height: 2,
index: 0,
inventoryManagement: true,
inventoryPolicy: true,
isLowQuantity: true,
isSoldOut: false,
isDeleted: false,
isVisible: true,
length: 2,
lowInventoryWarningThreshold: 0,
metafields: [
{
value: "value",
namespace: "namespace",
description: "description",
valueType: "valueType",
scope: "scope",
key: "key"
}
],
minOrderQuantity: 0,
optionTitle: "Awesome Soft Bike",
originCountry: "US",
price: 992.0,
shopId: internalShopId,
sku: "sku",
taxable: true,
taxCode: "0000",
taxDescription: "taxDescription",
title: "One pound bag",
variantId: internalVariantIds[1],
weight: 2,
width: 2
}
];

test("expect true when product has a child", async () => {
mockCollections.Products.findOne.mockReturnValueOnce(Promise.resolve(mockVariants[0]));
const spec = await hasChildVariant(internalProductId, mockCollections);
expect(spec).toBe(true);
});

test("expect false when product does not a child", async () => {
mockCollections.Products.findOne.mockReturnValueOnce(Promise.resolve(null));
const spec = await hasChildVariant(internalVariantIds[1], mockCollections);
expect(spec).toBe(false);
});
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
import tagsResolver from "./tags";
import getFakeMongoCursor from "/imports/test-utils/helpers/getFakeMongoCursor";
import Factory from "/imports/test-utils/helpers/factory";

const base64ID = "cmVhY3Rpb24vc2hvcDoxMjM="; // reaction/shop:123

const mockTags = [
{ _id: "a1", name: "Men" },
{ _id: "b2", name: "Women" },
{ _id: "c3", name: "Children" }
];

const mockTags = Factory.Tag.makeMany(3, { _id: (i) => (i + 100).toString() });
const mockTagsQuery = getFakeMongoCursor("Tags", mockTags);

test("calls queries.tags and returns a partial connection", async () => {
const tags = jest.fn().mockName("queries.tags").mockReturnValueOnce(Promise.resolve(mockTagsQuery));
const tags = jest
.fn()
.mockName("queries.tags")
.mockReturnValueOnce(Promise.resolve(mockTagsQuery));

const result = await tagsResolver({}, { shopId: base64ID }, {
queries: { tags }
});
const result = await tagsResolver(
{},
{ shopId: base64ID },
{
queries: { tags }
}
);

expect(result).toEqual({
nodes: mockTags,
pageInfo: {
endCursor: "c3",
endCursor: "102",
hasNextPage: false,
hasPreviousPage: false,
startCursor: "a1"
startCursor: "100"
},
totalCount: 3
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,7 @@ const wrapComponent = (Comp) => (
}

handleProductFieldSave = (productId, fieldName, value) => {
let updateValue = value;
// special case, slugify handles.
if (fieldName === "handle") {
updateValue = Reaction.getSlug(value);
}
Meteor.call("products/updateProductField", productId, fieldName, updateValue, (error) => {
Meteor.call("products/updateProductField", productId, fieldName, value, (error) => {
if (error) {
Alerts.toast(error.message, "error");
this.forceUpdate();
Expand Down
Loading