| 1 | package workers |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "database/sql" |
| 6 | "fmt" |
| 7 | "log" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/stripsior/struxa/watchkeeper/internal/crypto" |
| 11 | "github.com/stripsior/struxa/watchkeeper/internal/wings" |
| 12 | ) |
| 13 | |
| 14 | const billingInterval = 60 |
| 15 | |
| 16 | var durationDays = map[ |
| 17 | "7day": 7, |
| 18 | "1month": 30, |
| 19 | "3months": 90, |
| 20 | "6months": 180, |
| 21 | "1year": 365, |
| 22 | } |
| 23 | |
| 24 | func RunBillingWorker(db * |
| 25 | log.Println("[billing] worker started, polling every 60s |
| 26 | billingTick(db) |
| 27 | for range time.Tick |
| 28 | billingTick(db) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | type expiredSubRow struct { |
| 33 | id string |
| 34 | userId string |
| 35 | priceId string |
| 36 | currency string |
| 37 | currentPeriodEnd time. |
| 38 | } |
| 39 | |
| 40 | func billingTick(db * |
| 41 | rows, err := |
| 42 | SELECT id, user_id, price_id, currency, current_period_end |
| 43 | FROM billing_subscriptions |
| 44 | WHERE status IN ('active','trialing') AND current_period_end <= NOW()`) |
| 45 | if err != nil |
| 46 | log.Printf("[billing] tick query error: |
| 47 | return |
| 48 | } |
| 49 | defer rows.Close() |
| 50 | |
| 51 | var subs []expiredSubRow |
| 52 | for rows.Next() |
| 53 | var s expiredSubRow |
| 54 | if err := rows |
| 55 | log.Printf("[billing] scan error: |
| 56 | continue |
| 57 | } |
| 58 | subs = append( |
| 59 | } |
| 60 | _ = rows. |
| 61 | |
| 62 | const maxConcurrent = 10 |
| 63 | sem := make( |
| 64 | for _, s |
| 65 | sem <- struct{}{} |
| 66 | go func(sub expiredSubRow |
| 67 | defer func() { |
| 68 | <-sem |
| 69 | if r := recover |
| 70 | log.Printf("[billing] panic processing sub |
| 71 | } |
| 72 | }() |
| 73 | processExpiredSubscription(db, sub |
| 74 | }(s) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func processExpiredSubscription(db * |
| 79 | var priceCents int |
| 80 | var duration string |
| 81 | err := db. |
| 82 | Scan(&priceCents, |
| 83 | if err != nil |
| 84 | log.Printf("[billing] fetch price for sub |
| 85 | if err == sql |
| 86 | suspendSubscription(db, sub |
| 87 | } |
| 88 | return |
| 89 | } |
| 90 | |
| 91 | days, ok := |
| 92 | if !ok { |
| 93 | days = 30 |
| 94 | } |
| 95 | |
| 96 | var walletId string |
| 97 | var balanceCents int |
| 98 | err = db. |
| 99 | Scan(&walletId, |
| 100 | if err != nil |
| 101 | log.Printf("[billing] fetch wallet for user |
| 102 | if err == sql |
| 103 | suspendSubscription(db, sub |
| 104 | } |
| 105 | return |
| 106 | } |
| 107 | |
| 108 | if balanceCents < priceCents |
| 109 | suspendSubscription(db, sub |
| 110 | return |
| 111 | } |
| 112 | |
| 113 | tx, err := |
| 114 | if err != nil |
| 115 | log.Printf("[billing] begin tx for sub |
| 116 | return |
| 117 | } |
| 118 | |
| 119 | newPeriodStart := sub. |
| 120 | newPeriodEnd := sub. |
| 121 | |
| 122 | res, err := |
| 123 | UPDATE billing_subscriptions |
| 124 | SET status='active', current_period_start=?, current_period_end=? |
| 125 | WHERE id=? AND current_period_end=? AND status IN ('active','trialing')`, |
| 126 | newPeriodStart, newPeriodEnd, |
| 127 | if err != nil |
| 128 | _ = tx. |
| 129 | log.Printf("[billing] claim sub |
| 130 | return |
| 131 | } |
| 132 | affected, _ := |
| 133 | if affected == 0 |
| 134 | _ = tx. |
| 135 | return |
| 136 | } |
| 137 | |
| 138 | res, err = |
| 139 | UPDATE billing_wallet SET balance_cents = balance_cents - ? |
| 140 | WHERE user_id=? AND balance_cents >= ?`, |
| 141 | priceCents, sub.userId |
| 142 | if err != nil |
| 143 | _ = tx. |
| 144 | log.Printf("[billing] deduct wallet for sub |
| 145 | suspendSubscription(db, sub |
| 146 | return |
| 147 | } |
| 148 | affected, _ = |
| 149 | if affected == 0 |
| 150 | _ = tx. |
| 151 | suspendSubscription(db, sub |
| 152 | return |
| 153 | } |
| 154 | |
| 155 | var balanceAfter int |
| 156 | if err := tx |
| 157 | _ = tx. |
| 158 | log.Printf("[billing] read balance after debit for sub |
| 159 | return |
| 160 | } |
| 161 | invoiceId := billingUUID() |
| 162 | invoiceItemId := billingUUID() |
| 163 | walletTxId := billingUUID() |
| 164 | transactionId := billingUUID() |
| 165 | |
| 166 | var invoicePrefix string |
| 167 | _ = db. |
| 168 | if invoicePrefix == "" |
| 169 | invoicePrefix = "INV-" |
| 170 | } |
| 171 | invoiceNumber := fmt. |
| 172 | |
| 173 | _, err = |
| 174 | INSERT INTO billing_invoices (id, user_id, subscription_id, invoice_number, status, currency, |
| 175 | subtotal_cents, discount_cents, total_cents, amount_paid_cents, amount_due_cents, paid_at, created_at, updated_at) |
| 176 | VALUES (?,?,?,?,'paid',?,?,0,?,?,0,NOW(),NOW(),NOW())`, |
| 177 | invoiceId, sub.userId |
| 178 | if err != nil |
| 179 | _ = tx. |
| 180 | log.Printf("[billing] insert invoice for sub |
| 181 | return |
| 182 | } |
| 183 | |
| 184 | _, err = |
| 185 | INSERT INTO billing_invoice_items (id, invoice_id, description, quantity, unit_amount_cents, total_cents, |
| 186 | currency, period_start, period_end, created_at, updated_at) |
| 187 | VALUES (?,?,?,1,?,?,?,?,?,NOW(),NOW())`, |
| 188 | invoiceItemId, invoiceId, |
| 189 | if err != nil |
| 190 | _ = tx. |
| 191 | log.Printf("[billing] insert invoice item for sub |
| 192 | return |
| 193 | } |
| 194 | |
| 195 | _, err = |
| 196 | INSERT INTO billing_wallet_transactions (id, user_id, invoice_id, amount_cents, balance_after_cents, |
| 197 | currency, type, description, created_at, updated_at) |
| 198 | VALUES (?,?,?,?,?,?,'charge','Subscription renewal',NOW(),NOW())`, |
| 199 | walletTxId, sub.userId |
| 200 | if err != nil |
| 201 | _ = tx. |
| 202 | log.Printf("[billing] insert wallet tx for sub |
| 203 | return |
| 204 | } |
| 205 | |
| 206 | _, err = |
| 207 | INSERT INTO billing_transactions (id, user_id, invoice_id, type, status, amount_cents, currency, |
| 208 | description, created_at, updated_at) |
| 209 | VALUES (?,?,?,'payment','succeeded',?,?,'Subscription renewal',NOW(),NOW())`, |
| 210 | transactionId, sub.userId |
| 211 | if err != nil |
| 212 | _ = tx. |
| 213 | log.Printf("[billing] insert transaction for sub |
| 214 | return |
| 215 | } |
| 216 | |
| 217 | if err := tx |
| 218 | log.Printf("[billing] commit renewal for sub |
| 219 | return |
| 220 | } |
| 221 | |
| 222 | log.Printf("[billing] renewed subscription |
| 223 | } |
| 224 | |
| 225 | func suspendSubscription(db * |
| 226 | res, err := |
| 227 | UPDATE billing_subscriptions SET status='past_due' |
| 228 | WHERE id=? AND status IN ('active','trialing')`, sub.id |
| 229 | if err != nil |
| 230 | log.Printf("[billing] suspend sub |
| 231 | return |
| 232 | } |
| 233 | affected, _ := |
| 234 | if affected == 0 |
| 235 | return |
| 236 | } |
| 237 | |
| 238 | rows, err := |
| 239 | SELECT s.id, s.uuid, n.fqdn, n.scheme, n.daemon_listen, n.token |
| 240 | FROM servers s JOIN nodes n ON s.node_id=n.id |
| 241 | WHERE s.subscription_id=? AND s.suspended=0`, sub.id |
| 242 | if err != nil |
| 243 | log.Printf("[billing] fetch servers for sub |
| 244 | return |
| 245 | } |
| 246 | defer rows.Close() |
| 247 | |
| 248 | type srvRow struct |
| 249 | id, uuid, |
| 250 | listen int |
| 251 | } |
| 252 | var srvs []srvRow |
| 253 | for rows.Next() |
| 254 | var r srvRow |
| 255 | if err := rows |
| 256 | log.Printf("[billing] scan server row: |
| 257 | continue |
| 258 | } |
| 259 | srvs = append( |
| 260 | } |
| 261 | |
| 262 | for _, srv |
| 263 | tok, err := |
| 264 | if err != nil |
| 265 | log.Printf("[billing] failed to decrypt token for server |
| 266 | continue |
| 267 | } |
| 268 | client := wings. |
| 269 | if err := client |
| 270 | log.Printf("[billing] kill server |
| 271 | continue |
| 272 | } |
| 273 | if _, err |
| 274 | log.Printf("[billing] suspend server |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | log.Printf("[billing] subscription |
| 279 | } |
| 280 | |
| 281 | func billingUUID() string |
| 282 | var b [16] |
| 283 | _, _ = |
| 284 | b[6] = |
| 285 | b[8] = |
| 286 | return fmt.Sprintf( |
| 287 | } |