[SalesForce] Sharing rules on Community Users

I need to create a Account and have a lookup from account to Account as (Partner). Lookup will determine if related Account, related Contacts and Opportunities are visible to these Partner Community Users. I have to create Sharing Rules that enable Partner Account Contacts (as Community Users) to access their related Account and Contact's records.
Please guide me how to create a Sharing rule for this scenario.

Best Answer

Quick caveat to my answer, there could be a way to accomplish this with sharing sets but I don't have enough knowledge of that particular feature to say one way or another. The best way I would go about accomplishing this is by managing sharing with apex. You would need a trigger on account and user that calls a helper class that has method to accept both a list of users and list of accounts passed in from the trigger.

The user method, needed only on insert, would find all child accounts associated with the user's community account and insert a sharing row for each.

The account method is trickier, as it would need to operate in all contexts (update, delete, insert, etc.). This method would need to fire when the parent account is not null (and on update probably be isolated to only when the parent account changes), and you would then find all users associated with the parent account and grant access to the account, contacts, etc. being listed as a new child. This is a relatively complex trigger, as you will need to make it bulk safe, which will require a few maps in your apex method(s). You'll also want to make sure to clean up and delete sharing rows when a parent/child relationship is changed or severed.