Joulora
An electricity bill app built with Flutter. Photograph a bill and an AI model reads only what is printed on it; the phone does every sum after that: where the money went, what each appliance costs to run, what the month will come to, and what the same bill would have been on another tariff. A Laravel key proxy with an admin panel and a one-page product website are in the same download.
Flutter and Material 3Gemini, OpenAI, Claude or your server Demo mode needs no keyDark and light English, Spanish, ArabicLaravel key proxy included Landing page included
1What Joulora is
Joulora is an app for the person who pays the electricity bill. They photograph the bill; an AI model reads the figures printed on it; and from then on the phone does all the arithmetic itself: where the money went, band by band, what each appliance costs to run, what this month will come to, and what the same bill would have been on another tariff.
The line between the two halves is the product. The model is asked to read, never to calculate or advise, and the reply it can send has no field for a name, an address or an account number. Every amount beyond the printed ones is worked out by 4 small pure-Dart engines, so it is the same on every phone and can be checked by hand.
The download holds three things:
- The Flutter app (
joulora_ai_app/) with 21 screens, dark and light, 3 languages, and a Demo mode that answers on the device with no key and no network. - A Laravel back end (
backend/): a key proxy that holds your AI provider keys on your own server and runs only this app's three jobs, with per-device and server-wide spending caps, a usage log, a copy of the bill photos read through it, and a Filament admin panel. - A one-page product website (
landing/), a self-contained HTML file in the app's own colors and typefaces.
Out of the box the app opens in Demo mode on a sample household: 4 bills, 10 appliances on the strip, 3 tariffs and one meter reading, so every screen is populated the moment it opens. Add a key of your own, or point it at the back end, and it reads real bills.
2Requirements
You need a working Flutter toolchain and one of the two mobile SDKs.
| What | Version | Notes |
|---|---|---|
| Flutter SDK | 3.47 or newer | Dart 3.13 or newer comes with it. The project pins 3.47.2 in
.fvmrc for people who use fvm; plain flutter works
too. |
| Android | compileSdk 36 | Android Studio with the command line tools, and JDK 17. Gradle 9 and AGP 9.1 come with the project. |
| iOS | Xcode 16 or newer | CocoaPods. On Apple silicon, install it with Homebrew rather than the system Ruby. |
| Back end | PHP 8.4+ | π΄ Laravel 13 will not run on PHP 8.2 or 8.3. Check the PHP version your host offers before you buy the plan; many shared plans still default to 8.2. Docker needs no PHP on your machine at all. |
| An AI key | optional to try | Demo mode needs none. To read real photographs you need either a key from Google, OpenAI or Anthropic, or the back end holding one. |
The app depends on 21 packages, and packages/, the
feature packs, is part of the project: do not delete it.
3Run it in five minutes
The project is at the root of its folder in the download; there is no wrapper folder to step into first.
flutter pub get
flutter run
The app opens on a splash, three onboarding pages and the sign-in screen.
The sign-in form is a demo: it arrives filled with the demo
account (demo@joulora.app / demo1234), but any email
and password get in, including empty fields, and nothing leaves the phone. The chapter on signing in
says what is real and what is not.
You land on Home in Demo mode. Tap Read a bill and then Read this bill: Demo mode "reads" the sample bill drawn in the frame and hands it to the same parser a live answer goes through, so you see the whole path without a key.
Check it
flutter analyze # expect: No issues found!
flutter test # expect: All tests passed! (193 tests)
Running it without a terminal
- Open the
joulora_ai_appfolder in Android Studio (File → Open) or VS Code with the Flutter extension. - Let the IDE run Pub get when it offers to (Android Studio shows a
banner at the top of
pubspec.yaml). - Pick a simulator or a connected phone in the device menu, and press the green Run button.
Everything this manual does with --dart-define on the command
line can also be done by editing one file; the chapter on pointing the app at
the back end shows how.
4The screens
21 screens: four tabs, the screens they open, and Settings behind the avatar on Home. The appliance sheet and the line editor are bottom sheets on top of them.
| Where | Screen | What it is for |
|---|---|---|
| Entry | Splash, onboarding (three pages) | The plug mark; three photo pages that say what the app does. |
| Sign in, create account | A demo form, plus Google and Apple when configured. | |
| Home tab | Home | The meter window, the day ruler, the month-end bill, Why this month, the three dearest appliances on the strip, the last bill. |
| Bills tab | Bills | The latest bill as a branching ribbon, then every bill with its change against the one before. |
| Appliances tab | Appliances | The power strip: one socket per appliance, with what it costs this month. |
| Tariffs tab | Tariffs | Your tariffs, each with what your last bill would have come to on it. |
| Bills | Read a bill | Viewfinder, camera or photo library, and the What we send panel. |
| Check the reading | Every line read, the totals check, confidence, save. | |
| Bill detail | The ribbon, per-day figures, every line, and the way into the ledger. | |
| Ledger | The bill against another tariff, or against another bill, band by band. | |
| Month by month | Insights: every bill as a bar, averages, all-in cost per kWh. | |
| Appliances, tariffs | Appliance sheet | The 24-hour timer dial, watts, standby watts, how many. |
| Tariff editor | Flat, tiered or time of use, or filled in from a photo of a rate card. | |
| Account | Settings | Demo mode, AI route, theme, language, lock, notifications, privacy, currency, your data. |
| AI and key proxy | Which route reads bills: Demo mode, the included server, or a key of your own. | |
| Notifications | What the app has told the person. | |
| How Joulora works | About: what is computed, what the AI does, where data lives. | |
| Joulora Pro | The in-app purchase screen (mock until you add store product ids). |
5Conventions used in this manual
- Paths are relative to the folder they belong to:
lib/β¦,test/β¦andassets/β¦are insidejoulora_ai_app/;app/β¦,routes/β¦,config/β¦anddatabase/β¦are insidebackend/. - Anything in
<angle brackets>is a value you supply. The brackets are not part of it. file.dart:42means line 42 of that file, measured when this manual was built.- "Demo mode" means the sample household in
lib/app/data/mock/sample_data.dartand the on-device answer indemo_provider.dart; "the back end" or "your server" meansbackend/. - Amounts in examples are the sample household's, in dollars. The app prints whatever currency symbol the person sets, and never converts.
6Colors in one file
Every color in the app is in one file:
lib/app/core/theme/app_colors.dart. Light and dark values sit side
by side, so a token always has both. Dark is the default theme.
The brand comes in grades
A store thumbnail has to be bright to stand out in a shelf of other thumbnails; white text needs a fill dark enough to be read. No single color does both, so the filament orange is split, and each grade has one job:
| Constant | Value | Used for |
|---|---|---|
primaryBright | #FF8A3D |
The store tile, the dark theme's buttons and highlights (dark ink on it), and the energy band of the ribbon. |
primary | #B84E0C |
The light theme's fill: buttons, selected chips, the tab highlight. White on it. |
primaryDeep | #963E06 |
Brand-colored words on the light paper. |
primaryDark / onPrimaryDark |
#FF8A3D / #131110 |
The dark theme's fill and the ink on it. |
accentDark / accentLight |
#8FD3FF / #1E6FB0 |
Ice blue, for money saved: a cheaper tariff, a lower bill. |
overDark / overLight |
#FF6B5E / #B3261E |
Dearer than before. |
bandEnergy, bandFixed, bandTax,
bandOther | four values | The four bands of the bill ribbon and the ledger. Keep them distinct from each other in both themes. |
Change a grade and keep its pair readable: a selected chip is the fill
color with its label on it, and test/theme_contrast_test.dart and
test/chip_contrast_test.dart fail if that pair drops below
4.5:1. The second one renders real chips and reads their pixels, so it catches
what reading the theme cannot.
The meter window's glass and bezel (meterGlass,
meterBezel) are the same in both themes on purpose: a meter is
black glass whatever the room looks like.
7Typefaces
Three families, bundled as 8 files in
assets/fonts/ and never downloaded: Anybody
(600, 700, 800) for headings and screen titles, Sen (400, 500,
700) for the body, and Azeret Mono (500, 700) for every figure
a person reads at a glance: amounts, kWh, meter digits.
- Drop your
.ttffiles intoassets/fonts/. Use static files: a variable font's file name carries square brackets, which a web build encodes and a marketplace upload rejects. - Update the
fonts:block inpubspec.yaml, one entry per weight. - Change the constants
headingFamily,bodyFamilyandfigureFamilyinlib/app/core/theme/app_text_theme.dart, the only Dart file that names a font. - Update
assets/fonts/LICENSES.txtso it names what you ship.
The Roboto entry in pubspec.yaml points at the body
face on purpose: anything Material draws from its own defaults falls back to
Roboto, and on the web the engine would otherwise fetch it from Google's font
servers.
8The launcher icon
The launcher icon is drawn by a script, so it can be regenerated after any change rather than hand-exported at twenty sizes.
Replacing it with your own artwork
- Make a 1024 Γ 1024 PNG, no transparency, no rounded corners: both stores round the corners themselves, and iOS rejects an icon with an alpha channel.
- For Android's adaptive icon, make a second 1024 Γ 1024 PNG of the mark alone on a transparent background, with the mark inside the middle 66% (the outer ring is cropped to a circle, a squircle or a teardrop depending on the phone).
- Save them as
assets/icon/app_icon.pngandassets/icon/app_icon_foreground.png, and setadaptive_icon_backgroundinpubspec.yamlto the color behind the mark (it ships as#FF8A3D). - Run
dart run flutter_launcher_icons. It writes everymipmap-*folder on Android and the wholeAppIcon.appiconseton iOS. - Uninstall the app from the simulator or phone and run it again: both platforms cache the old icon until the app is reinstalled.
Or edit the drawn one
assets/icon/_mark.py draws the plug with its filament loop;
python3 assets/icon/make_icon.py writes the two PNGs above and
python3 web/make_web_icons.py the browser icons. The same geometry
is drawn in Dart by BrandMark in
lib/app/modules/splash/splash_view.dart, so change both
together.
9App name and bundle identifier
The name people see and the identifier the stores use are two different things, set in different places.
| What | Android | iOS |
|---|---|---|
| Name under the icon | android:label in
android/app/src/main/AndroidManifest.xml |
CFBundleDisplayName and CFBundleName in
ios/Runner/Info.plist |
| Bundle identifier | applicationId and namespace in
android/app/build.gradle.kts (now
com.joulora.joulora_ai_app) |
PRODUCT_BUNDLE_IDENTIFIER in
ios/Runner.xcodeproj/project.pbxproj: three Runner lines and
three RunnerTests lines (now com.joulora.jouloraAiApp). Easiest in
Xcode: Runner target → Signing & Capabilities → Bundle
Identifier. |
| Title in the task switcher | title: in lib/main.dart | |
On Android, if you change namespace, move
MainActivity.kt into the matching folder under
android/app/src/main/kotlin/ and change its
package line. iOS identifiers cannot contain underscores.
The strings a person reads (the wordmark on the splash, "Joulora Pro", the
lock prompt) are in the language files in lib/l10n/; search each
file for the old name.
10The photographs
The app ships 13 photographs in
assets/images/energy/: a glowing bulb for the Home hero, meters
and a socket for onboarding and empty states, and one photograph per sample
appliance (fridge, oven, dishwasher, washing machine, kettle, TV, laptop, hair
dryer, fan, lamp). They are royalty-free Pexels stock, used under the Pexels
License, and LICENSES.txt in the same folder lists each one:
file, subject, source page, photographer.
They are sample content. Replace them with your own: keep the file names and
nothing else needs to change, or change the names and update the references.
The appliance photos are named in
lib/app/data/mock/sample_data.dart as
asset://assets/images/energy/<file>; an appliance a person
adds without a photo is drawn with a glyph instead. Keep each file under about
150 KB and the long edge around 1280 px.
The bill in the capture screen's frame is not a photograph: it is drawn from
the sample data (lib/app/core/widgets/bill_sheet.dart), so it
always shows the figures Demo mode is about to read.
11Feature packs
9 feature packs, in 11 small packages under
packages/: 9 interfaces and the two Firebase
implementations two of them plug into, each with a mock or no-op default
behind it. Nothing here runs until you switch it on,
which is why the app you just ran asked for no permission beyond the camera,
sent nothing anywhere and charged nobody. Every switch lives in one file:
lib/app/core/values/feature_config.dart. The single place that
chooses an implementation is
lib/app/data/services/feature_packs.dart; screens only ever see the
interface.
Languages (qh_l10n)
English, Spanish and Arabic ship. Every word the app shows comes from one
file per language in lib/l10n/. Settings → Language switches
the whole app at once; Arabic flips the layout. The app also sends the language
to your server (Accept-Language), so the back end's messages come
back in it.
| To⦠| Change |
|---|---|
| Add a language | Copy lib/l10n/es.dart to
<code>.dart, rename the constant, translate the values (the
date.* lines are month and weekday names). Add its import and its
name to the list in lib/l10n/app_languages.dart. |
| Remove a language | Delete its name and import from that list. |
| Change a sentence | Edit the value in en.dart and in
each other language file. The keys stay the same. |
test/l10n_test.dart fails when a language is missing a key or
still has English in it. The line labels a supplier printed on a bill are kept
as printed; the lines the app computes (First 300 kWh, Tax 5%)
are translated.
The Spanish and Arabic tables are machine-assisted. Have a native speaker read both before the app reaches real people.
Lock on launch (qh_biometric)
Settings → Security. The switch is disabled on a phone with no enrolled
biometrics. iOS shows the sentence in NSFaceIDUsageDescription
(ios/Runner/Info.plist); Android needs nothing further: the
manifest declares USE_BIOMETRIC and the activity is a
FlutterFragmentActivity.
Version prompts (qh_upgrade)
With API_BASE_URL set at build time, the app asks
GET /api/version once per launch. You drive it from the admin
panel's App updates page: each row is a release with the latest
version, the oldest version still allowed to run, the sentence the prompt shows,
the two store links and the time it goes live, and the newest published row is
the one the server answers with. Until a row is published, the server falls back
to APP_LATEST_VERSION, APP_MINIMUM_VERSION,
APP_UPDATE_MESSAGE and the two store URLs in its
.env. Below the minimum, the dialog has no Later
button.
Analytics and crash reports (qh_analytics + qh_analytics_firebase)
Needs a Firebase project. Run flutterfire configure, set
firebaseConfigured = true in lib/firebase_config.dart,
and enable Analytics and Crashlytics in the console. Settings → Privacy is
the consent switch; with it off nothing is collected, and bill contents are
never sent either way. FeatureConfig.analyticsDefaultOn decides
where the switch starts. Demo mode never initializes Firebase, whatever the
flag says.
Without a terminal: in the Firebase console, add an Android
app and an iOS app with the bundle identifiers from the app name chapter,
download google-services.json and
GoogleService-Info.plist, put them in
android/app/ and ios/Runner/, and copy the API key,
app id, sender id and project id from them into the matching fields of
lib/firebase_options.dart by hand. Then flip the flag.
Push notifications (qh_push + qh_push_firebase)
The same Firebase project, plus the Push Notifications capability in Xcode
and an APNs key uploaded to the console. Permission is asked in Settings →
Notifications, never at launch. Every install subscribes to the topic in
FeatureConfig.pushBroadcastTopic (all), so the admin
panel's Send notification page, which needs
FIREBASE_CREDENTIALS in the back end's .env, reaches
all of them. A message with a route key opens that screen, for
example /notifications. Pick a time under Send later and
the server sends it then; Push history lists every send with its status
and cancels a scheduled one before it goes. For a send to everyone its
Phones column shows 1, because Firebase reports that it accepted the
message, not how many phones received it. A send
for later needs the scheduler's cron line (the chapter on putting the back end on
a server).
Continue with Google / Apple (qh_social_login)
Outside Demo mode the buttons appear only for the providers you configure, and
with API_BASE_URL set the id token is exchanged at
POST /api/auth/social. Every console step, for both providers on
both platforms, is in the chapter Setting up Google and Apple sign-in.
In-app purchases (qh_iap)
The Joulora Pro screen sells one digital unlock: an unlimited bill history
(the free plan keeps 12 bills, a year of monthly ones). Its product ids
go in FeatureConfig.iapProductIds, keyed by plan id
(monthly, yearly, lifetime). Until you
build with --dart-define=IAP=on the screen is a mock: instant,
always succeeds, charges nothing, and says so on the screen. The store steps are
in the chapter Setting up in-app purchases.
Pictures (qh_image)
Appliance photos go through QhNetworkImage:
asset://assets/images/β¦ for a bundled file or an
https:// URL, with a placeholder while loading and a neutral box if
the URL is dead.
Sharing (qh_share)
The share icon on a bill hands its summary (period, kWh, every line, the total) to the system sheet as text. On iPad the sheet is anchored to the button that was tapped.
Switching packs on connects the app to third-party services (Firebase, Google Cloud, the Apple and Google developer programs and their stores), which will involve accounts of your own and will incur their own separate costs, billed by those providers to you. None of them is included in this item.
12Setting up in-app purchases
The paywall and the qh_iap pack are finished; what is left is on the
stores' side. Until you do the steps below the app runs a mock checkout:
every purchase succeeds instantly, charges nothing and says so on screen, which is what
the walkthrough and the Live Preview show. Do the store you ship to first; each takes
about an hour, most of it waiting for the store.
| What the app already does | Where |
|---|---|
| Reads prices from the store, in the buyer's currency | SubscriptionService Β· StorePurchaseGateway |
| Keeps Pro after a purchase, offline too | the encrypted store on the phone |
| Restore purchases (one tap on the paywall) | PurchaseGateway.restore() |
| Android's billing permission | android.permission.BILLING is already in AndroidManifest.xml |
| Checks receipts with your own server | left to you: the verify hook on StorePurchaseGateway |
1. Put the product ids in one file
Pick one id per plan and use the same id in both stores. The keys are the plan ids the paywall already shows; the values are what you create in the stores:
// lib/app/core/values/feature_config.dart
static const iapProductIds = <String, String>{
'monthly': 'com.joulora.jouloraAiApp.pro.monthly',
'yearly': 'com.joulora.jouloraAiApp.pro.yearly',
'lifetime': 'com.joulora.jouloraAiApp.pro.lifetime',
};
Store ids cannot be reused after you delete them, so settle on the names first.
2. App Store Connect (iOS)
- Agreements, Tax, and Banking β accept the Paid Apps agreement and fill in tax and bank details. Until its status is Active, the store returns no products at all. That is the most common reason a paywall shows the mock prices on a real phone.
- Apps β + β New App with bundle id
com.joulora.jouloraAiApp(it must match Xcode exactly). - In the app: Monetization β Subscriptions β create a subscription group (for example Joulora Pro), then one subscription per recurring plan with the ids from step 1. A one-off plan (lifetime) goes under In-App Purchases as Non-Consumable.
- Give each product a price, a display name and a review screenshot (the paywall screen is fine). Products stay Missing Metadata, and invisible to the app, until all three are there.
- Users and Access β Sandbox β Test Accounts β add a tester with an e-mail that is not a real Apple ID.
- In Xcode open
ios/Runner.xcworkspaceβ Runner β Signing & Capabilities β + Capability β In-App Purchase. (It adds no file to the project; the capability lives on the App ID.)
3. Play Console (Android)
- Create app, then complete the payments profile (Settings β Payments profile); without it, products cannot be created.
- Upload one signed build (
flutter build appbundle) to Testing β Internal testing. Google only serves products to an app it has seen; with no build uploaded, every product answers not found. - Monetize β Products β Subscriptions β one subscription per recurring plan with the ids from step 1, each with a base plan and a price. A one-off plan goes under In-app products. Activate each one.
- Settings β License testing β add the Google accounts that will test; they are charged nothing and can cancel at once.
- Join the internal test from that account (the opt-in link on the Internal testing page)
and install from the Play Store once. A build side-loaded with
flutter runworks afterwards, a build that was never installed from Play may not see products.
4. Turn it on and try it
flutter run --release --dart-define=IAP=on
# a real phone, signed in with the sandbox (iOS) or license-test (Android) account
The paywall now shows the store's prices. Buy a plan: the sheet is the store's own,
marked as a test. Then delete and reinstall the app and tap Restore purchases: Pro
comes back. Leave out --dart-define=IAP=on and the app goes back to the mock, which
is why simulator runs and the Live Preview never touch a store.
When products do not load
| What you see | Why | Fix |
|---|---|---|
| Mock prices on a real phone | Built without --dart-define=IAP=on, or iapProductIds is empty | Step 1 and step 4 |
| iOS: the paywall lists no plans | Paid Apps agreement not active, or a product still Missing Metadata | App Store Connect step 1 and 4 |
| iOS: Cannot connect to iTunes Store | Signed in with a real Apple ID on a debug build | Sign out under Settings β App Store β Sandbox Account and use the tester |
Android: item not found / BILLING_UNAVAILABLE | No build on a testing track, the product is inactive, or the Play Store app is not signed in | Play Console step 2 and 3 |
| Android: This version of the application is not configured for billing | The running build's version code is higher than any uploaded one | Upload the build you are running to internal testing |
The app trusts the store's answer on the phone. For anything you would not want a
modified phone to unlock, check receipts on a server: App Store Server API and Google Play
Developer API both take the purchase token the verify hook receives. The stores
keep their standard commission on every sale.
13Setting up Google and Apple sign-in
The buttons and the sign-in flow are finished: the app sends the id token to the included back end (POST /api/auth/social), which checks it with Google or Apple and answers with the same session a password sign-in gets. What is left is registering the
app with Google and Apple. A button appears only for a provider you configure, so you can ship with one
and add the other later, with one rule on iOS: App Store guideline 4.8 says an app that offers Google
sign-in must also offer Sign in with Apple, so on iOS the Google button stays hidden until Apple is set up
too (a debug build says so in the console). Android shows whatever you configure. In demo mode both buttons show and sign in as a demo user without
asking anything.
Field in lib/app/core/values/feature_config.dart | What goes in it |
|---|---|
googleServerClientId | The Web OAuth client id. It is what makes the id token checkable by a server. Needed on Android and iOS. |
googleIosClientId | The iOS OAuth client id. |
appleSignIn | true once the capability is on the App ID (step "Apple on iOS"). A button without it fails every time. |
appleServiceId Β· appleRedirectUri | Only for Apple on Android: the Services ID and its Return URL. |
Your identifiers: iOS bundle id com.joulora.jouloraAiApp Β· Android package com.joulora.joulora_ai_app.
Google on Android
- In Google Cloud console β APIs & Services β Credentials (the project you use for the app), configure the OAuth consent screen first: app name, support e-mail, and your domain if you have one.
- Create credentials β OAuth client ID β Web application. Copy its client id into
googleServerClientId. - Create credentials β OAuth client ID β Android, package name
com.joulora.joulora_ai_app, and the SHA-1 of the key that signs the build. Add one per key: the debug key for development, your upload key, and the App signing key Play shows under Setup β App integrity for store installs:# debug key keytool -list -v -keystore ~/.android/debug.keystore \ -alias androiddebugkey -storepass android -keypass android # release (upload) key keytool -list -v -keystore <your upload keystore>.jks -alias <its alias> - On the server, put the same Web client id in
GOOGLE_CLIENT_IDSinbackend/.env(comma-separated if you have several). The server only accepts id tokens made for the ids listed there.
Google on iOS
- Create credentials β OAuth client ID β iOS, bundle id
com.joulora.jouloraAiApp. Copy its client id intogoogleIosClientId. - Add the reversed iOS client id as a URL scheme, so Google can hand the result back
to the app. It goes in
ios/Runner/Info.plist, inside the top-level<dict>:<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <!-- the iOS client id, reversed: com.googleusercontent.apps.1234-abcd --> <string>com.googleusercontent.apps.REPLACE_WITH_YOURS</string> </array> </dict> </array>
Apple on iOS
- In the Apple Developer portal β Certificates, Identifiers & Profiles β
Identifiers, open the App ID
com.joulora.jouloraAiAppand tick Sign in with Apple. - The entitlement is already in
ios/Runner/Runner.entitlements; Xcode shows it under Signing & Capabilities. Regenerate the provisioning profile if Xcode asks. - Set
appleSignIn = true. - On the server, list who Apple tokens may be for in
APPLE_CLIENT_IDS: the iOS bundle idcom.joulora.jouloraAiApp, and the Services ID if you also sign in on Android.
App Review (guideline 4.8) asks an iOS app that offers Google sign-in to offer a privacy-focused option as well; Sign in with Apple is the one it names, so ship the two together on iOS.
Apple on Android
Optional: most apps offer Apple on iOS only. On Android it runs in the browser and comes back
to the app through the activity already declared in AndroidManifest.xml
(SignInWithAppleCallback).
- Identifiers β + β Services IDs: create one (for example
com.joulora.jouloraAiApp.signin), enable Sign in with Apple, and add your domain and the Return URL below. - Keys β +: a key with Sign in with Apple enabled, for the App ID; download the
.p8file (once only). - The trip back into the app goes through the included back end, so the Services ID's
Return URL is
https://<your server>/api/auth/apple/callback. SetAPPLE_ANDROID_PACKAGE=com.joulora.joulora_ai_appinbackend/.envso it knows which app to hand the result to, and add the Services ID toAPPLE_CLIENT_IDS. - Put the Services ID in
appleServiceIdand the Return URL inappleRedirectUri.
Try it
Build with the ids filled in and demo mode off, on a real phone for Apple (the simulator cannot sign in with Apple reliably). Sign in with each provider once, sign out, and sign in again: the second time Apple sends no name or e-mail. That is Apple's normal behavior, and the account is found by its id.
Staying signed in
Someone who signs in stays signed in: closing the app, or the phone killing it, does not sign them out. The next time it opens it goes straight to the main screen, without the slides or the sign-in form. Only Sign out or Delete account ends the session.
A Google / Apple sign-in on the included back end also keeps its session token in the same store, so requests after a restart carry it as before.
The session is one entry in the phone's encrypted store (Keychain on iOS, Keystore on Android),
kept by lib/app/core/session/session_memory.dart. It is written when a sign-in finishes, and a
sign-up still waiting on the code screen does not count. The splash reads it once. Two cases never
remember a session: the web build running on the sample data, which is the Live Preview, so every visitor
sees sign-in; and a session made on the sample data, which a build talking to a server will not
accept.
Deleting an account
Apple (App Store guideline 5.1.1(v)) and Google Play both require that an app which lets people make an account also lets them delete it from inside the app. This one does.
Settings β Delete account does two calls on the included back end:
DELETE /api/auth/me for a Google or Apple sign-in (the account and its tokens), then
DELETE /api/ai/device for this phone's device record, its request log and every bill photo
stored under it. The device key is forgotten too, so a later AI read registers as a new device. Bills on
the phone stay until Delete everything.
Google Play also asks, in the Data safety form, for a web page where people can ask for deletion without the app. A page with your support e-mail address is enough.
Terms of Service and Privacy Policy
Both stores ask for a privacy policy (App Store Connect and the Play Console each have a field for its address), and people should see what they agree to before they make an account. The sign-up screen says By creating an account you agree to the Terms of Service and the Privacy Policy with both names tappable, and Settings has a row for each.
- Rewrite
assets/legal/terms.mdandassets/legal/privacy.mdas your own: they are templates, with every part to fill in shown in [square brackets], and a list of what this app keeps and sends that you should check against how you run it. - Publish them as web pages and put the two addresses in
termsUrlandprivacyUrlinlib/app/core/values/feature_config.dart. From then on both entries open the page in the browser, the same page the store listing links to. Left empty, the bundled text shows inside the app.
When sign-in fails
| What you see | Why | Fix |
|---|---|---|
| No Google button | googleServerClientId is empty (and demo mode is off) | Google on Android, step 2 |
| iOS only: no Google button, though Android has one | Sign in with Apple is not set up; App Store guideline 4.8 needs both | Apple on iOS, then appleSignIn = true |
| Android: DEVELOPER_ERROR / error 10 | The SHA-1 of the key that signed this build is not on an Android OAuth client | Add that SHA-1. Play-installed builds use the App signing key |
| iOS: the app crashes when Google opens | The reversed client id URL scheme is missing | Google on iOS, step 2 |
| Apple: invalid_client | The Services ID, domain or Return URL does not match what the portal has | Apple on Android, step 1 |
| The server answers 503 sign-in is not configured | GOOGLE_CLIENT_IDS / APPLE_CLIENT_IDS are empty | Fill them in backend/.env |
14Dark and light
Dark is the default: a warm near-black ground with the filament orange on top, the way a meter cupboard looks with the light off. Light is a real second theme on warm paper, not an afterthought.
Settings → Appearance switches between light, dark and the phone's
setting. To open in light by default, change the one line in
lib/app/core/theme/theme_controller.dart:
final choice = ThemeChoice.dark.obs; →
ThemeChoice.light.
15Adding or removing a bottom tab
Four tabs on a bar drawn by the app itself (_BottomBar in
lib/app/modules/main/main_view.dart), mounted as the scaffold's
bottomNavigationBar.
lib/app/core/widgets/tab_glyphs.dart): a meter window, a
branching ribbon, a plug and a two-column ledger, so they recolor with the
theme.Adding a tab
- Build the screen and its controller, as the other tabs are (a
GetViewand a controller in its own folder underlib/app/modules/). lib/app/modules/main/main_controller.dart: add a constant toMainTabwith the next index.lib/app/modules/main/main_binding.dart:lazyPutthe controller.lib/app/modules/main/main_view.dart: add the view to theIndexedStackchildren at the same index, add its id to_tabIds, and add anavItemto the bar's row. Add an icon toTabGlyphor use a Material icon.- Add the label to every file in
lib/l10n/('tab.<name>').
Removing a tab
The same four places, in reverse, and renumber the MainTab
constants that come after it. Two things to watch: the index in
MainTab, the position in the IndexedStack and the
position in the bar must agree, or a tap opens the neighboring screen; and
test/app_smoke_test.dart and
integration_test/screenshots_test.dart tap tabs by their key
(tab-Bills, tab-Appliancesβ¦), so update them in the
same change.
Five tabs fit on a phone; past that, move one behind the avatar on Home as Settings is.
16Architecture
GetX, in four layers, and each layer only talks to the one below it:
View (lib/app/modules/β¦) what the person sees
β Controller screen state, taps
β EnergyService / AiService every derived figure / every AI request
β engines (data/engines/) pure Dart: tariff, appliance, forecast, ledger
β jobs (data/providers/) bill read, rate-card read, three sentences
β LocalStore Γ4, settings encrypted storage on the phone
- No screen imports the sample data. Everything goes through
EnergyService, which reads fourLocalStores (bills, appliances, tariffs, meter readings), wired inlib/main.dart. While Demo mode is on they hold the sample household in memory and write nothing to disk; switching Demo mode on mid-session sets the person's records aside and switching it off brings them back untouched. Outside Demo mode the sample is seeded only on the very first launch, when nothing has ever been saved: a store the person emptied, or wiped with Delete everything, stays empty after a restart. Delete everything also deletes every bill and rate-card photo the app has written, and deleting one bill deletes its photo, on the phone. A copy already kept on the included server stays there. Deleting it on the panel's Pictures page is final only once the phone no longer has the file: while it does, the next sync sends it again. Deleting that install's row on Devices takes all its pictures with it. - The engines are pure Dart
(
lib/app/data/engines/): no Flutter import, no clock of their own, no network. Every input is a parameter, which is why they are tested line by line and why you can lift them into another app. - One service talks to the AI:
AiServicepicks the adapter for the route chosen in Settings (Demo, Gemini, OpenAI, Claude or your server), runs a job through it, and hands the reply to the job's own parser. Screens never see a provider. - Storage is the platform's encrypted store: the Keychain on
iOS, EncryptedSharedPreferences on Android. A bill or rate-card photo is a file
in the app's own documents folder, and a record keeps only the file's name,
never the device path, so an app update that moves that folder still finds it (a record saved with a full path by an earlier build is read by
the last part of the path). While the app reads bills through
the included server, the server keeps a copy of each photo too (see
Choosing an AI route). API keys never leave
SettingsServiceas a list. - Everything drawn is drawn: the meter drums, the day ruler, the bill ribbon, the power strip and its socket cards, the timer dial and the tab icons are 10 custom painters and clippers, not image assets.
17Reading a bill: where the AI stops
Three jobs go to a model, and each one is fenced in the same three places: the instruction says what is allowed, the reply schema has nowhere to put anything else, and a parser in the app reads only the fields it knows and range-checks every number.
| Job | Sees | Returns |
|---|---|---|
BillReadJob | One photo of a bill | The period, kWh, the two meter readings, up to 12 charge lines
(each energy, fixed, tax or
other), the printed total, the due date, a confidence. |
TariffReadJob | One photo of a rate card | Flat, tiered or time of use, the rates, tiers or windows, the standing charge a month and the tax percent. |
WhyJob | Numbers only, never a photo | Three short sentences about this month. |
The rules
The rules for reading a bill start at lib/app/data/providers/bill_read_job.dart:33. In short: read only what is
printed and return null for anything that is not; never compute,
estimate or fill in a typical value; never return a name, address, account
number, meter serial, customer number or payment details; never recommend a
tariff, a supplier or a product. The rate-card job has the same fence and also
refuses to say which tariff is cheaper.
The schema has no field for personal data
The reply schema is at lib/app/data/providers/bill_read_job.dart:93. It lists the fields above and nothing
else, and it is sent to the provider as a structured-output schema (Gemini's
responseSchema, OpenAI's strict json_schema,
Anthropic's output format), so a model that wanted to volunteer a name would
have to break the schema, which all three reject.
The parser checks every number
static BillReading parse(Map<String, dynamic> json) // lib/app/data/providers/bill_read_job.dart:133
- A line without an amount or a label is dropped; an amount over 100,000 is dropped; a kWh over 100,000 or a rate over 50 per kWh is set to empty.
- A string with exactly one number in it is read (
"512 kWh","1,234.50"); a string with two ("300 kWh at 0.18") is refused rather than guessed at. - The meter readings are kept only when both are printed and the current one is not lower than the previous one. Dates must be real dates between 2000 and 2100.
- The printed total is compared with the sum of the lines, to the cent. The review screen says whether they agree.
- A reply whose fields have the wrong type (a number sent as text, a word sent as a number) is read where it can be and otherwise becomes the named bad response error, never a silent stop.
Anything the model got wrong is corrected on the review screen before it is saved, and on the bill afterwards: tap a line to edit it, or tap the period under the month (the dates and kWh, with a pencil) to correct the billing period, the kWh and the two meter readings.
What we send
The What we send panel on the capture screen opens to the exact instruction the model gets, rules included, followed by the size of the photo once it is encoded. On the included server it also shows the schema instruction that route adds, because the server has nowhere to hang a structured-output schema (see the chapter on AI routes). What is sent is the instruction and the photo; nothing else about the person or the household goes with a bill read. On the included server route the photo file is also stored on that server afterwards, separately from the read (see Choosing an AI route).
The third job only sees numbers
WhyJob is given the projected kWh and cost, the last bill, the
tariff type, the share of use the appliances explain and the three dearest
appliances, each already formatted the way the screen prints it. Its parser
drops any sentence that carries a number not in that list, so a sentence cannot
state a figure the screen does not show.
18The four engines
| Engine | Answers | Tests |
|---|---|---|
TariffEngine | What one tariff charges for some kWh over some days: flat, tiered (block by block) or time of use (window by window), the standing charge pro-rated from a 30-day month, tax on everything before it, and lines the tariff does not set (meter rental, a fee) carried across and taxed as the bill taxed them. | test/engines_test.dart |
ApplianceEngine | kWh a day for one appliance: running watts for the hours it runs, standby watts for the rest of the day, times how many. Unplugged draws nothing. | |
ForecastEngine | The kWh this billing period is heading for, and which of three sources that figure came from. | |
BillDiffEngine | Two sides of the ledger, band by band: a bill against another tariff for the same kWh, or against another bill. |
A worked example: the sample August bill
512 kWh from 1 to 31 August on the Standard tiered tariff (first 300 kWh at $0.18, 300 to 600 kWh at $0.24, above that $0.31; standing charge $12.00 a month; tax 5%), with meter rental printed as its own line:
| Line | How | Amount |
|---|---|---|
| First 300 kWh | 300 Γ 0.18 | $54.00 |
| 300β600 kWh | 212 Γ 0.24 | $50.88 |
| Standing charge | 12.00 Γ 31 / 30 | $12.40 |
| Meter rental | as printed | $2.00 |
| Tax 5% | 5% of 119.28 | $5.96 |
| Total | $125.24 |
The sample bills are not typed in: sample_data.dart builds each
one by running this engine over its kWh, and test/engines_test.dart
asserts the August total is $125.24. A figure on a sample bill and the figure
the ledger derives from it cannot disagree.
Rules worth knowing before you change them
- Every line is rounded to the cent as it is made, and the total is the sum of the rounded lines, the way a supplier prints a bill.
- A tier table that stops short of the energy used prices the rest at the last rate rather than dropping it.
- Time of use without a split spreads the energy over the windows by their length (the neutral assumption), and the ledger says so.
- The appliance strip is priced at the average energy rate of your tariff at this month's projected use, so each socket shows its share of the energy part of the bill; standing charges and tax are not spread over appliances.
19The meter window and the forecast
Home opens on a meter window: black glass, a bezel and six digit drums that roll like an odometer, the last one the tenths on an orange ground. Under it a day ruler has a tick for every day of the billing period, the days gone solid and today an orange dot.
Switch to Month end and the drums roll forward to where the meter
will be on the last day of the period; switch back and they roll back. The
drums carry like a mechanical counter: a higher drum only moves while every drum
below it is passing 9 to 0. The widget is MeterWindow in
lib/app/core/widgets/meter_window.dart.
Where the month-end figure comes from
ForecastEngine tries three sources, most trustworthy first, and
Home prints which one it used under the number:
- A meter reading this period. The use since the last bill's closing reading, at the same daily rate to the end of the period. In the sample: 48,698 β 48,217 = 481 kWh in 28 days, so 17.2 kWh a day and 515 kWh over 30 days. A reading is logged from Home with Log a meter reading, under the day ruler.
- The last bill. Its kWh a day, times the days of this period.
- The appliance strip. The listed appliances, for the whole period.
With none of the three there is no number, and Home says what to add. The period starts the day after the last bill ended and runs one month, to the day before the same date next month (a period from the 31st ends inside the next month). When the last bill is older than that, the period rolls forward to the one today is in, so Home never shows a month that has already closed. The meter label under the drums says Meter today only for a reading taken this period; a figure extended from the last bill's closing reading is labelled Meter, estimated.
The projected bill is the current tariff's TariffEngine.cost for
that kWh, with the last bill's lines that no tariff sets (meter rental, a fee)
carried in as extras, the same way the ledger carries them: 515.36
kWh on the tiered tariff is $54.00 + $51.69, plus the $12.00 standing charge for
the 30 days and the $2.00 meter rental, plus 5% tax on all of it, $125.67. So the
month-end figure is comparable with a printed bill line for line.
In Demo mode "today" is fixed at (2026, 9, 28), that is 28 September 2026, so every walkthrough shows the same drums, the same ruler and the same projection.
20The bill ribbon
The Bills tab draws the latest bill as one ribbon that splits: the total on the left, the four bands in the middle (energy, standing charges, taxes, other), and on the right every line the bill printed, grouped by band. Every strand's width is its amount, so the picture adds up the way the bill does.
- A continuous branching band, not bars or rings. The curves
are cubic BΓ©ziers between node edges; nothing here is a chart package. The
widget is
BillRibboninlib/app/core/widgets/bill_ribbon.dart. - The line labels are widgets, not canvas text, so they wrap, translate and are read by a screen reader. Where two small lines sit close, their labels are pushed apart and kept inside the ribbon's height.
- Tap a band or a line to select its band; tap it again to clear. The same ribbon appears on the review screen and on the bill detail.
- A credit (a negative line) is listed with the lines but has no width, because a ribbon cannot be narrower than nothing.
21The ledger
From a bill, Compare opens the ledger: the bill as printed on the left, and on the right either what another tariff would have charged for the same kWh over the same days, or another bill. The two columns are lined up band by band (energy, standing charges, taxes, other), each band with its difference, and the headline says how much more or less the right-hand side comes to.
- Lines no tariff sets are carried across. Meter rental, a
fee or a credit belongs to the bill, not to a tariff, so it appears on both
sides with a difference of nothing, and is taxed on the right the way the bill
taxed it. That is also why the bill's own tariff, on the right, comes to the
printed total:
test/engines_test.dartchecks both. - The standing charge is pro-rated to the bill's own days.
- Bill against bill uses both bills as printed, from the Against chip on the bill detail.
- Every figure is computed on the phone, and the note under the ledger says it is not a supplier quote.
The time-of-use what-if
A bill does not say what time of day its energy was used, so on a
time-of-use tariff the energy is spread over the windows by their length, and
the note says that is an assumption. The switch Move 30% of use to
Off-peak moves 30% of the use outside the cheapest window into it
(TariffEngine.shifted), the "what if the dishwasher ran at night"
figure. The fraction is shiftFraction in
lib/app/modules/compare/compare_controller.dart.
The same engine call gives the Tariffs tab its figures: each tariff card shows what your last bill would have come to on it, through the same comparison.
22The power strip and the timer dial
The Appliances tab is a power strip: a long board with a cable, a master lamp, and one socket card per appliance, two to a row. Each card shows the appliance's photo across its full width, its watts and hours, and what it costs this month.
- Tap a socket to open its sheet with the timer dial. Hold a socket to unplug it or plug it back in; an unplugged appliance stays on the strip and draws nothing.
- The cards are real widgets (
SocketCardinlib/app/core/widgets/socket_card.dart): a rounded card with a socket face cut through its edge, two slots and an earth hole, so the board shows through. The board isPowerStripinpower_strip.dart. - The strip does not measure anything. kWh comes from the watts and hours set here, not from a smart plug; the About screen says the same.
The timer dial
A plug-in timer's face: 24 hours round the edge, 96 notches (one every quarter
hour), and a segment for how long the appliance runs each day. Drag round the
dial to set the hours; every notch passed clicks, like the pins on a mechanical
timer, and the value snaps to quarter hours. The widget is
TimerDial in lib/app/core/widgets/timer_dial.dart.
23Tariffs: flat, tiered and time of use
A tariff is one of three kinds, and the editor changes shape for each:
| Kind | What you enter | Sample |
|---|---|---|
| Flat | One rate per kWh | Flat saver: $0.21 |
| Tiered | Blocks, each with the kWh it runs up to and its rate; the last block has no ceiling | Standard tiered: 0.18 / 0.24 / 0.31 at 300 and 600 kWh |
| Time of use | Windows, each with a label, a from and to time (HH:MM) and a rate; a window may run past midnight and a label may appear twice | Night and day: off-peak 0.11, standard 0.22, peak 0.38 |
Every kind also has a standing charge a month and a tax percent. One tariff is marked This is my tariff: the strip and the month-end figure are priced on it.
Windows with the same label are one group priced at one rate, which is how a card with a morning and an evening peak is entered. Two windows with the same label and different rates are numbered on save (Window, Window 2) so each keeps its own rate. Save tariff refuses a form the engines cannot price and says why: a rate of zero, a tier limit that does not climb, an open limit before the last tier, or a window that starts and ends at the same time.
Filling one in from a rate card
At the top of the editor, Fill in from a photo of a rate card sends
a photo through TariffReadJob. The reply fills the editor and
nothing is saved until the person checks each figure and taps Save
tariff. Rates printed in cents are converted to the main unit; a standing
charge printed per day is multiplied by 30 and the note says so.
24Choosing an AI route
Settings → AI opens the AI and key proxy screen. It chooses who reads the photos:
| Route | Key | Good for |
|---|---|---|
| Demo mode | none | Trying the app and reviewing it. Answers on the device from the sample bills, through the real parser. Does not look at a photo. |
| The included server | on your server | Shipping to people who should never see a key. The app posts to your back end, which holds the keys and runs only the app's three jobs, within a daily limit per device and server-wide daily and monthly caps. |
| Google Gemini | the person's own | The easiest start: a key from AI Studio needs no card. |
| OpenAI | the person's own | Steady at keeping to the reply shape. Needs a payment method. |
| Anthropic Claude | the person's own | Careful with a creased or blurry bill. Needs a payment method. |
All three vendors are called over plain REST with the http
package; there is no provider SDK. A route that is picked but not set up (no
key, no server address) falls back to Demo mode, and the screens say so rather
than failing. Choosing a live route turns Demo mode off, which is the moment the
app starts keeping the person's own bills.
Keys
A pasted key goes into the platform's encrypted store and is read back for
one request at a time, only by AiService. The screen shows whether a
key is saved, never the key. Every vendor's key page and rate-limits page are
linked from its card; no free allowance is quoted as a number, because vendors
change them.
Model names expire
Vendors retire model names every so often, and a retired name answers with an error the app turns into "The model is no longer available". Two places hold model names, and they are separate:
| Route | Default as shipped | Change it in the app | Change the default |
|---|---|---|---|
| Gemini | gemini-3.1-flash-lite | The Model name field on that route's card; it is kept per route and a blank field goes back to the default | lib/app/data/providers/gemini_provider.dart:32 |
| OpenAI | gpt-5 | lib/app/data/providers/openai_provider.dart:26 | |
| Claude | claude-opus-5 | lib/app/data/providers/claude_provider.dart:39 | |
| Your server | gpt-4o-mini, claude-haiku-4-5-20251001,
gemini-2.5-flash | not from the app: the app sends no model name on this route | The admin panel's AI proxy page, or the defaults at
app/Models/AiSetting.php:32 |
Each card links to the vendor's current model list. A model you choose must accept images: reading a bill is a vision job.
The included server
Enter the server's address on the The included server card
(origin only, such as https://<your-domain>) and Test the
connection. The app trades a random 32-character device key, made once per
install and not an OS device id, for a bearer token at
POST /api/ai/device, then reads bills through
POST /api/ai/chat. The card shows the server's own answer from
GET /api/ai/status: which vendors it has keys for and how many of
today's requests this device has used.
On this route the app sends no prompt. It names the job
(bill_read, tariff_read or why) and sends
that job's input: the photograph, or the month's figures for Why this month.
The server holds each job's instruction in config/ai_tasks.php
and chooses the provider and model itself, so a token copied off a phone can
only run these three jobs. The wording there is the same text the direct
routes send; test/proxy_tasks_sync_test.dart fails if the two
copies drift, so edit both together.
The server's chat route is provider-neutral, so there is nowhere on it to hang a structured-output schema. The server's instruction carries the schema instead, and the app reads the reply defensively (a code fence is unwrapped, prose before or after the object is trimmed), then runs the same parser. That is weaker than the direct routes' schema enforcement, which is why it is stated here. If the server revokes the token (a blocked device, a rebuilt database), the app registers once more and retries once; it never loops.
Spending caps on your server
Every request on this route is paid from your provider account, so the AI proxy page has four limits. The first is per device; the other three count the whole server, so they hold however many devices register:
| Setting | Default | What it stops |
|---|---|---|
| Requests per device per day | 200 | one phone using more than its share |
| Requests per day, all devices | 2,000 | a busy or abused day running away |
| Tokens per month, all devices | 5,000,000 | the month's bill passing what you budgeted |
| New devices per network per day | 20 | a script registering device after device for fresh allowances |
Accept new devices switches registration off altogether; phones
already registered keep working. 0 turns a numeric cap off. Behind a reverse
proxy or Cloudflare, set TRUSTED_PROXIES so the per-network count sees
each phone's own address rather than the proxy's. Work the token budget out
from your provider's current price per million tokens.
Recommended spending limits at each provider
Set a hard limit where the bill is issued as well, so a mistake in one place is caught by the other, and use a key made for this server only.
- OpenAI: create a project for this server, use a key from that project, and set the project's monthly budget and usage limits.
- Anthropic: use a key from a workspace of its own and set that workspace's spend limit in the Console.
- Google Gemini: use a Google Cloud project of its own, set a budget with alerts in Cloud Billing, and lower the Generative Language API's requests per day quota for that project.
A sensible start is the monthly amount you would accept losing, for example US$20 to US$50 while you launch; raise it once the panel's Usage page shows what real users cost.
Locking the proxy to your app (App Check)
Optional, and off until you turn it on. Firebase App Check proves a request comes from your published app: Play Integrity on Android, App Attest or DeviceCheck on iOS, behind one token. With it enforced, a script that copied a device key off a phone still cannot call the proxy.
- Configure Firebase for the app (chapter What is left for you to wire up) and register the app in the Firebase console's App Check page with Play Integrity and App Attest.
- Add the
firebase_app_checkpackage, and inmain.dart, after Firebase starts, callFirebaseAppCheck.instance.activate(...)with those two providers. - Hand the app the token:
SettingsService.appCheckTokenSource = () => FirebaseAppCheck.instance.getToken();. The proxy route then sends it asX-Firebase-AppCheckwhen it registers and on every AI request, the two routes the server checks. - On the server, set
FIREBASE_CREDENTIALSand thenAI_APP_CHECK=enforcein.env. Do this last: once it is on, a phone that sends no token is refused.
Photos kept on the server
On this route the server also keeps a copy of every bill and rate-card photo
the phone holds, so whoever runs the server has the pictures the AI read, not
only the figures. PhotoSync
(lib/app/data/services/photo_sync.dart) does it:
- When: about 10 seconds after a bill, an appliance or a tariff changes, and each time the app comes back to the foreground.
- Once per photo: it asks
GET /api/mediawhat the server holds (each file's name and SHA-256) and sends only what is new or changed, onePUT /api/media/<name>per file. - Only with a device token. The first bill read registers the install; until then there is nothing to send with. With the person's own key, in Demo mode or with no server address, nothing is sent.
- Silently. A photo that does not go now goes on the next change or the next return to the foreground; the screens show nothing either way, and a failure is at most counted in crash reports, when that pack is on.
The pictures appear on the panel's Pictures page under Device #n Β· platform (or the label you gave the device). Nothing is pulled back to a phone: a new phone registers as a new device and starts empty. Deleting a bill on the phone does not delete the server's copy, and deleting a picture on the panel while the phone still has it only lasts until the next sync, which sends it again.
Error handling
Every failure is a ProviderException carrying a translation key,
so what the person reads is a sentence in their language with a next step, and
the raw response is behind Details for the developer.
| What happened | Key | What the person reads, in short |
|---|---|---|
| No key saved for a key route | err.missing_key | Add a key in Settings, or switch on Demo mode. |
| Vendor 401 / 403 | err.invalid_key, err.forbidden | The key was rejected, or accepted but refused (usually region or project). |
| Vendor 404 on the model | err.model_not_found | The model name is no longer available; enter a current one. |
| Vendor 429 | err.quota | The quota is used up for now. |
| Reply cut off | err.truncated | Run it again; it usually fits. |
| No server address | err.server_unset | Enter the address of your back end, or use your own key. |
| Server 401 after one re-registration | err.server_rejected | Check the address points at the right site. |
| Server 403 | err.device_blocked | This device was blocked on the server. |
| Server 413 | err.too_large | The photo is larger than the server accepts. |
| Server 429 | err.daily_limit | This device, or the server as a whole, used today's or this month's allowance. |
| Server 503 / 504 | err.server_off | The proxy is off, or has no key for that vendor. |
| No response | err.network, err.server_unreachable | Could not reach the service; Demo mode works offline. |
| Anything unparseable | err.bad_response | The reply was not in the expected format. |
A failed read loses nothing: bills, appliances and tariffs are as they were, and the lines can be typed in by hand.
25Signing in
The email and password form is a demo. Sign in and
Sign up wait a moment and open the app (lib/app/modules/auth/auth_controller.dart:72); no request is made,
and a line under each form says so. The sign-in fields arrive filled with the
demo account the back end also seeds, so a reviewer can press Sign in
without typing. Joulora keeps its records on the phone and
needs no account to work, so the form is there as the seam most buyers want,
drawn in the right place.
- Google and Apple (the
qh_social_loginpack) are real sign-ins once configured. WithAPI_BASE_URLset at build time, the id token is exchanged atPOST /api/auth/socialfor a Sanctum token, kept in the encrypted store. Without it they are as mock as the form. In Demo mode a fake provider stands in for both. - The back end has real account routes
(
POST /api/auth/register,POST /api/auth/login,GET /api/auth/me,POST /api/auth/logout), seeded with a demo account. The app's form does not call them as shipped; the wire-up chapter shows the change that makes it. - Bill reading does not use an account. The key proxy identifies installs by a device key, not by a person, so the included server works whether or not anyone signs in.
- Forgot password? opens a note: password reset belongs to your server, and is listed in the wire-up chapter.
26What is left for you to wire up
The app is complete for what it does. These are the pieces a real product connects that no template can connect for it, each with the exact place it goes.
Connect your backend to the sign-in form
The form is a demo (see Signing in). To sign in against the included back
end, replace the body of login() in
lib/app/modules/auth/auth_controller.dart, and
register() the same way with /api/auth/register:
Future<void> login() async // lib/app/modules/auth/auth_controller.dart
// before
isLoading.value = true;
await _fakeCall();
isLoading.value = false;
Get.offAllNamed(Routes.main);
// after
isLoading.value = true;
final res = await http.post(
Uri.parse('${FeatureConfig.apiBaseUrl}/api/auth/login'),
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: jsonEncode({'email': emailCtrl.text, 'password': passwordCtrl.text}),
);
isLoading.value = false;
if (res.statusCode != 200) return; // show the server's message
final token = jsonDecode(res.body)['token'] as String;
await const FlutterSecureStorage().write(key: SocialAuthApi.tokenKey, value: token);
Get.offAllNamed(Routes.main);
Storing the token under SocialAuthApi.tokenKey keeps password
and social sign-ins in one place. Password reset needs a route on your server
(Laravel's own password broker; mail is set up by the MAIL_* keys)
and a call from the Forgot password? link in
login_view.dart.
Real in-app purchases
Product ids in FeatureConfig.iapProductIds and
--dart-define=IAP=on (the chapter Setting up in-app purchases). The purchase is cached
on the phone, so a buyer opens the app as Pro offline. Receipt validation is
yours: StorePurchaseGateway takes a verify callback,
and returning false refuses the purchase.
final Future<bool> Function(PurchaseDetails details)? verify; // packages/qh_iap/lib/src/store_purchase_gateway.dart
Firebase: push and analytics
lib/firebase_config.dart ships with
firebaseConfigured = false and lib/firebase_options.dart
holds deliberately invalid placeholders; the feature packs chapter has both the
flutterfire configure path and the no-terminal one. The admin panel
sends to every install through the topic. To notify one install (say, when a
month is running ahead), store the token qh_push reports against
that install's row in devices, through a route of your own, and send
to it from the server.
Another AI vendor
Write a class that implements AiAdapter, add a
ProviderConfig to ProviderCatalog.all and register the
adapter in AiService. No screen changes. Its model must read
images.
Future<Map<String, dynamic>> complete( // lib/app/data/providers/ai_adapter.dart
required PromptSpec spec, required String apiKey, String model = '',
});
What the app does not do, by design
It does not log in to a supplier, pay a bill or read a smart meter; tariffs are
typed in or read off a photo, and appliance kWh comes from watts and hours. A
supplier or smart-meter integration would be a new data source feeding
EnergyService, the one place every figure is derived.
Where the numbers live
Every tunable constant, with its file and line:
| What | Where | Now |
|---|---|---|
| Bills the free plan keeps | lib/app/data/services/subscription_service.dart:116 | 12 |
| Largest photo the app sends, base64 | lib/app/data/services/ai_service.dart:48 | 1200 * 1024 bytes |
| Photo long edge and JPEG quality | lib/app/data/services/photo_store.dart:41 | 1800 px, 85 |
| How long a provider may take | lib/app/data/providers/ai_adapter.dart:16 | 120 s |
| Charge lines read from one bill | lib/app/data/providers/bill_read_job.dart:29 | 12 |
| Sentences in Why this month | lib/app/data/providers/why_job.dart:13 | 3 |
| Output tokens per job (server, before the ceiling) | config/ai_tasks.php:124 | 2000 |
| Share moved to the cheapest window in the what-if | lib/app/modules/compare/compare_controller.dart:22 | 0.3 |
| Demo mode's pause before it answers | lib/app/data/providers/demo_provider.dart:32 | 1200 ms |
| Demo mode's "today" | lib/app/data/mock/sample_data.dart:17 | 28 Sep 2026 |
| Currency symbol before a person sets one | lib/app/data/services/settings_service.dart:67 | $ |
| Requests per device per day (server) | app/Models/AiSetting.php:35 | 200 |
| Output-token ceiling (server) | app/Models/AiSetting.php:36 | 2048 |
| Largest image the server accepts | config/companion.php:34 | 1258291 bytes |
| Images per request (server) | config/companion.php:38 | 2 |
The two image limits have to agree: the app refuses a photo it knows the
server will reject, so raise maxImageBytes and
AI_MAX_IMAGE_BYTES together or one of them does nothing.
27What the back end is
backend/ is a Laravel 13 application with Filament 5 and
Sanctum, set up as a key proxy. It is included so that the
people who install your app never need an API key of their own: the app posts
the bill photo to your server, your server adds the key it holds and forwards
the request to OpenAI, Anthropic or Gemini, and the answer comes back.
- Devices, not accounts. Each install registers a random device key and gets a bearer token. The Devices page lists them; label one, block one (its token is revoked on the spot), see its request count.
- A daily limit per device (200 requests out of the box,
0 for none), counted per device key and reset at midnight in the server's
APP_TIMEZONE, so one install cannot run up your bill. - Server-wide caps that hold however many devices register: requests per day and tokens per month across all devices, at most 20 new devices per network per day, and a switch that stops new devices joining (see Spending caps on your server).
- Fixed jobs. The prompt for each of the app's three jobs
is in
config/ai_tasks.php; the app names a job and sends its input, never a prompt or a model. - A usage log. Every call is a row: provider, model, tokens
in and out, latency, and
ok,error,quotaorblocked. The dashboard charts it. - Provider keys held server-side, encrypted with
APP_KEY, set on the AI proxy page or in.env(the panel wins). The same page sets the provider and the model every request uses, the caps above and an output-token ceiling. - Pictures. Every bill and rate-card photo the app has stored on the server (see Choosing an AI route), with a thumbnail, the device it came from, its size and a Delete action.
- App updates. Announce a release: the latest version, the
oldest one still allowed to run, what the update prompt says, the store links
and when it goes live.
GET /api/versionanswers with the newest published row, and with the.envvalues only while there is none. - Send notification and Push history. Push to every install now or at a time you pick; every send is recorded with its status, and a scheduled one can be canceled until it goes.
- The accounts, version and social routes the feature packs
use, including
POST /api/auth/apple/callback, the return URL for Sign in with Apple on Android.
The app also works without it: with a key of the person's own on any of the three vendor routes, or in Demo mode. The back end is what lets you ship the app to people who will never paste a key.
What is inside
| Folder | What |
|---|---|
app/Models | Device,
AiUsageLog, AiSetting (one row), plus
User, AppSetting, MediaFile (a stored
picture), AppRelease and PushSend. |
app/Services/Ai | ProxyService (settings,
quota, size checks, adapter, usage row) and one adapter per vendor, which turns
the neutral request into that vendor's own format, images included. |
app/Http/Controllers/Api | The REST controllers:
AiProxyController, AuthController,
SocialAuthController, AppleCallbackController,
VersionController, MediaController. |
app/Filament | The panel: Dashboard, Users, AI proxy, Devices, Usage, Pictures, App updates, Settings, Send notification, Push history. |
database/seeders | An admin, a demo account, three demo devices with two weeks of usage, a bill photo and a meter photo on the first of them, sample releases and push records, all flagged as demo data. |
tests | Pest: device registration, the proxy for each vendor, limits, image checks, reply language, accounts, social sign-in, the version route, panel pages. |
docs/DEPLOY.md | The deployment material from the next chapter, in a file you can hand to whoever runs the server. |
From here on, anything in <angle brackets> is a value you
supply and the brackets are not part of it.
28Putting it on a server
Three routes. Pick the one that matches your host. Whichever you choose, PHP must be 8.4 or newer.
A. Docker, if you have it
# in backend
docker compose up -d --build
This starts MySQL 8 and the app on http://127.0.0.1:8000 (panel
at /admin). On every start the container generates the application
key only if .env has none yet, runs the migrations (additive: they
only create what is missing) and runs the seeder, which skips itself once the
demo admin exists. So a restart, a reboot of the machine or an upgrade of the
image keeps every device, usage row, account and saved key. Pictures are the
exception: they are files in the app container's
storage/app/private/media/, which is not a volume, so a rebuilt or
recreated container starts without them, while the database still lists them, so
their thumbnails break and the phones, seeing a matching list, do not send them
again. Add a volume for that folder in docker-compose.yml before you
rely on them. Stop it with
docker compose down; docker compose down -v also deletes
the database volume, and the next start begins from an empty database with the
demo data. If docker compose up cannot pull its images, your network
is blocking Docker Hub; that is the network, not the project, and routes B and C
need no Docker.
B. A terminal on a server you control
# in backend
./install.sh
The script checks your PHP version and Composer, copies
.env.example to .env if there is none, installs the
dependencies, generates the application key, creates the SQLite file if that is
the database, runs the migrations, seeds the demo data and makes the writable
folders writable. It stops with a readable message rather than a stack trace if
PHP is too old. Then point your web server's document root at
<path-to-backend>/public, not at the folder above it, which
holds .env.
C. Shared hosting, with cPanel and no terminal
- In cPanel, open MultiPHP Manager and set the domain to PHP 8.4 or newer. If the list stops at 8.3, ask your host to enable 8.4; this back end will not run below it.
- Create a MySQL database and a user, and give the user all privileges on it. Note the database name, the user and the password.
- Upload the contents of
backend/above your public folder, and the contents ofbackend/public/intopublic_html/. - Open
public_html/index.phpand fix therequirepaths so they point at where you put the rest. - Copy
.env.exampleto.envand fill inAPP_URL,DB_CONNECTION=mysql,DB_DATABASE,DB_USERNAME,DB_PASSWORD, and at least one ofAI_OPENAI_KEY,AI_ANTHROPIC_KEY,AI_GEMINI_KEY(or paste a key into the panel later). - Open cPanel's Terminal once for
php artisan key:generateandphp artisan migrate --seed, the only commands this route needs. No terminal at all?docs/DEPLOY.mdhas the phpMyAdmin route. - Make
storage/andbootstrap/cache/writable (file manager → Permissions), then visithttps://<your-domain>/admin.
The server needs outbound HTTPS to api.openai.com,
api.anthropic.com and
generativelanguage.googleapis.com; a few hosts block outbound
requests on their cheapest plans.
The scheduler (one cron line)
Notifications scheduled with Send notification → Send later go out from Laravel's scheduler, which needs one line in the server's crontab (cPanel: Cron Jobs, every minute):
* * * * * cd <path-to-backend> && php artisan schedule:run >> /dev/null 2>&1
With Docker there is nothing to add: the app container runs the
scheduler itself. Without the line the panel
still works; a notification scheduled for later just stays
Scheduled. Times are read in APP_TIMEZONE.
Pictures users take
The photos the app stores through /api/media are files under
storage/app/private/media/, outside the web root. Back that folder
up together with the database: the database lists the pictures and the folder
holds them.
Signing in the first time
| Account | Password | |
|---|---|---|
| Admin (the panel) | admin@joulora.test |
password |
| Demo account (the account routes) | demo@joulora.app |
demo1234 |
Change the admin password, set APP_ENV=production and
APP_DEBUG=false, set the per-device and server-wide caps on the
AI proxy page to what you are willing to pay for (and a spending limit
at the provider), and run php artisan demo:clear (or
Settings → Clear demo data) to remove the demo accounts, devices
and usage rows. Back up .env and
storage/app/private/media/ with the database: the keys saved in the
panel are encrypted with its APP_KEY, and the folder holds the
pictures.
/admin.29Pointing the app at it
Two ways to bake the address into a build, and a third for a single phone.
From the command line
flutter run --dart-define=API_BASE_URL=https://<your-domain>
flutter build appbundle --dart-define=API_BASE_URL=https://<your-domain>
flutter build ipa --dart-define=API_BASE_URL=https://<your-domain>
By editing a file
If you build from Android Studio or VS Code, open
lib/app/core/values/feature_config.dart and give the constant a
default. The line as shipped:
static const apiBaseUrl = String.fromEnvironment('API_BASE_URL');
becomes:
static const apiBaseUrl = String.fromEnvironment('API_BASE_URL',
defaultValue: 'https://<your-domain>');
That is the whole change. A --dart-define still wins when it is
passed.
Or on one phone, in Settings
Settings → AI → The included server → Server address. This routes bill reading through your server on that phone and overrides the built-in address. It is the quickest way to test a server, but it only affects the AI route and the photo copies that go with it: the version prompt and the Google / Apple exchange read the build-time address only.
Give the origin only: https://example.com, not
https://example.com/api; the app appends
/api/ai/β¦ itself. A trailing slash is removed. On a real phone,
127.0.0.1 is the phone: use your computer's LAN address while
testing.
What happens next
A build with a built-in address opens with Demo mode off and the included
server chosen as the route, so the first bill a person photographs is read
through your server. The first request registers the install
(POST /api/ai/device) and it appears on the panel's
Devices page; each read is a row on Usage, and the photos
start to appear on Pictures shortly after. A person can still
switch to their own key or back to Demo mode in Settings.
30HTTP or HTTPS
Both platforms refuse plain HTTP by default, and quietly enough that it looks like the server is down.
Android
Cleartext traffic is off by default. For development only, add to
android/app/src/main/AndroidManifest.xml:
<application android:usesCleartextTraffic="true" β¦>
For anything narrower, use a network_security_config.xml that
allows the one development host, referenced with
android:networkSecurityConfig.
iOS
App Transport Security refuses http:// the same way. For
development only, in ios/Runner/Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key><true/>
</dict>
NSAllowsLocalNetworking covers a server on your own network
without opening the app to plain HTTP everywhere, which
NSAllowsArbitraryLoads would.
What this project ships with
Neither exception is in the source. The main Android manifest
declares INTERNET (Flutter only writes it into the debug manifest,
so a release build without it would fail every request),
USE_BIOMETRIC, POST_NOTIFICATIONS and
BILLING, and no cleartext flag; the plist has no ATS block. The
simulator reaches http://127.0.0.1 anyway, because iOS exempts it;
a physical phone does not.
In production, use HTTPS
A bill photo and a bearer token travel on every read, and on plain HTTP they travel in the clear to everyone on the same network. A Let's Encrypt certificate is free and most panels issue one in a couple of clicks. Remove any development exception before a release build.
31API reference
Every endpoint, 17 in all, as php artisan route:list
--path=api reports them. "Device" means a token from
/api/ai/device; "user" means one from the account routes. The AI
routes take a device token only and refuse a user token with a 403; the picture
routes take either, and each token sees only its own pictures.
| Method | Path | Auth | Body / returns |
|---|---|---|---|
POST | /api/ai/device | no | device_key (16 to 64 of A-Z a-z 0-9 _ -), platform, app_version → 201, token + device. Re-posting rotates the token. A new key is refused with 429 past the per-network daily cap, and with 403 while new devices are switched off. |
GET | /api/ai/status | device | enabled, default provider, each provider's availability, the job names it runs, the daily limit and this device's requests today, the token ceiling |
DELETE | /api/ai/device | device | Settings → Delete account: this device, its request log and every picture it stored, 204 |
POST | /api/ai/chat | device | task (a job in config/ai_tasks.php), input?, images?[{mime, data}], reply_in_user_language? → provider, model, text, usage, finish_reason. The server holds the prompt, provider, model and limits; the app cannot send them. |
POST | /api/auth/register | no | name, email, password → 201, token + user (403 if sign-up is switched off in Settings) |
POST | /api/auth/login | no | email, password → token + user |
POST | /api/auth/social | no | provider, id_token → token + user (503 until client ids are set) |
GET | /api/auth/me | user | the signed-in user |
POST | /api/auth/logout | user | revokes the token, 204 |
DELETE | /api/auth/me | user | Settings → Delete account: the account and its tokens, 204 (403 for the owner account) |
POST | /api/auth/apple/callback | no | Sign in with Apple's return URL on Android: Apple posts here and the server sends the phone back into the app with the same fields (303). 503 until APPLE_ANDROID_PACKAGE is set. |
GET | /api/version | no | latest, minimum, message, android_url, ios_url: the newest published row of App updates, or the .env values while there is none |
GET | /api/media | device or user | the caller's pictures (name, SHA-256, size), used_bytes, max_total_bytes, file_max_bytes |
PUT | /api/media/{name} | device or user | the picture's raw bytes as the body (JPEG, PNG, WebP, HEIC / HEIF or GIF, checked from the bytes) → 201, or 200 when it replaced a file or the same bytes were already there (a no-op). 413 over MEDIA_FILE_MAX_BYTES or when the caller's total would pass MEDIA_MAX_TOTAL_BYTES; 415 when it is not a picture; 422 when empty. |
GET | /api/media/{name} | device or user | the picture's bytes, 404 if the caller has none by that name |
DELETE | /api/media/{name} | device or user | deletes it, 204 |
GET | /api/media-preview/{media} | signed link | the picture behind a panel thumbnail; the panel makes these links itself, valid for ten minutes |
The routes that issue a token, and the Apple return URL, are limited to 10 requests a minute per address; everything else to 120 a minute per token.
Authentication headers
Authorization: Bearer <token>
Accept: application/json
Content-Type: application/json (on POST)
Leave Accept off and a validation failure comes back as an HTML
page, the most common reason a client reports "invalid JSON" against a server
that is working. The app also sends Accept-Language, and the server
answers its errors in that language where it has a translation.
The three most used, in full
Register a device
curl -X POST https://<your-domain>/api/ai/device \
-H 'Accept: application/json' -H 'Content-Type: application/json' \
-d '{"device_key":"q7Zc2Lw9-Hf3xN0aRk5vT8mBy1sDe6Pu","platform":"ios","app_version":"1.0.0"}'
{
"token": "4|Xk2mβ¦",
"device": { "id": 4, "platform": "ios" }
}
Ask what the server can do
curl https://<your-domain>/api/ai/status \
-H 'Accept: application/json' -H 'Authorization: Bearer <token>'
{
"enabled": true,
"default_provider": "openai",
"providers": {
"openai": { "available": true },
"anthropic": { "available": false },
"gemini": { "available": false }
},
"tasks": ["bill_read", "tariff_read", "why"],
"daily_request_limit": 200,
"requests_today": 3,
"max_output_tokens": 2048
}
Read a bill
curl -X POST https://<your-domain>/api/ai/chat \
-H 'Accept: application/json' -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <token>' \
-d '{
"task": "bill_read",
"images": [{ "mime": "image/jpeg", "data": "<base64>" }]
}'
{
"provider": "openai",
"model": "gpt-4o-mini",
"text": "{\"period_start\":\"2026-08-01\",\"period_end\":\"2026-08-31\",\"kwh\":512, β¦ \"total\":125.24,\"confidence\":\"high\"}",
"usage": { "prompt_tokens": 1320, "completion_tokens": 214 },
"finish_reason": "stop"
}
The model's answer is a string in text; the app parses it. The
server checks, in order: the proxy is on (503), the device is not blocked
(403), the job exists (422), the device's daily limit, the server's daily
limit and the month's token budget (429), a key for the provider (503), the
job's text size (413), then the job's number of images (one for each reader,
none for Why this month, never more than 2), each at most 1258291 bytes of valid base64 (413 or 422). Anything else in the
body, such as a system or model field, is ignored. A provider it cannot reach is a 504. Every outcome, refused
ones included, is written to the usage log.
124 Pest tests cover these routes.
32Environment variables
Every environment variable in .env.example is on this page, so
you can check your file against it line by line. Copy .env.example
to .env and fill in the ones you need; the rest have working
defaults.
The ones you will set
| Key | Type | Default | What it does |
|---|---|---|---|
APP_NAME | text | Joulora | The name in the panel's title bar and in mail. |
APP_ENV | text | local | Set it to production on a live server. |
APP_KEY | text | required | Encryption key, also for the provider keys saved in the panel. php artisan key:generate writes it. Change it and those saved keys can no longer be read. |
APP_DEBUG | boolean | true | π΄ false in production. Left true, an error page shows your configuration to whoever triggered it. |
APP_URL | url | http://localhost | Used to build absolute links and the panel's assets. Set it to your real domain. |
APP_TIMEZONE | text | UTC | The zone "today" and "tomorrow" and every scheduled time are read in: the per-device daily limit's midnight, a notification sent later. For example Europe/London. |
TRUSTED_PROXIES | list | empty | Set it behind a load balancer or Cloudflare, or every install shares one registration rate limit. |
DB_CONNECTION | text | sqlite | sqlite, mysql or pgsql. |
SESSION_DRIVER | text | database | Where panel sessions live. |
CACHE_STORE | text | database | file is fine on shared hosting. |
QUEUE_CONNECTION | text | database | Nothing here queues work; leave it. |
LOG_CHANNEL | text | stack | Where storage/logs gets written. |
LOG_LEVEL | text | debug | error in production keeps the log small. |
AI_OPENAI_KEY | text | empty | OpenAI key, used when none is saved on the AI proxy page. |
AI_ANTHROPIC_KEY | text | empty | The same for Anthropic. |
AI_GEMINI_KEY | text | empty | The same for Gemini. |
AI_TIMEOUT_SECONDS | number | 90 | How long the server waits for a provider. Commented out in the file as shipped. |
AI_MAX_IMAGES | number | 2 | Images allowed in one request. Commented out in the file as shipped. |
AI_MAX_IMAGE_BYTES | number | 1258291 | Largest image, as base64 characters. Raise it with the app's maxImageBytes, never alone. Commented out in the file as shipped. |
APP_LATEST_VERSION | text | 1.0.0 | The version /api/version reports as current while no App updates row is published. Once one is, the panel wins. |
APP_MINIMUM_VERSION | text | 1.0.0 | Below this, the update prompt has no Later. Fallback, like the line above. |
APP_UPDATE_MESSAGE | text | empty | The sentence in the update prompt. Fallback. |
APP_STORE_URL_ANDROID | url | empty | Where the prompt's Update button goes on Android. Fallback. |
APP_STORE_URL_IOS | url | empty | The same on iOS. Fallback. |
MEDIA_FILE_MAX_BYTES | number | 2097152 | Largest picture /api/media stores (2 MB). A photo at the app's settings is a few hundred KB. Past 8 MB, raise post_max_size and upload_max_filesize in php.ini above it too. |
MEDIA_MAX_TOTAL_BYTES | number | 209715200 | Picture space per device or account (200 MB). Past it, a new picture is refused with 413 and the phone tries again later. |
GOOGLE_CLIENT_IDS | list | empty | OAuth client ids accepted by /api/auth/social for Google, comma-separated. |
APPLE_CLIENT_IDS | list | empty | Bundle / Services ids accepted for Apple. |
APPLE_ANDROID_PACKAGE | text | empty | Sign in with Apple on Android only: the app's Android package name. /api/auth/apple/callback sends the phone back into that app, and answers 503 while this is empty. |
AI_APP_CHECK | off / enforce | off | enforce refuses device and chat requests without a valid Firebase App Check token. Needs FIREBASE_CREDENTIALS and App Check on in the app first. Commented out in the file as shipped. |
FIREBASE_CREDENTIALS | path | storage/app/firebase-service-account.json | The Firebase service-account JSON the Send notification page uses. Keep it outside public/. |
Everything else in the file
Laravel's own defaults. Most are read only if you switch a driver above to something other than what this back end ships with.
| Key | Default | What it does |
|---|---|---|
APP_LOCALE | en | Language for panel text, dates and validation messages. |
APP_FALLBACK_LOCALE | en | Used when a string is missing in the locale above. |
APP_FAKER_LOCALE | en_US | Only used by test factories. |
APP_MAINTENANCE_DRIVER | file | Where php artisan down keeps its flag. |
APP_MAINTENANCE_STORE | database | Cache store for the flag, when the driver is a cache. Commented out in the file as shipped. |
PHP_CLI_SERVER_WORKERS | 4 | Workers for artisan serve only. Commented out in the file as shipped. |
BCRYPT_ROUNDS | 12 | Password hashing cost. Higher is slower and safer. |
LOG_STACK | single | Which channels the stack channel writes to. |
LOG_DEPRECATIONS_CHANNEL | null | Where PHP deprecation notices go. |
DB_HOST | 127.0.0.1 | Only read when DB_CONNECTION is not sqlite. On MySQL, DB_DATABASE is the database name, not a path. Commented out in the file as shipped. |
DB_PORT | 3306 | Only read when DB_CONNECTION is not sqlite. On MySQL, DB_DATABASE is the database name, not a path. Commented out in the file as shipped. |
DB_DATABASE | laravel | Only read when DB_CONNECTION is not sqlite. On MySQL, DB_DATABASE is the database name, not a path. Commented out in the file as shipped. |
DB_USERNAME | root | Only read when DB_CONNECTION is not sqlite. On MySQL, DB_DATABASE is the database name, not a path. Commented out in the file as shipped. |
DB_PASSWORD | empty | Only read when DB_CONNECTION is not sqlite. On MySQL, DB_DATABASE is the database name, not a path. Commented out in the file as shipped. |
SESSION_LIFETIME | 120 | Minutes before a panel session expires. |
SESSION_ENCRYPT | false | Whether Laravel encrypts the panel's session data. |
SESSION_PATH | / | Cookie path for the panel session. |
SESSION_DOMAIN | null | Cookie domain. Leave null unless you run subdomains. |
BROADCAST_CONNECTION | log | Event broadcasting. Nothing here broadcasts. |
FILESYSTEM_DISK | local | Default disk. The pictures in /api/media always go to the local disk (storage/app/private/), whatever this says. |
CACHE_PREFIX | empty | Prefix for cache keys, if you share a cache server. Commented out in the file as shipped. |
MEMCACHED_HOST | 127.0.0.1 | Only read when CACHE_STORE is memcached. |
REDIS_CLIENT | phpredis | Only read when a cache, queue or session driver is set to redis. |
REDIS_HOST | 127.0.0.1 | Only read when a cache, queue or session driver is set to redis. |
REDIS_PASSWORD | null | Only read when a cache, queue or session driver is set to redis. |
REDIS_PORT | 6379 | Only read when a cache, queue or session driver is set to redis. |
MAIL_MAILER | log | Outgoing mail. Ships as log, which writes mail to storage/logs instead of sending it. |
MAIL_SCHEME | null | Outgoing mail. Ships as log, which writes mail to storage/logs instead of sending it. |
MAIL_HOST | 127.0.0.1 | Outgoing mail. Ships as log, which writes mail to storage/logs instead of sending it. |
MAIL_PORT | 2525 | Outgoing mail. Ships as log, which writes mail to storage/logs instead of sending it. |
MAIL_USERNAME | null | Outgoing mail. Ships as log, which writes mail to storage/logs instead of sending it. |
MAIL_PASSWORD | null | Outgoing mail. Ships as log, which writes mail to storage/logs instead of sending it. |
MAIL_FROM_ADDRESS | hello@example.com | Outgoing mail. Ships as log, which writes mail to storage/logs instead of sending it. |
MAIL_FROM_NAME | ${APP_NAME} | Outgoing mail. Ships as log, which writes mail to storage/logs instead of sending it. |
AWS_ACCESS_KEY_ID | empty | Only read when a disk is set to s3. |
AWS_SECRET_ACCESS_KEY | empty | Only read when a disk is set to s3. |
AWS_DEFAULT_REGION | us-east-1 | Only read when a disk is set to s3. |
AWS_BUCKET | empty | Only read when a disk is set to s3. |
AWS_USE_PATH_STYLE_ENDPOINT | false | Only read when a disk is set to s3. |
VITE_APP_NAME | ${APP_NAME} | Only read by a front-end build, which this back end does not use. |
71 of the 71 keys in .env.example, counted when
this page was built.
Read by the back end but not in the file
config/companion.php also reads these. Add them to
.env only if you need them:
| Key | What it does |
|---|---|
AI_ANTHROPIC_ENDPOINT | The Anthropic endpoint. |
AI_GEMINI_ENDPOINT | The Gemini endpoint. |
AI_MAX_INPUT_CHARS | A ceiling over every job's own text limit in config/ai_tasks.php, in characters (images are counted separately). Default 60000. |
AI_OPENAI_ENDPOINT | The OpenAI endpoint, for a compatible gateway. |
php artisan config:clear. Laravel caches the configuration, and
a changed key behind a stale cache is the most common "I set it and nothing
happened".
33Everyday jobs without a terminal
Everything the server does day to day is in the panel. This chapter covers the jobs that usually want a terminal, done without one. The one thing that runs on a timer is a notification scheduled for later, and that needs the scheduler's cron line from the chapter on putting it on a server.
| Job | In the panel | In cPanel or phpMyAdmin |
|---|---|---|
| Add or replace a provider key | AI proxy → the key field, Save | or AI_*_KEY in .env with the file manager |
| Change the model when a name is retired | AI proxy → the provider's model | |
| Switch the proxy off for a while | AI proxy → Proxy switched on; the app then says the server is not answering, and the person can switch to their own key or Demo mode | |
| Change the daily limit | AI proxy → Requests per device per day (0 = none) | |
| Stop one install using the proxy | Devices → Block on its row (its token is revoked) | |
| See what it is costing | Usage, filtered by provider or status; tokens in and out per call | |
| Tell every install something | Send notification (needs the Firebase key); fill Send later to schedule it | |
| See what was sent, or stop a scheduled one | Push history → Cancel on a scheduled row | |
| Ask everyone to update the app | App updates → New: latest and minimum version, the message, the store links, when it goes live | |
| See or delete the photos an install sent | Pictures → Delete on a row, or select several. A photo the phone still holds is sent again on its next sync. | |
| Remove an install and what it left here | Devices → Delete on its row; its usage rows and pictures go with it | |
| Stop people creating accounts | Settings → Let new users sign themselves up | |
| Add an administrator | Users → New, role admin | |
| Back up the database | phpMyAdmin → the database → Export → Quick → SQL. Keep the file, a copy of .env and the folder storage/app/private/media/ (file manager → Compress) off the server. | |
| Restore a backup | phpMyAdmin → Import → the .sql file. | |
| Clear the demo data | Settings → Clear demo data. It removes only the seeded records (the demo pictures, releases and push records included) and asks first. | cPanel Terminal: php artisan demo:clear does the same. |
GUI tools that work with this back end
- phpMyAdmin, on nearly every shared host.
- TablePlus or Sequel Ace, a desktop client over SSH, if your host allows it.
- DB Browser for SQLite, which opens
database/database.sqlitedirectly on the default database.
34Upgrading to a newer release
When a newer release of this item arrives, you want its fixes without losing your own work. These are the files a buyer usually changes, and what to do with each.
| Keep yours | Take the new one |
|---|---|
backend/.env (and its APP_KEY: the saved provider keys depend on it) | backend/app/ |
backend/config/*.php if you edited any | backend/routes/ |
Your database, and backend/storage/app/private/media/ (the pictures) | backend/database/migrations/ |
assets/icon/, assets/images/energy/ | joulora_ai_app/lib/, except the files on the left |
lib/app/core/theme/app_colors.dart, app_text_theme.dart, lib/app/core/values/feature_config.dart, lib/firebase_*.dart | test/, integration_test/, packages/ |
Your sentences in lib/l10n/ | pubspec.yaml, merged rather than replaced if you added packages |
The safe order
- Back up the database,
.envandstorage/app/private/media/first. - Unzip the new version beside the old one, not over it.
- Diff the two trees (VS Code: select two folders, Compare; or
diff -r <old> <new>). - Copy the new files over, skipping the left-hand column.
composer install, thenphp artisan migrate, thenphp artisan config:clear.flutter pub getand run the app.
Are the migrations safe on a live database?
Yes, for this release. Every migration creates a table or adds
a column; the only drop calls are in their down()
methods, which run on a rollback, never on migrate. So
php artisan migrate on a database with your devices and usage in it
is additive. You can check a future release before you run it: a migration that
removes something contains dropColumn, dropIfExists or
renameColumn in its up(). migrate:fresh is
a different command and drops everything; see the commands chapter.
On the phone
A person's bills, appliances and tariffs are kept under versioned keys
(schemaVersion on each model), so an app update reads what the old
version saved. If you change a model's fields, raise its
schemaVersion and handle the old shape in its
fromJson.
Keeping customizations easy to carry
Colors and type in the two theme files, switches in
feature_config.dart, copy in the l10n files, and anything genuinely
yours in new files rather than as edits to existing ones. The further your
changes are from the files this item ships, the shorter your next upgrade.
35Third-party services and what they cost
The app runs on the phone and the back end on your own hosting; Demo mode calls nothing at all. What costs money is whatever you connect:
| Service | Needed for | Who pays |
|---|---|---|
| Google (Gemini), OpenAI or Anthropic API | Reading real bills and rate cards, and the three sentences | With a person's own key, that person. Through the included server, you, per request, to the vendor whose key the server holds. Set the caps on the AI proxy page and a spending limit at the vendor accordingly. |
| Web hosting with PHP 8.4 and MySQL, or a VPS | The back end | You, to your host |
| Apple Developer Program | Publishing on the App Store, Sign in with Apple, push on iOS | You, to Apple |
| Google Play Console | Publishing on Google Play | You, to Google |
| Firebase | Push, analytics and crash reports (the feature packs) | You; the free tier covers a small app |
| A mail provider | Password reset mail, if you add it | You, per message |
A bill read is one request with one photo; Why this month is one small text request each time it is asked. Current prices and free allowances are on each vendor's own pricing and rate-limits pages, linked from the AI screen; this manual quotes none, because they change.
Connecting any of these will involve third-party services, and those services will incur their own separate costs, billed by the provider to you. None of them is included in this item.
36Building for release and the stores
From a working app to something the stores accept.
Android
- Create a keystore, once, and keep it safe; losing it means you can never
update the app under the same listing:
keytool -genkey -v -keystore <path-to-keystore>/upload.jks \ -keyalg RSA -keysize 2048 -validity 10000 -alias upload - Create
android/key.properties(keep it out of git and out of any archive you share):storePassword=<password> keyPassword=<password> keyAlias=upload storeFile=<path-to-keystore>/upload.jks - In
android/app/build.gradle.kts, read that file in asigningConfigsblock and pointbuildTypes.releaseat it (Flutter's "Build and release an Android app" page has the exact block). The project ships with debug signing so it runs out of the box. flutter build appbundle --release; the file lands atbuild/app/outputs/bundle/release/app-release.aab.- Upload it in the Play Console under Production → Create new release. Google Play wants an AAB; the APK is for sideloading.
iOS
- Open
ios/Runner.xcworkspacein Xcode. - Select the blue Runner project, then the Runner target, then the Signing & Capabilities tab.
- Tick Automatically manage signing and choose your
Team; Xcode creates the provisioning profile. The Push
Notifications and Sign in with Apple capabilities are already listed there
(from
Runner.entitlements); remove either if you will not use it. - Set the Bundle Identifier to one registered to your team, and the same prefix on the RunnerTests target.
flutter build ipa --release; it lands atbuild/ios/ipa/.- Upload with Transporter (free on the Mac App Store) or Xcode → Window → Organizer → Distribute App, then submit in App Store Connect.
The privacy keys App Review will ask about
ios/Runner/Info.plist carries three usage descriptions, and each
sentence should name your app if you rename it:
| Key | Why |
|---|---|
NSCameraUsageDescription | Taking a photo of a bill or a rate card. |
NSPhotoLibraryUsageDescription | Choosing a photo of a bill or a rate card. |
NSFaceIDUsageDescription | The lock-on-launch switch. |
UIBackgroundModes lists remote-notification for
push. On Android the manifest declares INTERNET,
USE_BIOMETRIC, POST_NOTIFICATIONS and
BILLING; the camera is reached through the system picker and needs
no permission of its own. In App Store Connect's privacy answers and the Play
Console's data safety form, say that bill photos are sent to the AI provider (or
your server) the person chose, to read the printed figures, and are not used to
identify them. If you ship with the included server as the route, also say that
the photos are stored on your server, linked to the install (not to a named
person), until you delete them.
Before you submit
- Bump
version:inpubspec.yaml(1.0.0+1): the part before the plus is what people see, the part after is the build number, and every upload needs a higher one. KeepAppIdentity.versioninlib/app/core/utils/app_identity.dartin step: it is what the app reports to your server. - Replace the launcher icon, the app name and the sample photographs.
- Decide what a fresh install opens on: Demo mode (as shipped), or your server
via
API_BASE_URL. A reviewer can use either without a key.
37Commands
In the app folder
| Command | What it does |
|---|---|
flutter pub get | Fetch the packages. Run it after any change to pubspec.yaml. |
flutter run | Run on the connected device or simulator, in Demo mode. |
flutter run --dart-define=API_BASE_URL=<url> | Run with your server built in: Demo mode off, bills read through the proxy. |
flutter run --dart-define=LOCALE=es | Pin one language for this build. |
flutter run --dart-define=IAP=on | Use the real store for purchases (needs product ids). |
flutter analyze | Static analysis. Ships with zero issues. |
flutter test | The unit and widget tests. |
flutter drive --driver=test_driver/integration_test.dart --target=integration_test/screenshots_test.dart -d <device> | Walk every screen and write screenshots. |
flutter build appbundle --release | The bundle Google Play wants. |
flutter build ipa --release | The archive App Store Connect wants. |
flutter build apk --release | An APK for sideloading. |
dart run flutter_launcher_icons | Regenerate every launcher icon from assets/icon/. |
flutter clean | Delete build output. Harmless, and the first thing to try when a build fails for no reason. |
In the back end folder
| Command | What it does |
|---|---|
./install.sh | First-time setup: dependencies, key, database, demo data. Safe to run twice: it keeps an existing .env and the seeder skips itself once the demo admin exists. |
composer install | Fetch the PHP dependencies. |
php artisan serve | A development server on port 8000. |
php artisan migrate | Apply new migrations. Additive in this release: nothing is dropped or renamed. |
php artisan db:seed | Insert the demo accounts, devices and usage, if the demo admin is not already there. |
php artisan route:list --path=api | Print every API route, as the API reference lists them. |
php artisan config:clear | Forget the cached configuration. Run it after editing .env on a live server. |
composer test | The Pest suite. |
docker compose up -d --build | Start the Docker stack. Keeps the database across restarts: migrations are additive and the seeder skips itself once the demo admin exists. |
docker compose down | Stop the Docker stack. |
The commands that destroy data
php artisan migrate:fresh --seed drops every table in the
database and rebuilds it, then inserts the demo data. Devices, usage
rows, accounts and the provider keys you saved in the panel are gone. There is no
confirmation prompt in a non-interactive shell and no undo. Use it on a laptop,
never on a live server.
php artisan demo:clear deletes every row flagged as demo data,
including the demo admin account. It asks first unless given
--force. That is what you want before going live, once you have
created an admin of your own; back up first.
docker compose down -v deletes the Docker database volume along
with the containers.
38Troubleshooting
The app will not build
| Symptom | Cause | Fix |
|---|---|---|
Unsupported class file major version, or Gradle complains about Java | Gradle is using a JDK that is too new or too old. | Install JDK 17 and point Flutter at it: flutter config --jdk-dir <path-to-jdk-17>. |
Minimum supported Gradle version is β¦ | An older Flutter SDK than the project needs. | flutter upgrade to 3.47 or newer. |
CocoaPods could not find compatible versions | A stale pod cache, or CocoaPods under the system Ruby on Apple silicon. | cd ios && pod repo update && pod install; if that fails, install CocoaPods with Homebrew. |
The IDE underlines every import but flutter run works | The editor does not know where the Dart SDK is. | VS Code: Flutter: Change SDK. Android Studio: Settings → Languages & Frameworks → Flutter. |
Could not find package qh_β¦ | packages/ was deleted or moved. | Put it back beside lib/; the feature packs are part of the project. |
| A build that used to work fails after a package change | Stale build output. | flutter clean && flutter pub get. |
The app runs but reading does not
| Symptom | Cause | Fix |
|---|---|---|
| Every read returns the sample bill | Demo mode is on, or the route you picked has no key or address yet, so Demo mode is answering. | Settings → AI: pick a route and add its key or server address. The screen says when it is falling back. |
| "The model β¦ is no longer available" | The vendor retired the model name. | Enter a current one on that route's card; on your server, on the AI proxy page. |
| "Could not reach your server" | The address is wrong, or the phone cannot see it. | On a real phone 127.0.0.1 is the phone: use your computer's LAN address, same Wi-Fi. Check the address has no /api. |
| "Your server is not set up to answer yet" | The proxy is switched off, or has no key for its default provider. | Panel → AI proxy: switch it on, add a key. GET /api/ai/status shows which providers are available. |
| "That photo is larger than your server accepts" | The image is over AI_MAX_IMAGE_BYTES. | Raise it together with the app's maxImageBytes, or take the photo a little further away. |
| The lines do not add up to the printed total | A line was missed or misread. | Tap the line to correct it, or Add line; the check updates as you type. |
| No Google / Apple buttons | Demo mode is off and there are no client ids in feature_config.dart. (In Demo mode both always show.) | See the chapter Setting up Google and Apple sign-in. |
The back end
| Symptom | Cause | Fix |
|---|---|---|
| A blank white page, and the URL shows your domain | The document root points at the folder above public/. | Point it at <path-to-backend>/public. Until you do, .env is downloadable. |
| A blank white page (or a 500), and the document root is already right | π΄ A different fault with the same symptom: storage/ and bootstrap/cache/ are not writable. | Make both writable by the web server: cPanel file manager → Permissions, or chmod -R ug+w storage bootstrap/cache. If storage/logs/laravel.log is empty or missing, this is almost certainly it. |
syntax error, unexpected token in a vendor file | PHP is older than 8.4. | cPanel → MultiPHP Manager → 8.4. php -v shows what you are really running. |
A change to .env has no effect | The configuration is cached. | php artisan config:clear. |
| Keys saved in the panel stopped working after a move | APP_KEY changed; the saved keys were encrypted with the old one. | Restore the old APP_KEY, or paste the keys again. |
SQLSTATE[HY000] [2002] | Wrong database host or credentials. | Check the DB_* keys; on shared hosts the names are prefixed with your account name. |
| Every install gets "too many attempts" at once | The server is behind a proxy it does not trust, so every install looks like one address. | Set TRUSTED_PROXIES. |
| Chat answers 504 | The server cannot reach the provider. | Ask your host whether outbound HTTPS is allowed on your plan. |
| A notification sent for later stays Scheduled | The scheduler's cron line is missing. | Add it (the chapter on putting it on a server), and check APP_TIMEZONE is your zone. |
| An install's photos stop appearing on Pictures | It has used its picture space (MEDIA_MAX_TOTAL_BYTES), so new ones are refused with 413; or the phone is on its own key or Demo mode, which sends none. | Raise MEDIA_MAX_TOTAL_BYTES. Deleting pictures on Pictures frees space only for photos the phone no longer holds (bills deleted on the phone); the rest are sent again. |
| The panel loads without styling | APP_URL does not match the address you are browsing. | Fix it, then php artisan config:clear. |
39Glossary
| Term | Meaning here |
|---|---|
| Band | One of the four kinds of bill line: energy, standing charges, taxes, other. |
| Standing charge | The fixed amount a tariff charges per month (or day) whatever the energy used. |
| Tiered tariff | Blocks of kWh, each at its own rate. |
| Time of use | Rates that depend on the hour: off-peak, standard, peak. |
| Ledger | The two-column comparison of a bill against another tariff or bill. |
| Job | One kind of request to a model, with its own instruction, schema and parser. |
| Route | Who answers a job: Demo mode, Gemini, OpenAI, Claude or your server. |
| Key proxy | The back end: it holds the provider keys and forwards requests for registered installs. |
| Device key | A random 32-character id made once per install and traded for a bearer token. |
| Demo mode | The sample household and the on-device answer; nothing is written to disk. |
| Feature pack | One of the small packages in packages/, switched on in feature_config.dart. |
| Sanctum token | The bearer token the back end issues. |
| Filament | The admin panel framework the back end uses. |
--dart-define | A value passed to a Flutter build from the command line, read with String.fromEnvironment. |
40Frequently asked questions
Does the app need the back end?
To try it, no: Demo mode answers on the device and every screen works. To read real bills it needs a model, through either a key the person pastes in or the back end in the same download. The back end is what lets you ship without asking anyone for a key.
Does the AI work out the bill?
No. It reads the printed figures into a closed form and nothing else. Every comparison, projection and appliance cost is arithmetic on the phone, in the engines, and the same inputs give the same answer everywhere.
What does a bill photo reveal?
The photo goes to the route the person chose. The reply has no field for a name, an address or an account number, and the rules tell the model not to return one. The phone keeps the photo in the app's own folder, and when the person reads bills through the included server, that server keeps a copy too, listed on the panel's Pictures page under the install, not a name.
Does it connect to a supplier or a smart meter?
No. Tariffs are typed in or read off a photo of a rate card, and meter readings are typed in. The wire-up chapter says where a data source like that would plug in.
Which currencies?
Any. The person sets the symbol in Settings, and the app never converts.
Can I change the colors and the typefaces?
Yes: one file for colors and one for type. See those two chapters.
Which languages?
English, Spanish and Arabic (3), including right-to-left. Adding one is a file and a line.
41Support and licenses
Support
Questions about setup, the AI routes, the back end or re-skinning are answered through the item's comments. Item support covers this item as shipped; it does not cover a provider's own account, quota or billing, or code you have changed.
Licenses
- Typefaces: Anybody, Sen and Azeret Mono, SIL Open Font
License 1.1:
assets/fonts/LICENSES.txt. - Photographs: Pexels License, each file and its source in
assets/images/energy/LICENSES.txt. - Flutter packages and PHP packages: their own licenses, in
pubspec.lockandcomposer.lock. The back end's Spanish and Arabic validation files come from Laravel-Lang (MIT,lang/LICENSE-Laravel-Lang.txt). - The landing page uses the same typefaces and screenshots of this app, and is yours to edit and publish.
landing/index.html: a one-page site
for your own app, in its colors and typefaces, with its own screenshots.