|
| 1 | +/* |
| 2 | + * Copyright ish group pty ltd 2024. |
| 3 | + * |
| 4 | + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. |
| 5 | + * |
| 6 | + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. |
| 7 | + */ |
| 8 | + |
| 9 | +package ish.oncourse.server.services.chargebee |
| 10 | + |
| 11 | +import com.chargebee.Environment |
| 12 | +import com.chargebee.models.Subscription |
| 13 | +import com.chargebee.models.Usage |
| 14 | +import com.google.inject.Inject |
| 15 | +import ish.common.chargebee.ChargebeePropertyType |
| 16 | +import ish.oncourse.server.ICayenneService |
| 17 | +import ish.oncourse.server.PreferenceController |
| 18 | +import ish.oncourse.server.cayenne.Script |
| 19 | +import ish.oncourse.server.messaging.MessageService |
| 20 | +import ish.oncourse.server.scripting.api.EmailService |
| 21 | +import ish.oncourse.server.scripting.api.EmailSpec |
| 22 | +import ish.oncourse.server.scripting.api.MessageSpec |
| 23 | +import ish.oncourse.server.services.AuditService |
| 24 | +import ish.oncourse.server.services.chargebee.property.ChargebeePropertyProcessor |
| 25 | +import ish.oncourse.server.services.chargebee.property.ChargeebeeProcessorFactory |
| 26 | +import ish.oncourse.types.AuditAction |
| 27 | +import org.apache.cayenne.query.ObjectSelect |
| 28 | +import org.apache.logging.log4j.LogManager |
| 29 | +import org.apache.logging.log4j.Logger |
| 30 | +import org.quartz.DisallowConcurrentExecution |
| 31 | +import org.quartz.Job |
| 32 | +import org.quartz.JobExecutionContext |
| 33 | +import org.quartz.JobExecutionException |
| 34 | + |
| 35 | +import java.sql.Timestamp |
| 36 | +import java.time.Instant |
| 37 | + |
| 38 | +@DisallowConcurrentExecution |
| 39 | +class ChargebeeUploadJob implements Job { |
| 40 | + private static final Logger logger = LogManager.getLogger() |
| 41 | + |
| 42 | + @Inject |
| 43 | + private ICayenneService cayenneService |
| 44 | + |
| 45 | + @Inject |
| 46 | + private ChargebeeService chargebeeService |
| 47 | + |
| 48 | + @Inject |
| 49 | + private MessageService messageService |
| 50 | + |
| 51 | + @Inject |
| 52 | + private PreferenceController preferenceController |
| 53 | + |
| 54 | + @Inject |
| 55 | + private AuditService auditService |
| 56 | + |
| 57 | + private static Subscription subscription = null |
| 58 | + |
| 59 | + |
| 60 | + @Override |
| 61 | + void execute(JobExecutionContext context) throws JobExecutionException { |
| 62 | + logger.warn("ChargebeeUploadJob started") |
| 63 | + |
| 64 | + def addons = chargebeeService.getAllowedAddons() |
| 65 | + if(addons.isEmpty()) { |
| 66 | + logger.warn("ChargebeeUploadJob is rejected due to allowed addons not configured for this college") |
| 67 | + return |
| 68 | + } |
| 69 | + |
| 70 | + def site = chargebeeService.configOf(ChargebeePropertyType.SITE) |
| 71 | + def apiKey = chargebeeService.configOf(ChargebeePropertyType.API_KEY) |
| 72 | + |
| 73 | + |
| 74 | + if (site == null || apiKey == null) { |
| 75 | + String error = "Try to use chargebee, but its configs don't have necessary field (site or api key)" |
| 76 | + logger.error(error) |
| 77 | + throw new RuntimeException(error) |
| 78 | + } |
| 79 | + |
| 80 | + Calendar aCalendar = Calendar.getInstance() |
| 81 | + aCalendar.add(Calendar.MONTH, -1) |
| 82 | + aCalendar.set(Calendar.DATE, 1) |
| 83 | + def firstDateOfPreviousMonth = aCalendar.getTime() |
| 84 | + |
| 85 | + aCalendar.add(Calendar.MONTH, 1) |
| 86 | + aCalendar.set(Calendar.DATE, 1) |
| 87 | + def firstDateOfCurrentMonth = aCalendar.getTime() |
| 88 | + |
| 89 | + def propertiesToUpload = ChargebeePropertyType.getItems() |
| 90 | + .findAll {addons.contains(it.getDbPropertyName())} |
| 91 | + |
| 92 | + logger.warn("Chargebee start date including $firstDateOfPreviousMonth , end date $firstDateOfCurrentMonth") |
| 93 | + |
| 94 | + try { |
| 95 | + if(!chargebeeService.localMode) |
| 96 | + Environment.configure(site, apiKey) |
| 97 | + |
| 98 | + propertiesToUpload.each { type -> |
| 99 | + def property = ChargeebeeProcessorFactory.valueOf(type, firstDateOfPreviousMonth, firstDateOfCurrentMonth) |
| 100 | + uploadUsageToSite(property) |
| 101 | + } |
| 102 | + } catch (Exception e) { |
| 103 | + logger.catching(e) |
| 104 | + throw e |
| 105 | + } |
| 106 | + |
| 107 | + logger.warn("ChargeebeeUploadJob executed successfully") |
| 108 | + } |
| 109 | + |
| 110 | + |
| 111 | + private void uploadUsageToSite(ChargebeePropertyProcessor propertyProcessor) { |
| 112 | + if(propertyProcessor.type == null) { |
| 113 | + throw new IllegalArgumentException("Try to upload chargebee usage without item type") |
| 114 | + } |
| 115 | + |
| 116 | + String itemPriceId = chargebeeService.configOf(propertyProcessor.type) |
| 117 | + if(itemPriceId == null) |
| 118 | + throw new IllegalArgumentException("Try to upload usage $propertyProcessor.type without configured item id") |
| 119 | + |
| 120 | + def quantity = propertyProcessor.getValue(cayenneService.dataSource) |
| 121 | + logger.warn("Try to upload to chargebee $propertyProcessor.type with id $itemPriceId value $quantity") |
| 122 | + |
| 123 | + if(Boolean.TRUE == chargebeeService.localMode) |
| 124 | + auditService.submit(ObjectSelect.query(Script).selectFirst(cayenneService.newReadonlyContext), AuditAction.SCRIPT_EXECUTED, "Try to upload to chargebee $propertyProcessor.type with id $itemPriceId value " + quantity.toPlainString()) |
| 125 | + else { |
| 126 | + def subscription = getSubscription() |
| 127 | + if(!subscription.subscriptionItems().find {it.itemPriceId() == itemPriceId}) { |
| 128 | + logger.warn("Item price id $itemPriceId not allowed for subscription $chargebeeService.subscriptionId and will be ignored") |
| 129 | + return |
| 130 | + } |
| 131 | + uploadToChargebee(itemPriceId, quantity.toPlainString()) |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + private void uploadToChargebee(String itemPriceId, String quantity) { |
| 136 | + try { |
| 137 | + Usage.create(chargebeeService.subscriptionId) |
| 138 | + .itemPriceId(itemPriceId) |
| 139 | + .quantity(quantity) |
| 140 | + .usageDate(new Timestamp(Instant.now().toEpochMilli())) |
| 141 | + .request() |
| 142 | + } catch (Exception e) { |
| 143 | + logger.error("Chargebee usage upload error: " + e.getMessage()) |
| 144 | + messageService.sendMessage(new MessageSpec().with { |
| 145 | + it.subject = 'onCourse->Chargebee usage upload error. Contact ish support' |
| 146 | + it.content ="\n$itemPriceId upload error for college $preferenceController.collegeName. Reason: $e.message" |
| 147 | + it.from(preferenceController.emailFromAddress) |
| 148 | + it.to("accounts@ish.com.au") |
| 149 | + it |
| 150 | + }) |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + private Subscription getSubscription(){ |
| 155 | + if(subscription != null) |
| 156 | + return subscription |
| 157 | + |
| 158 | + |
| 159 | + def subscriptions = Subscription.list().id().is(chargebeeService.subscriptionId).request() |
| 160 | + if(subscriptions.empty) { |
| 161 | + throw new IllegalArgumentException("Subscription with id $chargebeeService.subscriptionId not found!") |
| 162 | + } |
| 163 | + |
| 164 | + subscription = subscriptions.first().subscription() |
| 165 | + return subscription |
| 166 | + } |
| 167 | +} |
0 commit comments