@PersistenceContext(unitName="blPU")
protected EntityManager em;
@Override
public Integer generateSkusFromProduct(Long productId) {
Product product = catalogService.findProductById(productId);
if (CollectionUtils.isEmpty(product.getProductOptions())) {
return -1;
}
List<List<ProductOptionValue>> allPermutations = generatePermutations(0, new ArrayList<ProductOptionValue>(), product.getProductOptions());
LOG.info("Total number of permutations: " + allPermutations.size());
LOG.info(allPermutations);
//determine the permutations that I already have Skus for
List<List<ProductOptionValue>> previouslyGeneratedPermutations = new ArrayList<List<ProductOptionValue>>();
if (CollectionUtils.isNotEmpty(product.getAdditionalSkus())) {
for (Sku additionalSku : product.getAdditionalSkus()) {
if (CollectionUtils.isNotEmpty(additionalSku.getProductOptionValues())) {
previouslyGeneratedPermutations.add(additionalSku.getProductOptionValues());
}
}
}
List<List<ProductOptionValue>> permutationsToGenerate = new ArrayList<List<ProductOptionValue>>();
for (List<ProductOptionValue> permutation : allPermutations) {
boolean previouslyGenerated = false;
for (List<ProductOptionValue> generatedPermutation : previouslyGeneratedPermutations) {
if (isSamePermutation(permutation, generatedPermutation)) {
previouslyGenerated = true;
break;
}
}
if (!previouslyGenerated) {
permutationsToGenerate.add(permutation);
}
}
int numPermutationsCreated = 0;
//For each permutation, I need them to map to a specific Sku
for (List<ProductOptionValue> permutation : permutationsToGenerate) {
if (permutation.isEmpty()) continue;
Sku permutatedSku = catalogService.createSku();
permutatedSku.setProduct(product);
permutatedSku.setProductOptionValues(permutation);
permutatedSku = catalogService.saveSku(permutatedSku);
product.getAdditionalSkus().add(permutatedSku);
numPermutationsCreated++;
}
if (numPermutationsCreated != 0) {
catalogService.saveProduct(product);
}