Last active
May 5, 2026 09:50
-
-
Save anmolgkv/2716774bacd61aa9f1b128240324c2fd to your computer and use it in GitHub Desktop.
PackageLicenseAssigner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class PackageLicenseAssigner { | |
| public class AssignmentResult { | |
| public Integer requested = 0; | |
| public Integer alreadyAssigned = 0; | |
| public Integer successfullyAssigned = 0; | |
| public Integer failed = 0; | |
| public List<String> errors = new List<String>(); | |
| } | |
| /** | |
| * Assigns a package license to a list of users. | |
| * | |
| * @param userIds Users who should receive the license | |
| * @param packageLicenseId The PackageLicense Id (query from PackageLicense object) | |
| * @return AssignmentResult summary | |
| */ | |
| public static AssignmentResult assignLicense(List<Id> userIds, Id packageLicenseId) { | |
| AssignmentResult result = new AssignmentResult(); | |
| result.requested = userIds.size(); | |
| if (userIds.isEmpty() || packageLicenseId == null) { | |
| return result; | |
| } | |
| // 1. Find users who already have this license so we don't duplicate | |
| Set<Id> alreadyLicensedUserIds = new Set<Id>(); | |
| for (UserPackageLicense upl : [ | |
| SELECT UserId | |
| FROM UserPackageLicense | |
| WHERE PackageLicenseId = :packageLicenseId | |
| AND UserId IN :userIds | |
| ]) { | |
| alreadyLicensedUserIds.add(upl.UserId); | |
| } | |
| result.alreadyAssigned = alreadyLicensedUserIds.size(); | |
| // 2. Build the insert list, skipping users who already have it | |
| List<UserPackageLicense> toInsert = new List<UserPackageLicense>(); | |
| for (Id uid : userIds) { | |
| if (!alreadyLicensedUserIds.contains(uid)) { | |
| toInsert.add(new UserPackageLicense( | |
| UserId = uid, | |
| PackageLicenseId = packageLicenseId | |
| )); | |
| } | |
| } | |
| if (toInsert.isEmpty()) { | |
| return result; | |
| } | |
| // 3. Insert with allOrNone = false so one bad row doesn't fail the batch | |
| Database.SaveResult[] saveResults = Database.ins |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment