> ## Content Index
> Fetch the complete content index at: https://blog.sudowl.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Odoo Booking to InvoicePlane Invoice: Built, Running in Test Mode
- URL: https://blog.sudowl.com/odoo-booking-auto-invoice-invoiceplane-test-mode/
- Published: 2026-11-20T09:00:00.000Z
- Updated: 2026-11-20T08:22:30.000Z
- Description: A cron job turns confirmed Odoo rental orders into InvoicePlane invoices. Test mode, duplicate protection, room blockers and what broke on deploy.
- Author: Lukas
- Tags: Linux, business-ai

Yesterday I wrote that a client's coworking space had [Odoo bookings with zero invoices](/odoo-rental-bookings-no-invoices-invoiceplane/) and ended with a plan. This is the follow-up. It's built and deployed, running in test mode, and no real booking has gone through it yet. So read this as "built and checked", not "proven in production".

The ask had grown by then: staff should enter email bookings for someone else, rooms must be blockable without billing anyone, and the invoice should go out on its own, with me in BCC.

**TL;DR:** A cron job runs every 5 minutes, pulls confirmed rental orders from Odoo over JSON-RPC and creates an invoice in the self-hosted InvoicePlane. A mode variable switches between off, test (draft plus a mail to me, sending is one click) and live (straight to the customer). Draft and send UUIDs are stored before the invoicing server is called, and a send that ends in doubt is never retried. A "blocker" contact in Odoo blocks a room without an invoice. The website now counts Odoo orders when it shows free days.

## The cron line

```bash
# /etc/cron.d/internal-app (paths and names generalized)
2-57/5 * * * * appuser flock -n /var/lib/app/booking.lock sh -c 'cd /opt/app && set -a && . /etc/app/env && set +a && /opt/app/venv/bin/python -c "from app.booking.cron import main; raise SystemExit(main())"' >> /var/lib/app/booking.log 2>&1

```

```bash
# /etc/app/env (excerpt, values are examples)
ODOO_URL=https://example.odoo.com
ODOO_DB=example
ODOO_USER=api@example.com
ODOO_KEY=YOUR_API_KEY
BOOKING_MODE=test        # off | test | live
BOOKING_INFO=alice@example.com

```

Polling, no webhook. The internal app runs its other syncs from cron with `flock -n` too, so a slow run never overlaps the next one. If you like timers better, [systemd timers](/systemd-timers-instead-of-cron/) do the same job.

The mode is read defensively. Anything that isn't exactly `test` or `live` counts as `off`. A typo in the env file should stop the job, not send invoices.

## What one run does

1. **Start point.** On the very first run the job stores the highest existing rental order ID and only looks at orders above it. The old unbilled bookings had already been handled by hand, so they can never get an invoice by accident. No date logic, no list of exceptions.
2. **Fetch.** `sale.order` with `is_rental_order = True`, ID above the start point, state `sale` or `cancel`.
3. **New order?** It gets a row in a local SQLite table. Cancelled before anything happened: `ignored`. Customer is the blocker contact: `blocker`. Otherwise `draft`, with a fresh UUID for the draft request stored right away.
4. **Build the invoice data** from the Odoo order and run checks. If one fails, the row goes to `review` and I get a mail with the reason.
5. **Create the draft** in InvoicePlane (the existing invoice group, net price, 20% VAT, e-invoice like all the others) and store the InvoicePlane ID.
6. **Test mode:** stop here, status `review`, mail to me with a link to the review page. One click sends it. **Live mode:** send straight to the customer's invoice email.

The checks that send a booking to `review` instead of out the door:

- every order line needs exactly one tax rate
- the order needs at least one real line
- my recomputed gross total may not differ from Odoo's `amount_total` by more than 5 cents
- the billing address needs a postcode and city
- the invoice email has to look like an email

Default is "stop and ask a human". After fixing the data in Odoo there's a "retry" button in the internal app.

## Gotcha: the invoice must never go out twice

This is the part I spent the most care on. The bridge to InvoicePlane already existed from the review page: SSH forced command, JSON in, one JSON line out (the setup from my [ZUGFeRD InvoicePlane post](/zugferd-e-invoice-self-hosted-invoiceplane/)). It already had two protections:

- **Draft:** the request UUID is stored in a custom field on the invoice, and a MariaDB `GET_LOCK` on that UUID serializes parallel calls. Same UUID again returns the existing invoice instead of a new one.
- **Send:** a send UUID is executed at most once, ever. If a send was interrupted, the answer is "unclear", never a retry.

The cron job plays by the same rules. The draft UUID is in the state table before the first call. The send UUID is written into the row and into the shared "unclear" lock table **before** the invoicing server is called (simplified, names translated):

```python
send_uuid = row["send_uuid"] or str(uuid.uuid4())
con.execute("INSERT OR IGNORE INTO outbox_unclear(ip_id, uuid, created) "
            "VALUES (?,?,datetime('now'))", (ip_id, send_uuid))
set_row(con, so_id, send_uuid=send_uuid)
try:
    r = ip_client.request({"action": "send", "uuid": send_uuid, "ip_id": ip_id, ...},
                          TIMEOUT_SEND, automatic=True)
except IPError as e:
    if e.not_sent:          # server says: definitely nothing went out
        release_lock_and_mark_review()
    else:                   # timeout, broken pipe, anything in between
        mark_unclear()      # locked, mail to me, never retried

```

The client has its own guard too. Until now a send was refused unless it came from the review page with a "human confirmed" flag, and a test pins down which files may contain the send action. I added a second flag, `automatic=True`, used only by the booking job, and let that test allow exactly one more file. Auto-send is a written-down exception, not a default.

Same lesson as my [cron job that uploaded one file 153 times](/idempotency-cron-automation-duplicate-uploads/): mark the side effect right next to the side effect.

## Gotcha: the website didn't know about Odoo bookings

Before building the blocker I checked how the website decides that a day is free. It counted only its **own** booking list in WordPress, a custom post type. A booking created directly in Odoo was invisible to it. So someone could book a day online that staff had already given away in Odoo. Without fixing that, "blocking" would have meant nothing.

The fix is a small include file in the theme. It asks Odoo for confirmed rental order lines of that room's product in the date range and adds them to the WordPress count:

```php
$lines = example_odoo_call( 'sale.order.line', 'search_read', array( array(
    array( 'order_id.is_rental_order', '=', true ),
    array( 'order_id.state', '=', 'sale' ),
    array( 'product_id.product_tmpl_id', '=', (int) $cfg['odoo_tmpl'] ),
    array( 'order_id.rental_start_date', '<=', $date_to . ' 23:59:59' ),
    array( 'order_id.rental_return_date', '>=', $date_from . ' 00:00:00' ),
) ), array( 'fields' => array( 'order_id', 'product_uom_qty' ) ) );

```

(Function name generalized.) Three details that matter:

- Orders that came **from** a website booking are skipped, because WordPress already counts them. Otherwise every web booking would block two slots.
- The calendar result is cached for 60 seconds as a transient. The final check right before a booking is saved asks Odoo fresh, without the cache.
- If Odoo can't be reached, the function writes to the error log and returns nothing. The calendar then falls back to the WordPress list only. Not perfect, but the booking page stays up.

I backed up `functions.php` first and ran `php -l` on both files inside the container.

## Blockers and bookings for someone else

A blocker is just a rental order on a dedicated Odoo contact, something like "Internal (Blocker)". Confirmed order, so the room is blocked everywhere. The cron job sees that contact and writes `blocker`. No invoice, ever.

For bookings that come in by email there's a new page in the internal app: room, from and to date, customer (name, email, company, address), a note, and a "blocker, no invoice" checkbox. It checks that the room is free right before it creates the order, creates the rental order in Odoo, calls `action_confirm`, and sends Odoo's normal booking confirmation to the customer. Only three people can create bookings there. Others with a login can only see the list.

## Gotcha: smaller surprises

- **Odoo prices are gross.** The product text says "net day price", but the tax is set to price-included. So 55 EUR in Odoo is 45.83 net plus 20% VAT. The invoice takes exactly what Odoo charges. If 55 net was meant, Odoo has to change.
- **Due date is 7 days**, not the booking day as discussed, because the payment text on the company's existing invoices says "within 7 days". Invoice and text should agree.
- **The address sits in one field.** The website writes the whole billing address into `street`, sometimes on several lines. A regex picks out postcode and city. My plan said that without a postcode a small-amount invoice with name and email would be fine. But the existing InvoicePlane bridge requires a postcode, and I didn't want to touch that server for this. So no postcode means `review`. One existing customer has only a street, no postcode.
- **Odoo Online login sometimes returns `false`.** The client tries authentication twice before giving up.
- **BCC for the owner.** InvoicePlane has a setting `bcc_mails_to_admin`. The row didn't exist in `ip_settings`, so I inserted it with value `1`. The mailer then adds the email of user ID 1 as BCC. That means **every** mail InvoicePlane sends, also for the other company in the same instance. Fine here, but know it before you flip it.
- **The internal booking copy still fires for blockers.** The [Odoo automation that mails an internal copy](/odoo-automated-action-hidden-booking-copy-email/) triggers on every confirmed order, blockers too.
- **Deploy hiccups.** `python -m app.booking.cron` printed a runpy `RuntimeWarning` about the module already being in `sys.modules`. Calling `main()` through `python -c` got rid of it. And my one-off script to grant booking rights failed with "invalid module" until it imported the app first, so the new module was registered. Two old tests that list every module and audit-log action failed in the full suite and got the new entries.

## Where it stands

Live and checked: Odoo login from the app, room occupancy (two booked days in that month showed up), and the invoice data built from an existing order, with the address split correctly. The full test suite showed 861 passing and 2 failing. Both failures were the outdated tests above, fixed and rerun. I backed up the database and the env file before deploying.

What I did **not** do: create a fake booking to test end to end. Every confirmed order triggers the internal copy mail to other people, and I didn't want to spam them with a test. So the first real booking in test mode is the end-to-end test.

Open:

- switch `BOOKING_MODE` from `test` to `live` once a few real bookings went through test mode cleanly
- decide whether the Odoo prices are meant net or gross

The switch to live is one line in the env file.

---

### Related posts

- [Odoo Confirmed Every Booking and Never Wrote a Single Invoice](https://blog.sudowl.com/odoo-rental-bookings-no-invoices-invoiceplane/)
- [Valid ZUGFeRD E-Invoices From Self-Hosted InvoicePlane in Docker](https://blog.sudowl.com/zugferd-e-invoice-self-hosted-invoiceplane/)
- [Mirroring My Markdown Notes Into Notion With a Python Sync](https://blog.sudowl.com/notion-api-sync-markdown-notes/)