module Spree module Admin module SolidusMe class AccountsController < BaseController before_action :set_account, only: [:edit, :update, :destroy] def index @accounts = ::SolidusMe::Account.all end def new if ::SolidusMe::Account.any? flash[:error] = "Você só pode ter uma conta Melhor Envio cadastrada" redirect_to admin_solidus_me_accounts_path end @me_account = ::SolidusMe::Account.new end def create me_account = ::SolidusMe::Account.new account_params if me_account.save flash[:success] = "Conta criada com sucesso" redirect_to admin_solidus_me_accounts_path else flash[:error] = me_account.errors.full_messages.join("\n") redirect_to new_admin_solidus_me_account_path end end def edit end def update @me_account.update account_params flash[:success] = "Conta atualizada com sucesso" redirect_to edit_admin_solidus_me_account_path(@me_account.id) end def destroy @me_account.delete redirect_to admin_solidus_me_accounts_path end def authorize code = params[:code] me_account = ::SolidusMe::Account.first authorize_json = MeApi::Client.new.authorize( client_id: me_account.client_id, client_secret: me_account.client_secret, code: code, redirect_url: me_account.redirect_url ).json me_account.update( access_token: authorize_json["access_token"], refresh_token: authorize_json["refresh_token"], token_expires_in: (DateTime.now + authorize_json["expires_in"].seconds).to_s ) redirect_to edit_admin_solidus_me_account_path me_account end private def account_params params.require(:account).permit( :client_id, :client_secret, :access_token, :refresh_token, :redirect_url, :state, :token_expires_in, :services, :postal_code_from ) end def set_account @me_account = ::SolidusMe::Account.find(params[:id]) end end end end end