Skip to content

ProjectReferral routing, access and alerts

  • Industry

    Healthcare

  • Cloud

    Apex, LWC, Flow

  • Role

    Lead developer

The problem sharing solves

Referral__c holds patient information, so its organisation-wide default is Private: you see a referral only if you own it, you are above its owner in the role hierarchy, or something shares it with you. A coordinator for the North region must not see the South region’s referrals, and when a referral moves from North to South the North team has to lose it.

Salesforce gives a ladder of tools for this, and the honest advice is to climb only as far as you need:

  1. OWD and the role hierarchy, then criteria-based sharing rules (for example Region = North shares with the North group). Pure configuration. Start here.
  2. Manual sharing by a user. Not suitable for a rule, and the share is dropped when the owner changes.
  3. Apex managed sharing: code writes rows into the object’s __Share table with an Apex sharing reason. The rows survive an owner change, and only code (or an admin with the right permission) removes them.

What gets shared

  1. Referral__cOWD Private. Role hierarchy grants access to managers.
  2. Regional groupEdit while the referral is open, Read once it is closed. Row cause: Regional Coordination.
  3. Assigned coordinatorEdit while open, for cover from another region. Row cause: Coordinator Cover.

Both Apex sharing reasons (Regional_Coordination__c and Coordinator_Cover__c) are defined in Setup on the object. The row cause is what lets the code manage its own rows only: it never touches manual shares, sharing-rule shares or the owner’s implicit access.

The sharing service

The service works in three steps: work out the shares that should exist, load the ones that do exist, and apply the difference. Reconciling like this is idempotent. Run it twice and the second run does nothing, which is exactly what the trigger, the batch and a manual fix-up all need.

Illustrative: rebuilt for this site, not client codeReferralSharingService.cls
public inherited sharing class ReferralSharingService {

  public static void sync(List<Referral__c> referrals) {
      if (referrals.isEmpty()) return;
      Map<String, Referral__Share> desired = desiredShares(referrals);
      ShareStore store = new ShareStore();
      Map<String, Referral__Share> existing = store.load(new Map<Id, Referral__c>(referrals).keySet());

      List<Referral__Share> toInsert = new List<Referral__Share>();
      List<Referral__Share> toUpdate = new List<Referral__Share>();
      for (String key : desired.keySet()) {
          Referral__Share want = desired.get(key);
          Referral__Share have = existing.get(key);
          if (have == null) {
              toInsert.add(want);
          } else if (have.AccessLevel != want.AccessLevel) {
              have.AccessLevel = want.AccessLevel;
              toUpdate.add(have);
          }
      }
      List<Referral__Share> toDelete = new List<Referral__Share>();
      for (String key : existing.keySet()) {
          if (!desired.containsKey(key)) toDelete.add(existing.get(key)); // the stale grants
      }
      store.apply(toInsert, toUpdate, toDelete);
  }
}

The “should exist” half is a pure function of the records. No DML, no sharing, easy to unit test.

Illustrative: rebuilt for this site, not client codeReferralSharingService.cls (desired state)
    @TestVisible
  private static Map<String, Referral__Share> desiredShares(List<Referral__c> referrals) {
      Set<String> regions = new Set<String>();
      for (Referral__c r : referrals) {
          if (r.Region__c != null) regions.add(r.Region__c);
      }
      Map<String, Id> groupIds = CoordinatorSelector.groupIdsByRegion(regions);

      Map<String, Referral__Share> desired = new Map<String, Referral__Share>();
      for (Referral__c r : referrals) {
          Boolean closed = ReferralStatus.isClosed(r.Status__c);
          grant(desired, r, groupIds.get(r.Region__c), closed ? 'Read' : 'Edit',
                Schema.Referral__Share.RowCause.Regional_Coordination__c);
          if (!closed) {
              grant(desired, r, r.Assigned_Coordinator__c, 'Edit',
                    Schema.Referral__Share.RowCause.Coordinator_Cover__c);
          }
      }
      return desired;
  }

  private static void grant(Map<String, Referral__Share> into, Referral__c r,
                            Id principalId, String level, String cause) {
      // No one to grant to, or the owner (who already has full access and cannot be shared with).
      if (principalId == null || principalId == r.OwnerId) return;
      into.put(key(r.Id, principalId, cause),
          new Referral__Share(ParentId = r.Id, UserOrGroupId = principalId, AccessLevel = level, RowCause = cause));
  }

  public static String key(Id parentId, Id principalId, String cause) {
      return parentId + ':' + principalId + ':' + cause;
  }

Because the desired set is computed from the referral’s current region, a move from North to South needs no special “revoke” code. The North group’s row is simply not in the desired set any more, so the reconcile step deletes it, in the same transaction as the region change.

Where without sharing is justified

Writing rows to Referral__Share for a record the running user does not own can fail with INSUFFICIENT_ACCESS_OR_READONLY. An intake agent who saves a referral must still be able to cause the region’s access to be granted. So the DML lives in a small private inner class that runs without sharing, and nothing else in the service does.

Illustrative: rebuilt for this site, not client codeReferralSharingService.cls (writes)
    private static final Set<String> OUR_CAUSES = new Set<String>{
      Schema.Referral__Share.RowCause.Regional_Coordination__c,
      Schema.Referral__Share.RowCause.Coordinator_Cover__c
  };

  // The only without-sharing code in this file: it reads and writes share rows and nothing else,
  // and it only ever touches rows with our own two row causes.
  private without sharing class ShareStore {

      public Map<String, Referral__Share> load(Set<Id> parentIds) {
          Map<String, Referral__Share> found = new Map<String, Referral__Share>();
          for (Referral__Share s : [
              SELECT Id, ParentId, UserOrGroupId, AccessLevel, RowCause
              FROM Referral__Share
              WHERE ParentId IN :parentIds AND RowCause IN :OUR_CAUSES
              WITH SYSTEM_MODE
          ]) {
              found.put(key(s.ParentId, s.UserOrGroupId, s.RowCause), s);
          }
          return found;
      }

      public void apply(List<Referral__Share> toInsert, List<Referral__Share> toUpdate, List<Referral__Share> toDelete) {
          if (!toDelete.isEmpty()) delete toDelete;
          if (!toUpdate.isEmpty()) update toUpdate;
          if (!toInsert.isEmpty()) insert toInsert;
      }
  }

Failures are loud on purpose. If a share cannot be written (say, a group was deleted), the exception rolls back the referral save, because a referral that nobody can open is a worse outcome than a failed save the intake agent can retry.

Recalculating access in bulk

Triggers keep access right for new edits, but some changes never touch a referral: someone is added to a regional group, the routing metadata is corrected, a data load ran with the trigger bypassed. A batch class re-applies the same service to every referral. It is safe to run any time because sync only changes what is wrong.

Illustrative: rebuilt for this site, not client codeReferralShareRecalcBatch.cls
// Without sharing on purpose: this is a system job. It must see every referral, whoever schedules it,
// and it writes nothing but share rows (through ReferralSharingService).
public without sharing class ReferralShareRecalcBatch implements Database.Batchable<SObject>, Database.Stateful {
  private Integer checked = 0;

  public Database.QueryLocator start(Database.BatchableContext bc) {
      return Database.getQueryLocator([
          SELECT Id, OwnerId, Region__c, Status__c, Assigned_Coordinator__c
          FROM Referral__c
      ]);
  }

  public void execute(Database.BatchableContext bc, List<SObject> scope) {
      ReferralSharingService.sync((List<Referral__c>) scope);
      checked += scope.size();
  }

  public void finish(Database.BatchableContext bc) {
      System.debug(LoggingLevel.INFO, 'Referral access recalculated for ' + checked + ' referrals.');
  }
}

Run it from Developer Console or a scheduled job with Database.executeBatch(new ReferralShareRecalcBatch(), 200). A scope of 200 referrals means at most 400 desired share rows and a handful of queries per chunk, well inside the limits. Each chunk is its own transaction, so one bad chunk fails and reports on its own while the others carry on.

Proving it with System.runAs

Access is the thing most likely to break silently, so it gets a test that logs in as people. System.runAs switches the running user, and WITH USER_MODE makes the query honour that user’s sharing and permissions.

Illustrative: rebuilt for this site, not client codeReferralSharingTest.cls
@IsTest
private class ReferralSharingTest {

  @TestSetup
  static void setup() {
      TestDataFactory.createCoordinators('North', 1);
      TestDataFactory.createCoordinators('South', 1);
  }

  private static Integer visibleTo(User u, Id referralId) {
      Integer visible;
      System.runAs(u) {
          visible = [SELECT COUNT() FROM Referral__c WHERE Id = :referralId WITH USER_MODE];
      }
      return visible;
  }

  @IsTest
  static void access_followsTheRegion() {
      User north = TestDataFactory.coordinators('North')[0];
      User south = TestDataFactory.coordinators('South')[0];
      Referral__c referral = TestDataFactory.referrals(1, 'North', true)[0];

      Assert.areEqual(1, visibleTo(north, referral.Id), 'North coordinators open a North referral.');
      Assert.areEqual(0, visibleTo(south, referral.Id), 'South coordinators must not see it.');

      referral.Region__c = 'South';
      update referral;

      Assert.areEqual(0, visibleTo(north, referral.Id), 'The old region loses access in the same save.');
      Assert.areEqual(1, visibleTo(south, referral.Id), 'The new region gains it.');
  }

  @IsTest
  static void closing_dropsTheRegionToReadOnly() {
      Referral__c referral = TestDataFactory.referrals(1, 'North', true)[0];
      referral.Status__c = 'Completed';
      update referral;

      Referral__Share share = [SELECT AccessLevel FROM Referral__Share
                               WHERE ParentId = :referral.Id
                               AND RowCause = :Schema.Referral__Share.RowCause.Regional_Coordination__c];
      Assert.areEqual('Read', share.AccessLevel);
  }
}

The data factory, the 200-record version of this test and the limit assertions are on the Tests page.

Built with the Salesforce Lightning Design System. Not affiliated with Salesforce.

App Launcher