All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.sphere.internal.CustomerServiceImpl Maven / Gradle / Ivy

There is a newer version: 0.72.1
Show newest version
package io.sphere.internal;

import com.google.common.base.Strings;
import io.sphere.client.*;
import io.sphere.client.exceptions.*;
import io.sphere.client.model.QueryResult;
import io.sphere.client.model.VersionedId;
import io.sphere.client.shop.ApiMode;
import io.sphere.client.shop.CustomerService;
import io.sphere.client.shop.SignInResult;
import io.sphere.client.shop.model.Customer;
import io.sphere.client.shop.model.CustomerName;
import io.sphere.client.shop.model.CustomerToken;
import io.sphere.client.shop.model.CustomerUpdate;
import io.sphere.internal.command.Command;
import io.sphere.internal.command.CustomerCommands;
import io.sphere.internal.command.UpdateCommand;
import io.sphere.internal.request.RequestFactory;
import static io.sphere.internal.util.Util.getSingleError;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import org.codehaus.jackson.type.TypeReference;

public class CustomerServiceImpl extends ProjectScopedAPI implements CustomerService {
    private final RequestFactory requestFactory;

    public CustomerServiceImpl(RequestFactory requestFactory, ProjectEndpoints endpoints) {
        super(endpoints);
        this.requestFactory = requestFactory;
    }

    @Override public FetchRequest byId(String id) {
        return requestFactory.createFetchRequest(
                endpoints.customers.byId(id),
                Optional.absent(),
                new TypeReference() {});
    }

    @Override public FetchRequest byToken(String token) {
        return requestFactory.createFetchRequest(
                endpoints.customers.byToken(token),
                Optional.absent(),
                new TypeReference() {});
    }

    @Deprecated
    @Override public QueryRequest all() {
        return query();
    }

    @Override public QueryRequest query() {
        return requestFactory.createQueryRequest(
                endpoints.customers.root(),
                Optional.absent(),
                new TypeReference>() {});
    }

    /** Handles DuplicateField('email') on sign-up. */
    private Function handleDuplicateEmail(final String email) {
        return new Function() {
            public SphereException apply(SphereBackendException e) {
                SphereError.DuplicateField err = getSingleError(e, SphereError.DuplicateField.class);
                if (err != null && err.getField().equals("email")) {
                    return new EmailAlreadyInUseException(email);
                }
                return null;
            }
        };
    }

    /** Handles InvalidCredentials on sign-in. */
    private Function handleInvalidCredentials() {
        return new Function() {
            public SphereException apply(SphereBackendException e) {
                SphereError.InvalidCredentials err = getSingleError(e, SphereError.InvalidCredentials.class);
                if (err != null) {
                    return new InvalidCredentialsException();
                }
                return null;
            }
        };
    }

    @Override public CommandRequest signUp(String email, String password, CustomerName name) {
        CommandRequest signUpCmd = createSignInResultCommandRequest(
                endpoints.customers.root(),
                new CustomerCommands.CreateCustomer(email, password, name.getFirstName(), name.getLastName(),
                        name.getMiddleName(), name.getTitle()));
        return signUpCmd.withErrorHandling(handleDuplicateEmail(email));
    }


    @Override public CommandRequest signUp(String email, String password, CustomerName name, String cartId) {
        if (Strings.isNullOrEmpty(cartId)) throw new IllegalArgumentException("cartId can't be empty.");
        CommandRequest signUpCmd = createSignInResultCommandRequest(
                endpoints.customers.root(),
                new CustomerCommands.CreateCustomerWithCart(email, password, name.getFirstName(), name.getLastName(),
                        name.getMiddleName(), name.getTitle(), cartId));
        return signUpCmd.withErrorHandling(handleDuplicateEmail(email));
    }

    @Override public CommandRequest signIn(String email, String password) {
        CommandRequest signInCmd = createSignInResultCommandRequest(
                endpoints.login(),
                new CustomerCommands.SignIn(email, password));
        return signInCmd.withErrorHandling(handleInvalidCredentials());
    }

    @Override public CommandRequest signIn(String email, String password, String cartId) {
        if (Strings.isNullOrEmpty(cartId)) throw new IllegalArgumentException("cartId can't be empty.");
        CommandRequest signInCmd = createSignInResultCommandRequest(
                endpoints.login(),
                new CustomerCommands.SignInWithCart(email, password, cartId));
        return signInCmd.withErrorHandling(handleInvalidCredentials());
    }

    @Override public CommandRequest changePassword(VersionedId customerId, String currentPassword, String newPassword) {
        CommandRequest changePasswordCmd = requestFactory.createCommandRequest(
                endpoints.customers.changePassword(),
                new CustomerCommands.ChangePassword(customerId.getId(), customerId.getVersion(), currentPassword, newPassword),
                new TypeReference() {
                });
        return changePasswordCmd.withErrorHandling(new Function() {
            public SphereException apply(SphereBackendException e) {
                if (getSingleError(e, SphereError.InvalidCurrentPassword.class) != null) {
                    return new InvalidPasswordException();
                }
                return null;
            }
        });
    }

    @Override public CommandRequest update(VersionedId customerId, CustomerUpdate customerUpdate) {
        return createCommandRequest(
                endpoints.customers.byId(customerId.getId()),
                new UpdateCommand(customerId.getVersion(), customerUpdate));
    }

    @Override public CommandRequest createPasswordResetToken(String email) {
        return createCustomerTokenCommandRequest(
                endpoints.customers.createPasswordResetToken(),
                new CustomerCommands.CreatePasswordResetToken(email));
    }

    @Override public CommandRequest createPasswordResetToken(String email, int ttlMinutes) {
        return createCustomerTokenCommandRequest(
                endpoints.customers.createPasswordResetToken(),
                new CustomerCommands.CreatePasswordResetToken(email, ttlMinutes));
    }

    @Override public CommandRequest resetPassword(VersionedId customerId, String token, String newPassword) {
        return createCommandRequest(
                endpoints.customers.resetPassword(),
                new CustomerCommands.ResetCustomerPassword(customerId.getId(), customerId.getVersion(), token, newPassword));
    }

    @Override public CommandRequest createEmailVerificationToken(VersionedId customerId, int ttlMinutes) {
        return createCustomerTokenCommandRequest(
                endpoints.customers.createEmailVerificationToken(),
                new CustomerCommands.CreateEmailVerificationToken(customerId.getId(), customerId.getVersion(), ttlMinutes));
    }

    @Override public CommandRequest confirmEmail(VersionedId customerId, String token) {
        return createCommandRequest(
                endpoints.customers.confirmEmail(),
                new CustomerCommands.VerifyCustomerEmail(customerId.getId(), customerId.getVersion(), token));
    }

    // ---------------------------------------
    // Helpers to save some repetitive code
    // ---------------------------------------

    private CommandRequest createCommandRequest(String url, Command command) {
        return requestFactory.createCommandRequest(url, command, new TypeReference() {});
    }

    /** Used by both signIn and signUp, the result type is the same. */
    private CommandRequest createSignInResultCommandRequest(String url, Command command) {
        return requestFactory.createCommandRequest(url, command, new TypeReference() {});
    }

    private CommandRequest createCustomerTokenCommandRequest(String url, Command command) {
        return requestFactory.createCommandRequest(url, command, new TypeReference() {});
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy