import com.gridnine.xtrip.common.model.EntityContainer
import com.gridnine.xtrip.common.model.dict.ContractType
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.helpers.ProfileHelper
import com.gridnine.xtrip.common.model.profile.Contract
import com.gridnine.xtrip.common.model.profile.ContractCustomerInfo
import com.gridnine.xtrip.common.model.profile.ContractIndex
import com.gridnine.xtrip.common.model.profile.PaymentConditionItem
import com.gridnine.xtrip.common.model.system.PaymentType
import com.gridnine.xtrip.common.search.SearchCriterion
import com.gridnine.xtrip.common.search.SearchQuery

String code = "5555555";

SearchQuery query = new SearchQuery();

query.getCriteria().getCriterions().add(SearchCriterion.ne(
        ContractIndex.Property.contractType.name(), ContractType.VENDOR));

List<ContractIndex> indexes =
        EntityStorage.get().search(ContractIndex.class, query).getData();

for (ContractIndex index : indexes) {

    EntityContainer<Contract> contractContainer =
            EntityStorage.get().resolve(index.getSource());

    if (contractContainer != null) {

        boolean save = false;

        Contract contract = contractContainer.getEntity();

        boolean retail = ProfileHelper
                .isOrganizationCode(contract.getSupplier(), code);

        for (ContractCustomerInfo customer : contract.getCustomers()) {

            PaymentConditionItem paymentConditionItem =
                    new PaymentConditionItem();

            paymentConditionItem.setServicePaymentType(
                    retail ? PaymentType.CASH : PaymentType.INVOICE);
            paymentConditionItem.setPaymentTypeByDefault(true);

            customer.getPaymentConditions().getPaymentItems().clear();
            customer.getPaymentConditions().getPaymentItems()
                    .add(paymentConditionItem);

            save = true;
        }

        if (save) {

            contractContainer.getVersionInfo()
                    .setDataSource("update_contract_default_fop_script");

            EntityStorage.get().save(contractContainer, true);
        }
    }
}
