@Override
  public void setup(final TestContainer container) throws Exception {
    instanceActivated = false;
    container.login("1");
    container.addBean(new DataServiceBean());
    container.addBean(new ConfigurationServiceStub());
    container.addBean(new AccountServiceStub());
    container.addBean(Mockito.mock(BillingDataRetrievalServiceLocal.class));
    container.addBean(new PortLocatorBean());
    container.addBean(new LocalizerServiceBean());
    container.addBean(
        new ApplicationServiceStub() {

          @Override
          public void activateInstance(Subscription subscription)
              throws TechnicalServiceNotAliveException, TechnicalServiceOperationException {
            instanceActivated = true;
          }
        });
    container.addBean(new PaymentServiceBean());

    mgr = container.get(DataService.class);
    paymentMgmt = container.get(PaymentService.class);

    runTX(
        new Callable<Void>() {
          @Override
          public Void call() throws Exception {
            createOrganizationRoles(mgr);
            createPaymentTypes(mgr);
            SupportedCountries.createSomeSupportedCountries(mgr);
            return null;
          }
        });
    Organization organization =
        runTX(
            new Callable<Organization>() {
              @Override
              public Organization call() throws Exception {
                Organization organization =
                    Organizations.createOrganization(mgr, OrganizationRoleType.TECHNOLOGY_PROVIDER);
                Organizations.createUserForOrg(mgr, organization, true, "ProvAdmin");
                return organization;
              }
            });
    providerId = organization.getOrganizationId();

    supplier =
        runTX(
            new Callable<Organization>() {
              @Override
              public Organization call() throws Exception {
                Organization organization =
                    Organizations.createOrganization(mgr, OrganizationRoleType.SUPPLIER);
                supplierUser = Organizations.createUserForOrg(mgr, organization, true, "SuppAdmin");
                return organization;
              }
            });
    supplierId = supplier.getOrganizationId();
  }
 private PlatformUser givenUser() {
   Organization org = new Organization();
   org.setOrganizationId(ORGANIZATION_ID);
   PlatformUser user = new PlatformUser();
   user.setUserId(USER_ID);
   user.setOrganization(org);
   return user;
 }
  @Test
  public void testSetPaymentIdentificationForOrganizationValidateActivationOfSubs()
      throws Exception {
    // create org and sub with status suspended
    final Organization org =
        runTX(
            new Callable<Organization>() {
              @Override
              public Organization call() throws Exception {
                Organization org =
                    Organizations.createOrganization(mgr, OrganizationRoleType.CUSTOMER);

                return org;
              }
            });

    OrganizationRefToPaymentType orgPayType = addPaymentTypeToOrganization(org, CREDIT_CARD);
    final PaymentInfo pi = getPaymentInfoForOrg(orgPayType);

    container.login(String.valueOf(supplierUser.getKey()));
    enablePaymentTypes(org.getOrganizationId(), OrganizationRoleType.CUSTOMER);
    Subscription sub =
        runTX(
            new Callable<Subscription>() {
              @Override
              public Subscription call() throws Exception {
                prepareProducts(null);
                Organization supplier = new Organization();
                supplier.setOrganizationId(supplierId);
                supplier = (Organization) mgr.getReferenceByBusinessKey(supplier);
                Subscription sub =
                    Subscriptions.createSubscription(
                        mgr, org.getOrganizationId(), "testProd1", "subId", supplier);
                sub.setStatus(SubscriptionStatus.SUSPENDED);
                sub.setPaymentInfo(pi);
                return sub;
              }
            });
    final long subKey = sub.getKey();

    VOPaymentData pd =
        getData(
            pi.getKey(), "someIdFromPSP", null, null, org.getKey(), pi.getPaymentType().getKey());
    paymentMgmt.savePaymentIdentificationForOrganization(pd);

    // validate subscription status is active
    sub =
        runTX(
            new Callable<Subscription>() {
              @Override
              public Subscription call() throws Exception {
                return mgr.getReference(Subscription.class, subKey);
              }
            });
    Assert.assertEquals(
        "subscription was not activated", SubscriptionStatus.ACTIVE, sub.getStatus());
    Assert.assertTrue(instanceActivated);
  }
  @Test
  public void testSetPaymentIdentificationUpdate() throws Exception {
    Organization org =
        runTX(
            new Callable<Organization>() {
              @Override
              public Organization call() throws Exception {
                Organization org =
                    Organizations.createOrganization(mgr, OrganizationRoleType.CUSTOMER);
                return org;
              }
            });

    OrganizationRefToPaymentType orgPayType = addPaymentTypeToOrganization(org, DIRECT_DEBIT);
    PaymentInfo pi = getPaymentInfoForOrg(orgPayType);

    VOPaymentData pd =
        getData(
            pi.getKey(),
            "initialValueToSet",
            null,
            null,
            org.getKey(),
            pi.getPaymentType().getKey());
    paymentMgmt.savePaymentIdentificationForOrganization(pd);

    PaymentInfo savedPi = findPaymentInfo(pi.getKey());

    Assert.assertEquals(
        "Wrong external identifier for payment info stored",
        "initialValueToSet",
        savedPi.getExternalIdentifier());
    Assert.assertEquals(
        "Wrong payment info type stored",
        DIRECT_DEBIT,
        savedPi.getPaymentType().getPaymentTypeId());

    pd =
        getData(
            savedPi.getKey(),
            "initialValueToSetUpdated",
            null,
            null,
            org.getKey(),
            pi.getPaymentType().getKey());
    paymentMgmt.savePaymentIdentificationForOrganization(pd);

    PaymentInfo updatedPi = findPaymentInfo(pi.getKey());

    Assert.assertEquals(
        "Wrong payment info type updated",
        DIRECT_DEBIT,
        updatedPi.getPaymentType().getPaymentTypeId());

    Assert.assertEquals("Wrong object has been updated", updatedPi.getKey(), savedPi.getKey());
  }
 private PlatformUser givenUser(String locale) {
   Organization org = new Organization();
   org.setOrganizationId(ORGANIZATION_ID);
   org.setName(ORGANIZATION_NAME);
   PlatformUser user = new PlatformUser();
   user.setUserId(USER_ID);
   user.setOrganization(org);
   user.setLocale(locale);
   return user;
 }
  @Test(expected = ConcurrentModificationException.class)
  public void verify_newObjectAlreadySaved() throws Exception {
    // given
    Organization o = new Organization();
    o.setKey(1);
    Organization t = new Organization();
    t.setKey(0);

    // when
    VersionAndKeyValidator.verify(o, t, 0);
  }
  @Test
  public void verify() throws Exception {
    // given
    Organization o = new Organization();
    o.setKey(0);
    Organization t = new Organization();
    t.setKey(0);

    // when
    VersionAndKeyValidator.verify(o, t, 0);
  }
  @Test(expected = SaaSSystemException.class)
  public void verify_differentObjects() throws Exception {
    // given
    Organization o = new Organization();
    o.setKey(1);
    Organization t = new Organization();
    t.setKey(2);

    // when
    VersionAndKeyValidator.verify(o, t, 0);
  }
  private PlatformUser createReseller(Organization custOrg) {
    PlatformUser resellerAdmin = new PlatformUser();

    Organization resellerOrg = new Organization();
    resellerOrg.setOrganizationId(RESELLER_ORGID);
    addRole(resellerOrg, OrganizationRoleType.RESELLER);

    createOrgReference(resellerOrg, custOrg, OrganizationReferenceType.RESELLER_TO_CUSTOMER);

    resellerAdmin.setOrganization(resellerOrg);
    return resellerAdmin;
  }
  private PlatformUser createSupplier(Organization custOrg) {
    PlatformUser supplierAdmin = new PlatformUser();

    Organization supplierOrg = new Organization();
    supplierOrg.setOrganizationId(SUPPLIER_ORGID);
    addRole(supplierOrg, OrganizationRoleType.SUPPLIER);

    createOrgReference(supplierOrg, custOrg, OrganizationReferenceType.SUPPLIER_TO_CUSTOMER);

    supplierAdmin.setOrganization(supplierOrg);
    return supplierAdmin;
  }
  private PlatformUser createBroker(Organization custOrg) {
    PlatformUser brokerAdmin = new PlatformUser();

    Organization brokerOrg = new Organization();
    brokerOrg.setOrganizationId(BROKER_ORGID);
    addRole(brokerOrg, OrganizationRoleType.BROKER);

    createOrgReference(brokerOrg, custOrg, OrganizationReferenceType.BROKER_TO_CUSTOMER);

    brokerAdmin.setOrganization(brokerOrg);
    return brokerAdmin;
  }
 @Before
 public void setup() throws Exception {
   dsMock = mock(DataService.class);
   Organization org = new Organization();
   org.setOrganizationId(ORGANIZATIONID);
   PlatformUser user = new PlatformUser();
   user.setUserId(USERID_1);
   user.setLocale("en");
   user.setOrganization(org);
   when(dsMock.getCurrentUser()).thenReturn(user);
   marketplace = new Marketplace();
   marketplace.setKey(1000l);
   doReturn(marketplace).when(dsMock).getReferenceByBusinessKey(any(Marketplace.class));
 }
  /**
   * Tries to save the passed list of {@link VOUdaDefinition}s. Checks if the passed values are
   * valid and permitted to be accessed.
   *
   * @param defs the {@link VOUdaDefinition}s to save
   * @param caller the calling (owning) {@link Organization}
   * @throws ValidationException in case of an invalid {@link VOUdaDefinition}
   * @throws OrganizationAuthoritiesException in case the calling {@link Organization} has
   *     insufficient roles to create {@link UdaDefinition}s of the set {@link UdaTargetType}.
   * @throws NonUniqueBusinessKeyException in case a {@link UdaDefinition} with the passed id and
   *     target type already exists for the owning {@link Organization}
   * @throws OperationNotPermittedException in case it was tries to update a {@link UdaDefinition}
   *     owned by another {@link Organization}.
   * @throws ConcurrentModificationException in case the {@link UdaDefinition} to update was
   *     concurrently changed
   * @throws ObjectNotFoundException in case on of the {@link UdaDefinition}s to update was not
   *     found
   */
  public void saveUdaDefinitions(List<VOUdaDefinition> defs, Organization caller)
      throws ValidationException, OrganizationAuthoritiesException, NonUniqueBusinessKeyException,
          OperationNotPermittedException, ConcurrentModificationException, ObjectNotFoundException {

    for (VOUdaDefinition voDef : defs) {
      // convert and validate
      UdaDefinition def;
      try {
        def = UdaAssembler.toUdaDefinition(voDef);
        def.setOrganization(caller);
      } catch (ValidationException e) {
        logger.logWarn(
            Log4jLogger.SYSTEM_LOG,
            e,
            LogMessageIdentifier.WARN_INVALID_UDA_DEFINITION,
            voDef.getUdaId());
        ctx.setRollbackOnly();
        throw e;
      }
      // check if target type is allowed for organization
      UdaTargetType type = def.getTargetType();
      if (!type.canSaveDefinition(caller.getGrantedRoleTypes())) {
        String roles = rolesToString(type.getRoles());
        OrganizationAuthoritiesException e =
            new OrganizationAuthoritiesException(
                "Insufficient authorization. Required role(s) '" + roles + "'.",
                new Object[] {roles});
        logger.logWarn(
            Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
            e,
            LogMessageIdentifier.WARN_ORGANIZATION_ROLE_REQUIRED,
            Long.toString(caller.getKey()),
            roles);
        ctx.setRollbackOnly();
        throw e;
      }
      if (voDef.getKey() > 0) {
        updateDefinition(voDef, caller);
      } else {
        createDefinition(def);
      }
      UdaDefinition storedUda = (UdaDefinition) ds.find(def);
      if (storedUda == null) {
        return;
      }
      storeLocalizedAttributeName(storedUda.getKey(), voDef.getName(), voDef.getLanguage());
    }
  }
  /**
   * Returns all {@link UdaDefinition}s that are readable for the passed {@link
   * OrganizationRoleType} depending on their {@link UdaConfigurationType}
   *
   * @param supplier the supplier to get the {@link UdaDefinition}s from
   * @param role the {@link OrganizationRoleType} the definition must be readable for
   * @return
   */
  public List<UdaDefinition> getReadableUdaDefinitionsFromSupplier(
      Organization supplier, OrganizationRoleType role) {

    List<UdaDefinition> udaDefinitions = supplier.getReadableUdaDefinitions(role);

    return udaDefinitions;
  }
  @Test(expected = OperationNotPermittedException.class)
  public void filterCustomerConfiguration_NotPermitted() throws Exception {
    VOOrganizationPaymentConfiguration conf =
        createCustomerConfiguration(noCustomer.getOrganizationId(), PaymentType.INVOICE);

    pcf.filterCustomerConfiguration(Arrays.asList(conf));
  }
  @Test
  public void isDefaultServiceConfigurationChanged_NotDefault() {
    supplier.getSources().get(0).getPaymentTypes().get(0).setUsedAsDefault(false);
    VOPaymentType voPt = createPaymentType(PaymentType.CREDIT_CARD);

    assertTrue(pcf.isDefaultServiceConfigurationChanged(Collections.singleton(voPt)));
  }
  @Test
  public void getTemplateProducts_AllProductTypes() throws Exception {
    // given
    final Product template =
        createTemplateProduct(
            tpSup.getOrganizationId(), "product", "techProduct", ServiceStatus.ACTIVE);
    final Product customerTemplate =
        createCustomerSpecificCopiedProduct(tpSup, template, ServiceStatus.ACTIVE);
    final Product partnerTemplate = createPartnerProductCopy(template, tpSup, ServiceStatus.ACTIVE);
    runTX(
        new Callable<Void>() {
          public Void call() throws Exception {
            Subscriptions.createSubscription(ds, tpSup.getOrganizationId(), template);
            Subscriptions.createSubscription(ds, tpSup.getOrganizationId(), customerTemplate);
            Subscriptions.createPartnerSubscription(
                ds, tpSup.getOrganizationId(), partnerTemplate.getProductId(), "partnerSub", tpSup);
            return null;
          }
        });

    // when
    List<Product> products =
        runTX(
            new Callable<List<Product>>() {
              public List<Product> call() {
                return localService.getTemplateProducts();
              }
            });

    // then
    assertEquals(1, products.size());
    assertEquals(template.getKey(), products.get(0).getKey());
  }
 private void addRole(Organization org, OrganizationRoleType roleType) {
   OrganizationRole role = new OrganizationRole();
   role.setRoleName(roleType);
   OrganizationToRole otr = new OrganizationToRole();
   otr.setOrganizationRole(role);
   org.setGrantedRoles(Collections.singleton(otr));
 }
  @Test
  public void getProductsForVendor_FilterInStatuses() throws Exception {
    // give
    givenBrokerOrg();
    container.login(brokerUserKey, UserRoleType.BROKER_MANAGER.name());

    Product templateInactive =
        createTemplateProduct(
            broker.getOrganizationId(),
            "productInactive",
            "techProductInactive",
            ServiceStatus.INACTIVE);
    Product templateActive =
        createTemplateProduct(
            broker.getOrganizationId(), "productActive", "techProductActive", ServiceStatus.ACTIVE);
    createTemplateProduct(
        broker.getOrganizationId(), "productDeleted", "techProductDeleted", ServiceStatus.DELETED);
    createTemplateProduct(
        broker.getOrganizationId(),
        "productObsolete",
        "techProductObsolete",
        ServiceStatus.OBSOLETE);
    Product templateSuspended =
        createTemplateProduct(
            broker.getOrganizationId(),
            "productSuspended",
            "techProductSuspended",
            ServiceStatus.SUSPENDED);
    // when
    List<Product> products =
        runTX(
            new Callable<List<Product>>() {
              public List<Product> call() {
                return localService.getProductsForVendor();
              }
            });
    // then
    assertEquals(3, products.size());
    assertEquals(templateInactive.getKey(), products.get(0).getKey());
    assertEquals(ServiceStatus.INACTIVE, products.get(0).getStatus());

    assertEquals(templateActive.getKey(), products.get(1).getKey());
    assertEquals(ServiceStatus.ACTIVE, products.get(1).getStatus());

    assertEquals(ServiceStatus.SUSPENDED, products.get(2).getStatus());
    assertEquals(templateSuspended.getKey(), products.get(2).getKey());
  }
  @Test
  public void verify_wrongTemplateVersionInErrorMessage() throws Exception {
    // given
    Organization o = new Organization();
    o.setKey(1);
    Organization t = new Organization();
    t.setKey(0);

    // when
    try {
      VersionAndKeyValidator.verify(o, t, 1);
    } catch (ConcurrentModificationException e) {
      // then
      String versionInMessage =
          e.getMessage().substring(e.getMessage().length() - 1, e.getMessage().length());
      assertEquals("1", versionInMessage);
    }
  }
  @Test
  public void filterCustomerConfiguration_Change() throws Exception {
    VOOrganizationPaymentConfiguration conf =
        createCustomerConfiguration(customer.getOrganizationId(), PaymentType.CREDIT_CARD);
    List<VOOrganizationPaymentConfiguration> input = Arrays.asList(conf);

    List<VOOrganizationPaymentConfiguration> result = pcf.filterCustomerConfiguration(input);

    assertEquals(input, result);
  }
  @Test
  public void filterCustomerConfiguration_NoChange() throws Exception {
    VOOrganizationPaymentConfiguration conf =
        createCustomerConfiguration(customer.getOrganizationId(), PaymentType.INVOICE);

    List<VOOrganizationPaymentConfiguration> result =
        pcf.filterCustomerConfiguration(Arrays.asList(conf));

    assertEquals(new ArrayList<VOOrganizationPaymentConfiguration>(), result);
  }
  private List<Product> givenProducts() {
    List<Product> products = new ArrayList<Product>();

    Product product1 = new Product();
    product1.setKey(PRODUCTKEY_1);
    product1.setProductId(PRODUCTID_1);
    Organization org1 = new Organization();
    org1.setOrganizationId(VENDORID_1);
    product1.setVendor(org1);
    Product product2 = new Product();
    product2.setProductId(PRODUCTID_2);
    product2.setKey(PRODUCTKEY_2);
    Organization org2 = new Organization();
    org2.setOrganizationId(VENDORID_2);
    product2.setVendor(org2);
    products.add(product1);
    products.add(product2);
    return products;
  }
  @Test(expected = PaymentDataException.class)
  public void testSetPaymentIdentificationUpdateForbiddenPaymentType() throws Exception {
    Organization org =
        runTX(
            new Callable<Organization>() {
              @Override
              public Organization call() throws Exception {
                Organization org =
                    Organizations.createOrganization(mgr, OrganizationRoleType.CUSTOMER);
                return org;
              }
            });

    OrganizationRefToPaymentType orgPayType = addPaymentTypeToOrganization(org, INVOICE);
    PaymentInfo pi = getPaymentInfoForOrg(orgPayType);

    VOPaymentData pd =
        getData(pi.getKey(), "externalId", null, null, org.getKey(), pi.getPaymentType().getKey());
    paymentMgmt.savePaymentIdentificationForOrganization(pd);
  }
  @Test
  public void testSetPaymentIdentificationCreation() throws Exception {
    final String localOrgId = "orgForPSPIdTest2";
    Organization org = initPlainOrgWithId(localOrgId);
    OrganizationRefToPaymentType orgPayType = addPaymentTypeToOrganization(org, CREDIT_CARD);
    PaymentInfo pi = getPaymentInfoForOrg(orgPayType);

    String id = "initialValueToSet";
    String provider = "Platin Card";
    String account = "0123456";

    // Create a new PI (Registration)
    VOPaymentData pd =
        getData(0, id, provider, account, org.getKey(), pi.getPaymentType().getKey());
    paymentMgmt.savePaymentIdentificationForOrganization(pd);

    PaymentInfo savedPi = findPaymentInfo(0);
    Assert.assertEquals(
        "Wrong external identifier for payment info stored", id, savedPi.getExternalIdentifier());
    Assert.assertEquals(
        "Wrong payment info type stored", CREDIT_CARD, savedPi.getPaymentType().getPaymentTypeId());
    Assert.assertEquals(provider, savedPi.getProviderName());
    Assert.assertEquals(account, savedPi.getAccountNumber());

    // Now update an existing PI (Reregistration)
    pd = getData(pi.getKey(), id, provider, account, org.getKey(), pi.getPaymentType().getKey());
    pd.setPaymentInfoId(pd.getPaymentInfoId() + "2");
    paymentMgmt.savePaymentIdentificationForOrganization(pd);

    savedPi = findPaymentInfo(pi.getKey());
    Assert.assertEquals(
        "Wrong external identifier for payment info stored", id, savedPi.getExternalIdentifier());
    Assert.assertEquals(
        "Wrong payment info type stored", CREDIT_CARD, savedPi.getPaymentType().getPaymentTypeId());
    Assert.assertEquals(provider, savedPi.getProviderName());
    Assert.assertEquals(account, savedPi.getAccountNumber());
  }
  @Test
  public void getTemplateProducts_AllStates() throws Exception {
    // give
    for (ServiceStatus status : ServiceStatus.values()) {
      createTemplateProduct(
          tpSup.getOrganizationId(), status.name(), "tech_" + status.name(), status);
    }

    // when
    List<Product> products =
        runTX(
            new Callable<List<Product>>() {
              public List<Product> call() {
                return localService.getTemplateProducts();
              }
            });
    // then
    assertEquals(ServiceStatus.values().length, products.size());
  }
 @Test
 public void getProductsForVendor_WithSubscriptionSpecificCopy() throws Exception {
   // given
   givenBrokerOrg();
   container.login(brokerUserKey, UserRoleType.BROKER_MANAGER.name());
   Product template =
       createTemplateProduct(
           broker.getOrganizationId(), "product", "techProduct", ServiceStatus.ACTIVE);
   createSubscriptionSpecificProductCopy(broker, template);
   // when
   List<Product> products =
       runTX(
           new Callable<List<Product>>() {
             public List<Product> call() {
               return localService.getProductsForVendor();
             }
           });
   // then
   assertEquals(1, products.size());
 }
  @Test
  public void getPartnerProductsForTemplate() throws Exception {
    // give
    Organization broker1 = createOrgWithRole(OrganizationRoleType.BROKER);
    Organization broker2 = createOrgWithRole(OrganizationRoleType.BROKER);
    Organization broker3 = createOrgWithRole(OrganizationRoleType.BROKER);
    Organization reseller1 = createOrgWithRole(OrganizationRoleType.RESELLER);
    Organization reseller2 = createOrgWithRole(OrganizationRoleType.RESELLER);

    final Product template =
        createTemplateProduct(
            tpSup.getOrganizationId(), "product", "techProduct", ServiceStatus.ACTIVE);
    createCustomerSpecificCopiedProduct(tpSup, template, ServiceStatus.ACTIVE);
    createSubscriptionSpecificProductCopy(tpSup, template);

    Product brokerActiveProduct = createPartnerProductCopy(template, broker1, ServiceStatus.ACTIVE);
    Product resellerInactiveProduct =
        createPartnerProductCopy(template, reseller1, ServiceStatus.INACTIVE);
    createPartnerProductCopy(template, broker2, ServiceStatus.OBSOLETE);
    createPartnerProductCopy(template, broker3, ServiceStatus.DELETED);
    createPartnerProductCopy(template, reseller2, ServiceStatus.SUSPENDED);

    // when
    List<Product> products =
        runTX(
            new Callable<List<Product>>() {
              public List<Product> call() throws Exception {
                return localService.getPartnerProductsForTemplate(template.getKey());
              }
            });

    // then
    assertEquals(5, products.size());
    assertEquals(brokerActiveProduct.getKey(), products.get(0).getKey());
    assertEquals(resellerInactiveProduct.getKey(), products.get(1).getKey());
  }
  /**
   * Returns all {@link UdaDefinition}s owned by the passed {@link Organization}.
   *
   * @param owner the owner {@link Organization}
   * @return the list of {@link UdaDefinition}s
   */
  public List<UdaDefinition> getOwnUdaDefinitions(Organization owner) {

    List<UdaDefinition> list = owner.getUdaDefinitions();

    return list;
  }
  @Before
  public void setup() throws Exception {
    ds = mock(DataService.class);

    pt = new PaymentType();
    pt.setPaymentTypeId(PaymentType.INVOICE);
    pt.setKey(12345);

    Organization op = new Organization();
    op.setOrganizationId(OrganizationRoleType.PLATFORM_OPERATOR.name());

    supplier = new Organization();
    supplier.setOrganizationId("supplier");
    Organizations.grantOrganizationRole(supplier, OrganizationRoleType.SUPPLIER);

    reseller = new Organization();
    reseller.setOrganizationId("reseller");
    Organizations.grantOrganizationRole(reseller, OrganizationRoleType.RESELLER);

    OrganizationReference ref =
        OrganizationReferences.addReference(
            op, supplier, OrganizationReferenceType.PLATFORM_OPERATOR_TO_SUPPLIER);
    OrganizationReferences.enablePayment(ref, pt)
        .setOrganizationRole(new OrganizationRole(OrganizationRoleType.SUPPLIER));

    ref =
        OrganizationReferences.addReference(
            op, reseller, OrganizationReferenceType.PLATFORM_OPERATOR_TO_RESELLER);
    OrganizationReferences.enablePayment(ref, pt)
        .setOrganizationRole(new OrganizationRole(OrganizationRoleType.RESELLER));

    customer = new Organization();
    customer.setOrganizationId("customer");

    noCustomer = new Organization();
    noCustomer.setOrganizationId("noCustomer");

    ref =
        OrganizationReferences.addReference(
            supplier, customer, OrganizationReferenceType.SUPPLIER_TO_CUSTOMER);
    OrganizationReferences.enablePayment(ref, pt);

    ref =
        OrganizationReferences.addReference(
            reseller, customer, OrganizationReferenceType.RESELLER_TO_CUSTOMER);
    OrganizationReferences.enablePayment(ref, pt);

    product = new Product();
    product.setKey(9876);
    product.setVendor(supplier);
    product.setType(ServiceType.TEMPLATE);
    product.setPaymentTypes(Arrays.asList(new ProductToPaymentType(product, pt)));

    pcf = new PaymentConfigurationFilter(ds);

    user = new PlatformUser();
    user.setOrganization(supplier);

    when(ds.getCurrentUser()).thenReturn(user);
    when(ds.getReference(eq(Product.class), eq(product.getKey()))).thenReturn(product);
    when(ds.getReference(eq(Product.class), eq(PROD_NOT_FOUND_KEY)))
        .thenThrow(new ObjectNotFoundException(ClassEnum.SERVICE, "product"));

    when(ds.getReferenceByBusinessKey(any(DomainObject.class)))
        .thenAnswer(
            new Answer<DomainObject<?>>() {

              public DomainObject<?> answer(InvocationOnMock invocation) throws Throwable {
                Object object = invocation.getArguments()[0];
                if (object instanceof Organization) {
                  Organization o = (Organization) object;
                  if (customer.getOrganizationId().equals(o.getOrganizationId())) {
                    return customer;
                  }
                  if (noCustomer.getOrganizationId().equals(o.getOrganizationId())) {
                    return noCustomer;
                  }
                  throw new ObjectNotFoundException(ClassEnum.ORGANIZATION, o.getOrganizationId());
                }
                throw new ObjectNotFoundException(
                    ClassEnum.ORGANIZATION, object.getClass().getName());
              }
            });
  }