The best way to learn a platform is to use a platform

Wow what a week it’s been. First week back from vacation and I’m diving right into a sprint of stuff that needs to be delivered to the customer. My task for the week has been develop a connectivity layer between Salesforce and Dropbox using OAuth. This task has taken me on quite a learning journey.

Now I’ll call myself quite a seasoned programmer but ever since joining Salesforce 9 months ago I’ve had to relearn a lot of stuff. A new programming language in Apex, new framework technologies such as Salesforce Lightning Design System (SLDS) and the Lightning Platform and the entire underlying Salesforce Platform which is enormous. There are just different ways to do stuff… Previously I would have had my choice of any language, technology and framework to solve the issue but now those are kind of given.

Just this afternoon as I was putting the final semi-colons in the core OAuth layer (Apex), the Dropbox specific OAuth layer (Apex), the business specific facade class in front of those layers (Apex) and the management pages for the integration (Lightning) I was reminded of an old quote from an old biochemistry text book of mine: “The best way to learn a subject is the teach the subject”. And that continues to hold true and is equally true when saying “the best way to learn a platform is to build on the platform”. I’ve learned much stuff about Apex and Lightning in the past week. All the cool stuff you can do but also some of the crazy stuff that falls into that “you have have to know that”-category. But for all those things it holds true that you have to spend the time to reap the benefits.

For now I’ll just say that although the Apex language has it quirks and the compiler is definitely showing age (and Salesforce knows this – a new compiler is being developed or at least that’s what I heard in a Dreamforce 2016 session) there is still much so much power in the language. Is there stuff you cannot do? Sure! But there are cool interfaces like System.StubProvider which I read and hear little talk about. The built in support to unit tests and mocking of HTTP requests is awesome and allows you to quickly and easily stub out calls to external services. The runtime screams with performance and I’m pretty impressed about the speed with which my code runs.

Good stuff!

So in closing – I have my OAuth layer done, unit tested and commited. I’ll surely be blogging about how to chose to build it so others may learn from it if they want to spend the time and learn the platform.

Currency conversion in Apex

While waiting for my flight in the lounge tonight I was playing around with currencies in Salesforce because – why not… Conversion between configured currencies are supported in SOQL and Salesforce but only between the configured corporate currency and the users personal currency. But what if you want to convert between an opportunity amount in one currency and into another currency using the configured conversion rates in Salesforce? Well there is no support for this. So as an Apex / SOQL self-assignment I wrote the below class to do that. Basically it lazily reads in configured currencies and allows you to convert between any currency, from a supplied currency to the corporate currency or from a supplied currency to the users own currency. For extra credits it follows the decimal places configured in the Salesforce Setup.

Please note code is provided as-is without any warrenties or guarantees. As a friend always writes — YMMV….

public class CurrencyConverter {
    private Map conversions = null;
    private String corporateIso = null;
    private String userIso = null;

    /**
     * Initialize corporate currencies setup in Setup.
     */
    private void initCorpCurrencies() {
        // build once only
        if (null != this.conversions) return;

        // build map
        this.conversions = new Map();
        final List currencies = [select Id, IsCorporate, IsoCode, ConversionRate, DecimalPlaces from CurrencyType where IsActive=true];
        for (CurrencyType cur : currencies) {
            this.conversions.put(cur.IsoCode, cur);
            if (cur.IsCorporate) this.corporateIso = cur.IsoCode;
        }
    }

    /**
     * Read user currency from users preferences.
     */
    private void initUserCurrency() {
        // load only once
        if (null != this.userIso) return;

        // get user currency ISO and store it
        List users = [SELECT DefaultCurrencyIsoCode FROM User WHERE Id =: UserInfo.getUserId()];
        if (null == users || users.size() != 1) {
           throw new UnknownUserException('Could not find user record for active user ');
        }
        this.userIso = users[0].DefaultCurrencyIsoCode;
    }

    /**
     * Get corporate currency.
     */
    public String getCorporateISO() {
        this.initCorpCurrencies();
        return this.corporateIso;
    }

    /**
     * Get user currency.
     */
    public String getUserISO() {
        this.initUserCurrency();
        return this.userIso;
    }

    /**
     * Convert from supplied currency to corpotate currency.
     */
    public Decimal convertToCorporateCurrency(Decimal value, String fromIso) {
        return this.convert(value, fromIso, this.getCorporateIso());
    }

    /**
     * Convert from supplied currency to users currency.
     */
    public Decimal convertToUserCurrency(Decimal value, String fromIso) {
        return this.convert(value, fromIso, this.getUserISO());
    }

    /**
     * Convert between two known currencies.
     */
    public Decimal convert(Decimal value, String fromIso, String toIso) {
        if (String.isEmpty(fromIso) || String.isEmpty(toIso)) {
            return value;
        }
        this.initCorpCurrencies();

        // ensure valid to/from ISO
        if (!this.conversions.containsKey(fromIso)) {
           throw new UnknownCurrencyException('Unable to find active from ISO currency ');
        }
        if (!this.conversions.containsKey(toIso)) {
           throw new UnknownCurrencyException('Unable to find active to ISO currency ');
        }

        // if same currencies we simply round
        if (fromIso.equalsIgnoreCase(toIso)) {
            return value.setScale(this.conversions.get(fromIso.toUpperCase()).DecimalPlaces, System.RoundingMode.HALF_UP);
        }

        // get values and then rate
        final CurrencyType fromCur = this.conversions.get(fromIso.toUpperCase());
        final Decimal fromRate = fromCur.ConversionRate;
        final CurrencyType toCur = this.conversions.get(toIso.toUpperCase());
        final Decimal toRate = toCur.ConversionRate;
        final Decimal rate = toRate/fromRate;

        // calc
        final Decimal result = value * rate;
        final Decimal resultRounded = result.setScale(toCur.DecimalPlaces, System.RoundingMode.HALF_UP);

        // return
        return resultRounded;
    }

    public class UnknownUserException extends Exception {

    }

    public class UnknownCurrencyException extends Exception {

    }
}