A quick project to learn Odoo 17.
Note :
I will rely on the official documentation of Odoo 17 for this mini-project and then summarize what I have learned.
I will use ChatGPT to provide a summary with a simple storytelling technique, making this document accessible and easy to understand even for novices.
In the world of software, there exists a system known as Odoo, which follows a multitier structure. It resembles a grand castle with three distinct layers: the presentation tier, the logic tier, and the data tier. 🏰
In this castle, the presentation tier is like the castle's exterior, made of HTML5, JavaScript, and CSS. It's what visitors see and interact with. The logic tier, however, is like the castle's intricate machinery, all written in Python. This layer handles the castle's inner workings, ensuring everything runs smoothly. Lastly, the data tier, akin to the castle's vault, stores all the important information using PostgreSQL as its guardian. 🛡️
Now, within this castle, developers roam freely, crafting extensions called modules. Each module is like a special chamber dedicated to a specific purpose. Some modules add new features to the castle, while others extend existing functionalities. Imagine one module adding magical accounting rules to manage the kingdom's finances, while another conjures up real-time visualizations of flying dragons. 🐉
To understand these modules, one has to learn the castle's language. A module can contain various elements like business objects, object views, data files, web controllers, and even static web data like images and scripts. Each element serves a unique purpose, contributing to the castle's grandeur. 🌟
Imagine a brave adventurer embarking on a journey to create their own module. They venture into the module's directory, organized neatly like rooms in a castle. Inside, they find business objects, declared as Python classes, object views defining how information is displayed, and data files, either XML or CSV, holding vital information for the castle's operation. 🛠️
But wait, there are different versions of this castle! Odoo comes in two flavors: Enterprise and Community. The Enterprise version, with its licensed access, offers extra features, like secret chambers hidden within the castle walls. However, from a technical standpoint, these extra features are just additional modules layered atop the Community version. 🔒
Now, our adventurer is ready to embark on their journey. But before diving into writing code, they decide to prepare by reviewing the castle's installation process. After all, even seasoned knights need to ensure they start their quests on the right foot. 🚀
And thus, armed with knowledge and determination, our adventurer sets forth to conquer the realm of Odoo, one module at a time. 🌌
./addons
: This directory contains all the modules we want to add to Odoo 17. Therefore, it includes the module we are going to develop.
This directory will be part of the addon paths that reference all directories containing Odoo modules.
./config/odoo.conf
: This file contains Odoo configurations.
docker-compose.yml
: This file contains deployment configurations for deploying Odoo on localhost.
🌐 In the world of Odoo, where developers shape the digital corridors of the software, setting up the development environment is a key step. Like a chef preparing their favorite recipe, each developer has their own method, but for Odoo insiders, there's a preferred path: installation from the source code.
It all starts with environment preparation. Just like preparing ingredients to concoct a delightful dish, following the steps of the contribution guide is essential. Once these steps are followed, you have two precious ingredients: the local repositories odoo/odoo and odoo/enterprise.
For easier installation, it's better to use the containerized version of Odoo and then
orchestrate with Docker. Take a look at the ./docker-compose.yml
file.
To complete the preparation, you need to copy this project to your personal GitHub account. Click "Fork"
to create a
copy of this repository in your account.
Then, using the command below, replace <your_github_account>
with the name of your GitHub account to download your
copy of this project to your machine:
git clone [email protected]:<votre_compte_github>/learning-odoo-17.git
And there you go! Your environment is ready to run Odoo on your local machine. And here's how to launch Odoo 17 on your machine:
cd learning-odoo-17
docker compose up -d
To check the installation, simply open your browser and type http://localhost:8069/web.
username: admin
password: admin
To view the logs
data of the odoo
container:
docker logs -f odoo17Learning
docker logs -f postgres_odoo17Learning
To view the logs
data the postgres
container:
docker logs -f postgres_odoo17Learning
Now that your server is running, it's time to write our own application! 😎
📖 The purpose of this chapter is to embark on a journey of creation, laying the very foundation for a brand
new Odoo module
. Imagine starting from scratch, with only the bare essentials needed to catch Odoo's attention. As we
progress through the chapters, we'll add layers of features, weaving a tapestry of a realistic business case.
🏠 Welcome to the realm of the Real Estate
Advertisement module. This module delves into a specialized business area
not commonly found in the standard set of Odoo modules: real estate
. But before diving headfirst into development,
it's wise to scout Odoo's vast kingdom to ensure no existing solutions already address our specific needs.
🔍 Picture a main list view
adorned with various advertisements, each telling a story of properties waiting to be
discovered. The form view reveals essential details about each property: from the number of bedrooms to the presence of
a garden, offering a glimpse into the world within.
💼 The second tab unveils a treasure trove of offers
, where potential buyers
can make bids
above or below the
expected selling price
. It's a realm where negotiations
unfold, leaving the final decision in the hands of
the seller
.
🎥 And as if by magic, a quick video showcases the graceful dance of the module's workflow. Ah, if only it were captured already!
🛠 But fret not, for our journey begins with a humble task: preparing the addon directory
. This step ensures that Odoo
recognizes our newborn module, even if it's but an empty vessel for now. Soon, it will proudly stand among the Apps
,
awaiting its chance to shine.
✨ With a flick of a wand (or perhaps a few keyboard strokes), we create the necessary files: __init__.py
and __manifest__.py
. These files breathe life into our module, defining its name
and dependencies
, much like a
spellbook detailing the ingredients of a potent potion.
🧙♂️ Restart
the Odoo server, update
the Apps list, and behold! Our module, like a budding flower, blooms into view.
But wait, did it not appear? Fear not, for a simple tweak, removing the default filter
, reveals our creation in all
its glory.
🔑 And now, with a final flourish, we make our module an 'App'
, ensuring its presence even when the Apps filter
is
on. Though it may be but an empty shell, devoid of menus, it's a promising start to our magical journey.
📜 With the groundwork laid, our adventure continues as we prepare to create our first model
. Exciting times lie ahead
as we breathe life into our module, one enchanting step at a time.
🏰 Picture our Odoo module
as a freshly built house - sturdy and promising, yet lacking the warmth of life within its
walls. In this chapter, our quest was to breathe life into our module by giving it the ability to store data
. 💼
As we delved deeper into the documentation, we
discovered Object-Relational Mapping (ORM), a
wondrous tool bridging the gap between our Python code and the database
. ✨ This powerful technique allows us to define
our business objects as Python classes
, extending the Model
class. With a simple invocation, our model came to life,
seamlessly integrating into Odoo's automated persistence system.
Our task was to create the real estate properties model
. Inspired by the example given in the CRM module
, we
embarked on our quest, shaping the necessary files and folders to define our model
. 🏡 With each keystroke, the
framework began to take shape, and soon, our model stood proudly, ready to capture the essence
of real estate properties
.
But our journey did not end there. We set out to infuse our model with basic fields
, such as name
, description
,
and price
. Like an artisan adding details to a work of art, we enriched our model with fields
of
different types
- Char
, Text
, Integer
, and even Boolean
. Each field brought a new dimension to our model
,
enriching it with the essence of real-world data. 🎨
💡 Here's how to connect to the database inside the container to view the data.
docker exec -it postgres_odoo17Learning psql -U admin -d learning_db
SELECT COUNT(*) FROM estate_property;
\d estate_property;
Yet, our work was not complete until we ensured the integrity
of our data
. With a flourish of our craftsmanship, we
defined attributes
for our fields
, making them required
and ensuring their presence in every record
. We even
explored the realm of Automatic Fields
, uncovering the hidden mechanism behind fields like id
, create_date
,
and write_user
. 🔮
And so, our journey through Chapter 4 came to an end, but our module was now imbued with the power to store and manage
real estate data
. With each step forward, our module
grew stronger, paving the way for greater adventures in the
realm of Odoo
. 🚀
In the journey of building our Odoo module
, we've ventured into the realm of security
, a crucial aspect in any
software application, especially when it comes to managing sensitive
business data
. 🏰
Imagine our module
as a fortified castle, safeguarding valuable information
about properties and transactions within
its walls. But who gets access
to enter this castle? This is where Odoo's security mechanism
comes into play, like
the gatekeeper controlling entry to the castle. 🛡️
We've learned that Odoo
relies heavily on data, and one way to populate our module
with essential information is
through CSV files
. These files act as the blueprint, defining the structure and content of our data. For instance,
we've seen how a CSV file
sets up the states of countries, laying the foundation for our data castle. 📋
However, loading data
is just one part of the security
equation. We also need to control
who
can view
, edit
, create
, or delete
this data. This is where access rights
come in. Access rights act as the
guards patrolling the castle walls, ensuring only authorized users
can access specific areas. 🚨
To implement access rights
, we create rules
that dictate what each user
or group
of users can do within
our module
. These rules
are defined in CSV files
, just like our data files, and are loaded into Odoo's security
system.
In our journey, we've set out to grant access rights
to the base.group_user
, essentially allowing them to roam
freely within our module, albeit within certain limits. 🔒
With access rights
in place, our module's security
is fortified, and we're now ready to open the gates and let users
interact with our module's user interface
, marking the next phase of our adventure in Odoo development. 🚀
Now that we've laid the foundation with our new model
and access rights, it's time to dive into the exciting world
of user interface
interaction. 🚀
In our journey to understand Odoo
, we've encountered various ways to handle data
. While CSV files
are great for
simple data, the XML format
steps in for more complex structures
like views
or email templates. These XML files
,
residing in the same folders as CSVs
, define the intricate UI elements
we interact with. 📝
Actions
are the bridge
between menus
and models
, defining what happens when we click
or interact
with elements
in the interface. In our real estate
scenario, actions empower us to navigate through lists
and forms
seamlessly. ⚙️
Menus
in Odoo follow a hierarchical structure
, guiding us through different levels
of the interface
. By
defining menus
in XML files
, we craft an intuitive navigation
experience for users, leading them to the heart of
our application. 📂
Fine-tuning the view
is crucial for a user-friendly
experience. We can set default values
for fields,
specify read-only
fields, and control field behavior during duplication
. In our real estate
adventure, we ensure
that our data behaves as expected, setting defaults and enforcing rules
for smoother operations. 🎨
Certain fields
in Odoo come with predefined behaviors
, guiding how data behaves within the system. By understanding
and leveraging these reserved fields
, we can fine-tune our application to suit our needs effectively. 🛠️
With each step, we're unlocking new possibilities in our journey with Odoo
. As we delve deeper into defining
our views
, the interface becomes not just a canvas but a portal to a seamless user experience
. 🌟
🌟 In our journey through Odoo's realm, we've ventured into crafting models
and setting up access rights
. Now, it's
time to give our application a face, a user interface
where users can interact and bring our creation to life.
Views
, the windows to our application's soul, are where the magic happens. They organize and present data
in a way
that's not only meaningful but also intuitive for users to navigate
.
Imagine you're building a real estate
app. You wouldn't want just a list
of properties or a cluttered form
. You'd
want an organized layout
where users can easily find what they need. That's where views
come in.
Think of list views
as the bird's-eye view of your data. They're like spreadsheets
, neatly arranging records
for
easy scanning. In our real estate app
, we want more than just property names on this list. We want to
see essential details
like the last seen date too.
Now, imagine you're editing
a property's details
. You wouldn't want a chaotic mess of fields. Form views
provide
structure. They group fields
logically, making it easy to input
or edit
property information
. It's like filling
out a form
where everything has its place.
Searching
for a property? Search views
help narrow down your options. They filter
out unwanted clutter, leaving
you with exactly what you need
. In our app, we want to filter
properties by availability
and group
them
by postcode
for convenience.
As we sculpt these views
, remember, it's not just about aesthetics. It's about creating an experience
that users
will love
. So, let's dive in and design views
that breathe life into our real estate world.
We're just scratching the surface here. There's still much to explore, like custom filters
and grouping
. But for
now, let's revel in the joy of creating views
that make our app shine
.
In our quest to build the ultimate real estate management system
, we've journeyed through the intricacies of
crafting models
and designing intuitive views
. Now, armed with a deeper understanding of how views
shape
user interaction
, we venture into the realm of model relationships
.
Imagine our real estate application
as a bustling marketplace, where properties, customers, and agents converge in a
complex web of connections
. Just as our views
provide windows into our data
, these relationships
offer pathways
for seamless interactions
between different entities
.
In our bustling real estate marketplace, properties
often have distinct types
, buyers
, and sellers
.
With Many2one
fields, we establish clear links between these entities, enabling us to easily associate each property
with its type, buyer, and seller.
It's like building bridges that connect
different parts of our marketplace, ensuring smooth navigation for users.
But our marketplace isn't just about individual properties; it's about the stories they tell.
With Many2many relationships
, we enrich these stories by tagging properties with descriptive labels like 'cozy' or '
renovated.'
It's like adding layers of depth to our marketplace, allowing users to explore properties based on unique characteristics.
And what's a marketplace without offers
? With One2many relationships
, we capture the dynamic exchange of offers
between buyers and sellers. Each property can now boast a gallery of offers, each representing a potential transaction
waiting to unfold.
It's like opening a window into the negotiation process, where every offer adds to the intrigue of our marketplace.
As we weave these relationships
into the fabric of our real estate module
, we create a dynamic ecosystem where data
flows seamlessly between entities. It's not just about organizing information; it's about fostering meaningful
connections that bring our marketplace to life.
And so, armed with the knowledge of model relationships
, we embark on the next phase of our journey, eager to explore
the boundless possibilities that await us in the realm of Odoo
.
Notes:
Because a
One2many
is avirtual
relationship, there must be aMany2one
field defined in thecomodel
.
In our journey to master the intricacies of Odoo 17, we find ourselves standing at the threshold of a new
frontier: computed fields
and onchange
mechanisms. These may sound daunting, but fear not, for they hold the key to
unlocking the true potential of our real estate
management system.
Imagine our real estate
system as a grand canvas, waiting to be painted with data
. Computed fields
are our
brushes, allowing us to dynamically
calculate values based on other fields
. It's like magic; we define the rules,
and Odoo does the rest.
For instance, let's say we want to calculate
the total area
of a property by summing up its living area
and garden area
. With computed fields
, this becomes a breeze. We simply define the formula, and Odoo handles the
calculations behind the scenes.
But here's the catch: computed fields
often rely on the values of other fields. Think of them as puzzle pieces that
fit together to form a complete picture. We use the @api.depends
decorator to specify these dependencies
, ensuring
that our computations stay in sync
with the underlying data
.
For example, if the living area or garden area of a property changes
, we want the total area
to update automatically
. By defining these dependencies
, Odoo knows exactly when to recalculate the total area,
keeping our data
accurate and up-to-date
.
Now, let's shift our focus to onchange
mechanisms, the wizards of data manipulation
. Imagine our real estate
system as a living, breathing entity that responds
to user inputs in real-time
. Onchange methods
allow us to
perform actions on the fly, without ever saving anything to the database.
Suppose we want to enhance the user experience by automatically
setting the garden area to 10 and the orientation to
North when the 'garden' field is toggled on. Onchange methods
make this possible, creating a seamless and intuitive
interface for our users.
As we delve deeper into the realm of computed fields
and onchanges
, it's crucial to strike a balance. While these
tools empower us to automate tasks
and streamline workflows, we must exercise caution not to overcomplicate things.
Remember, simplicity
is key. Avoid the temptation to add unnecessary complexity, and always prioritize clarity
and
ease of use. After all, our goal is to build a real estate
management system that empowers users of all levels, from
novice to expert.
Armed with the knowledge of computed fields
and onchanges
, we stand poised to embark on the next leg of our journey.
In the upcoming chapter, we'll explore how to trigger business logic with the click of a button
, unlocking even
greater possibilities for our real estate
management system.
So, dear traveler, let us march forward with confidence, for the path ahead is paved with boundless opportunities to
shape the future of real estate
management with Odoo 17.
As we continue our odyssey through the realms of Odoo 17, we find ourselves at a pivotal juncture, where the concepts
of computed fields
and onchange
mechanisms have laid the foundation for even greater feats within our real estate
management system.
Picture our real estate
system as a bustling marketplace, alive with possibilities. Now, imagine imbuing it with the
ability to take action—canceling
properties, marking them as sold
, accepting or refusing offers—all with the click
of a button. This is the realm of action buttons
, where digital switches trigger tasks that shape the destiny of our
system.
But how do we make this magic happen? It's simple yet profound. We embed buttons
in our interface, each tied to a
specific action.
When users click these buttons
, they set off a chain reaction of events, seamlessly integrating functionality into our
system's fabric.
These action buttons
serve as conduits for our system's logic, orchestrating a symphony of user experience and
functionality.
Want to cancel
a property? Just hit "Cancel."
Sold it? Press "Sold."
The process is intuitive, guided by the logic
we've meticulously woven into our system.
But that's not all. We want our system to handle offers with grace and efficiency. By adding buttons like "Accept"
and "Refuse"
to our offer listings, we can streamline the process even further. And when an offer is accepted
, the
magic happens: the buyer is assigned, the selling price is set, all seamlessly orchestrated by the click of a button.
Now, you might wonder, how do we bring this magic to life? It's simpler than you think. We embed these buttons
into
our interface and link
them to
Python methods
that perform the desired actions
. By marking
these methods as public
and assigning them to the buttons
, we unleash their power upon our system.
Yet, as we venture deeper into the realm of action buttons
, let us heed a few guiding principles. Simplicity
reigns
supreme; let's resist the allure of unnecessary complexity. Clarity
and ease of use
should guide our every decision,
ensuring that our system empowers users of all levels.
With action buttons
at our disposal, we stand on the cusp of a new dawn. In the chapters to come, we'll explore how
to prevent incorrect data
from infiltrating our system, fortifying its foundations and ensuring its resilience in the
face of real-world challenges.
So, fellow voyager, let us embark on this journey with heads held high, for the path ahead brims with promise and the
potential to reshape the landscape of real estate
management with Odoo 17.
Notes:
In Chapter 6: Finally, Some UI To Play With, we created an action that was linked to a menu. You may be wondering if it
is possible to link an action to a button
. Good news, it is! One way to do it is:<button type="action" name="your_module.action_name" string="Button Label"/>
With the dawn of Chapter 9, we embraced the power of action buttons
, transforming our real estate management system
into a dynamic marketplace of possibilities. Yet, as our journey unfolded, we encountered a new challenge: ensuring the
integrity of our data amidst the ever-changing currents of user input.
In our quest for data integrity, we discovered the formidable tools of constraints
. These guardians of truth
stood
as sentinels, warding off the specter of incorrect data
with unwavering resolve.
With Chapter 11, we delved deeper into the arsenal of constraints, uncovering two mighty weapons: SQL constraints
and Python constraints
. Like knights donning armor, SQL constraints fortified our database with impenetrable barriers,
ensuring that amounts remained positive and names stood as unique beacons of identity.
Yet, in the labyrinth of data management, SQL
alone could not suffice. With Python
constraints, we wielded the
wisdom of Odoo to craft intricate spells of logic, guarding against the subtle nuances of incorrect data with precision
and finesse.
Guided by the hand of Odoo, we embarked on exercises that tested our skills and honed our craft. From ensuring positive prices to safeguarding the uniqueness of property tags, each challenge brought us closer to mastery over our realm of data.
In our quest to perfect our real estate module, we encountered an exercise of great importance: to ensure that no
offer could be accepted if it dared to fall below 90% of the expected price. With the guidance of Odoo, we crafted
a Python constraint
, leveraging the power of float comparison to safeguard our realm against unwelcome intruders.
But amidst our triumphs, a cautionary tale echoed through the halls of our adventure. Odoo warned us to tread carefully when working with floats, urging us to wield the tools of float comparison and precision handling with care and reverence.
As our tale draws to a close, we stand on the threshold of a new chapter, where the user interface awaits our touch of refinement. With each constraint we add, with every line of code we write, our real estate management system evolves, poised to shape the future of property management with Odoo 17.
With the formidable arsenal of constraints now firmly in place, our real estate management system stands as a fortress
of data integrity
, safeguarded against the specter of erroneous input.
Yet, as our journey through Odoo 17
continues, we find ourselves at a pivotal juncture: the refinement of our user
interface.
In the previous Chapter, we fortified our realm with the formidable tools of SQL and Python constraints
, ensuring that
our data remained pristine amidst the tumultuous currents of user interaction.
Now, as we gaze upon the landscape of our real estate module
, we recognize the need to add a touch of visual flair
and intuitive functionality
to enhance the user experience.
As we embark upon this Chapter, our mission is clear: to add the final touches that will elevate our real
estate management
system from a mere tool to a delightful and intuitive
platform for property management.
- We aspire to infuse our
list views
with vibrantcolors
, distinguishing properties with offers received, offers accepted, and those that have been sold or canceled.
- Through the judicious use of color
decorations
, we aim to create a visual language that intuitively conveys the status of each property at a glance.
- We seek to streamline user
interactions
by dynamically adjusting thevisibility
of buttons and fields based on contextual conditions.
- By employing conditional
visibility attributes
, we can ensure that users are presented with only the most relevantoptions
at any given moment, enhancing usability and reducing cognitive load.
- We endeavor to empower users with
efficient search
capabilities, enabling them to quicklyfilter
properties withvalues
based onspecific criteria
such as living area.
- Through the addition of default filters and custom search domains, we aim to streamline the search process, facilitating faster access to relevant property listings.
- We aspire to elevate the presentation of data within our
forms
and lists, leveraginginline views
to provide contextual insights and enabling users to interact with relatedrecords
seamlessly.
- By harnessing the power of
widgets
, we can tailor the display of fields to suit the unique requirements of our real estate module, enhancingclarity
and usability.
-
We recognize the value of providing users with quick access to insightful data, and thus, we seek to implement
stat buttons
that offer a glimpse into key metrics such as the number of offers associated with a specific property type. -
Through the judicious use of
related fields
and custom actions, we aim to unveil actionable insights with a single click, empowering users to make informed decisions.
As we embark upon this journey to add the final sprinkles to our real estate module
, we do so with a sense of purpose
and determination. With each enhancement we introduce, we draw closer to our vision of creating a user experience that
is both delightful and intuitive
, setting the stage for a new era in property management with Odoo 17.
After adding the final 🎨 decorative touches to our 🏠 real estate module
in the previous chapter, we now dive into this
chapter to explore even more features that enhance the user experience.
Like meticulous craftsmen, we seek to refine existing functionalities by exploring 🔗 inheritance
mechanisms in Odoo.
This allows us to ➕ add new features
while preserving code integrity and system stability.
Similar to superheroes acquiring new powers, we learn to 🚀 extend standard methods
of data creation, reading, writing,
and deletion.
For example, we now 🚫 prevent the accidental deletion
of important properties by disallowing the deletion of any
property that is not new or canceled.
Like an artist 🎨 painting a canvas, we ➕ add new fields
to our existing models to enrich the functionality of our
system.
As user experience architects, we 🛠️ customize
the appearance of our user interface
by inheriting existing views
and adapting them to our specific needs.
For example, we ➕ add a new tab
in the user view to display a list of available properties
, providing users with
quick and intuitive access to relevant information.
😃 With each new improvement we make, we move closer to our goal of creating an exceptional and intuitive user experience.
By fine-tuning
details, adding
new features, and refining
the user interface, we shape Odoo to perfectly meet the
needs of our business, paving the way for even more efficient and effective real estate
management with Odoo 17. 🌟
Building upon the foundation laid in previous Chapter, where we delved into the art of inheritance to enhance
our real estate module
, we now embark on a new journey of integration
and collaboration.
As we continue to polish our real estate
solution, we recognize the need to seamlessly connect
with other modules
,
unlocking new functionalities and streamlining workflows. In this chapter, our focus shifts towards integrating
with
the Invoicing module
to automate the invoice generation
process. 📑💼
Just as skilled artisans carefully craft intricate designs, we meticulously design a 'link' module
to bridge
our real estate
and accounting
functionalities.
By depending on both the estate
and account
modules, this link module
serves as a conduit for data exchange,
ensuring interoperability while maintaining modularity
. 🌐🔗
In the spirit of innovation, we extend our real estate
module's capabilities through model inheritance
.
By overriding
the action triggered
when a property is sold
, we lay the groundwork for automated invoice
creation, seamlessly integrating with the Invoicing module. 🚀🏠
With the framework in place, we turn our attention to crafting invoices
with precision.
Each invoice
is meticulously populated with essential details such as customer ID and move type, setting the stage for
accurate financial transactions. 🧾💳
Just as a skilled artist adds brushstrokes to complete a masterpiece, we add invoice lines
to our invoices.
Each line meticulously captures transaction
specifics, ensuring clarity and accuracy in financial records. 🎨✨
With each step, our real estate
solution evolves into a comprehensive and integrated platform. By seamlessly
connecting with the Invoicing module
, we empower users with automated workflows and enhanced efficiency.
As we navigate through this integration journey, we draw closer to our vision of creating a seamless and intuitive real estate management solution with Odoo 17. 🏡🔧
Building upon the harmonious collaboration achieved in previous chapter, where our real estate module
intertwined with
the Invoicing module
, we now embark on a quest to infuse our interface with unparalleled charm and flexibility. 🌟
In this chapter, we journey into the mystical realm of QWeb Templates
, a realm where design and functionality converge
in harmony. As we gaze upon the landscape of our real estate application
, we realize that to truly captivate our
users, we must transcend the ordinary and embrace the extraordinary. 🏞️
QWeb Templates
emerge as our guiding light, offering us the power to weave intricate designs
and dynamic templates
with ease. With QWeb
as our ally, we set out to create a wondrous Kanban view
for our properties. 🎨
In the enchanted land of Odoo, a Kanban view
is no mere display of data; it is a canvas
upon which we paint our
dreams and aspirations. With each stroke of our virtual brush, we bring life to the cards, infusing them with meaning
and purpose. 🖌️
As we delve deeper into the mysteries of QWeb
, we discover the art of conditional display
, allowing our properties
to reveal their secrets only when the time is right. Through the t-if
directive, we wield the power to create dynamic
and engaging interfaces that respond to the whims of our users. 🎭
But our journey does not end there. With the knowledge gained from our adventures in QWeb, we embark on a quest to
improve our Kanban view
further. We adorn it with treasures such as expected price, best price, selling price, and
tags, transforming each card into a masterpiece of information and insight. 💼
And as the final touch to our masterpiece, we invoke the ancient magic of default grouping
, arranging our properties
by type with effortless grace. With a wave of our wand, we create harmony amidst chaos, ensuring that each card finds
its rightful place in the grand tapestry of our real estate
application. 🌌
As our journey through the realm of QWeb
comes to a close, we emerge as masters of interface design
, armed with the
knowledge and skills to create captivating and immersive experiences for our users. With QWeb
as our guide, we
continue to push the boundaries of what is possible, forging new paths and unlocking new horizons in the world
of Odoo development
. 🚀
As our journey through the realm of Odoo
nears its conclusion, we stand on the precipice of greatness, poised to
embark on one final quest: the pursuit of perfection
in our code. 🏰
Guided by the ancient principles of
the Odoo coding guidelines,
we set forth to refine our creations and elevate them to new heights of excellence. These guidelines
, like the sacred
scriptures of our craft, are a roadmap to improving the quality
of our Odoo Apps code
. 📜✨
With each line of code we refactor
, we breathe life into our creations, imbuing them with the essence of best
practices and standards. We meticulously adhere to the module structure
, ensuring that our code is organized
and
easy to navigate. We choose variable names
with care, selecting words that convey meaning and clarity
. Our method
names follow a convention that speaks to the heart of readability
and coherence
. 💻🔍
As we polish our code
to a brilliant sheen, we heed the call to run our linter
, the vigilant guardian
of code quality
. With its watchful eye, we detect and rectify any deviations from the guidelines
, ensuring that our
code stands as a paragon of excellence. 🛡️🔧
But our journey does not end there. With our code refined and perfected, we turn our gaze towards the horizon and behold
the majestic runbot, Odoo's
own guardian
of stability and reliability. Here, on this
sacred ground, every commit, branch, and pull request undergoes rigorous testing
to prevent regressions
and uphold
the sanctity of the stable versions
. 🤖⚙️
In the realm of the runbot
, we witness the culmination of our efforts, as each successful test
run heralds the birth
of a new iteration of Odoo
, infused with the spirit of our dedication and craftsmanship. 🎉🌟
And so, dear traveler, as our odyssey draws to a close, we invite you to join us in this final act of exploration.
Journey to the runbot website, where the fruits of our labor await your inspection. Behold
the last stable version of Odoo
in all its glory, and marvel at the myriad applications and functionalities that
embody the spirit of our quest for perfection. 🚀🔍
SEE YOU NEXT 😃
Once upon a time in the kingdom of Odoo, there were sacred rules known as the Coding Guidelines
. These guidelines were
like magic spells that aimed to make the code of Odoo Apps shine brighter than the stars. 🌟
You see, proper code
was more than just lines on a screen; it was the key to unlocking the secrets of readability
,
the sword that vanquished complexity
, and the shield that guarded against bugs
. And so, every developer who dared to
venture into the realm of Odoo was expected to abide by these guidelines
, for they held the secrets to
crafting software
of the highest quality
.
But heed this warning, dear reader: when treading upon the paths of stable versions
, thou shalt not tamper with
existing files! For the style of those files is sacred, and any attempt to alter them would disrupt the very fabric
of revision history
. Keep thy changes minimal, and let the original style
reign supreme.
And in the land of directories
, where modules took shape, there lay the heart of business logic. From data
to models
, controllers
to views
, each directory whispered its purpose to those who dared to listen.
And file naming
? Ah, a tale as old as time itself! For in Odoo, the names of files were like breadcrumbs leading
developers on a journey of understanding
. Whether it be models or security, views or wizards, each file bore a name
that revealed its true essence
.
But let us not forget the stories of controllers
and static files, where JavaScript
and templates danced in harmony,
each with its own place in the grand tapestry of code. And wizards
, with their transient models
and views, added a
touch of magic to the world of Odoo.
So, dear reader, as you embark on your quest through the documentation of Odoo 17, remember these tales of
the Coding Guidelines
. For they are not mere rules to be followed, but the very essence of craftsmanship in the
enchanted kingdom of code. 🏰✨✨
Once upon a time in the bustling kitchen of Odoo, there existed a language known as XML
, akin to the recipes that held
the very essence of culinary creations.
In this lively kitchen, XML files
were like well-worn cookbooks, each containing the recipe for a delightful dish of
Odoo. But fear not, for even the novice chef could decipher their secrets with the help of the XML Format
.
Behold, the <record>
notation, a powerful recipe that brought forth new flavors into the kitchen of Odoo. With it, one
could declare views
, actions
, and even menus
with ease. But remember, young chef, to season with the id
attribute before the model
, for it is the key to unlocking the flavor within.
And what of ingredients, you ask? Ah, their declaration was a dance of syntax, where the name
attribute led the way,
followed by the value
in the field
tag or eval
attribute. And let us not forget the other
attributes, ordered by importance
, for they too played a role in shaping the taste of Odoo.
But wait! There are shortcuts, dear chef, shortcuts that can save you from the labyrinth of XML
. The menuitem
and template
tags, acting as sous-chefs in the kitchen, allow you to declare menus
and QWeb views
with but a few
ingredients.
Now, onto XML IDs
and naming
, a topic as vast as the pantry itself. For menus
, views
, and actions
, there
exists a recipe, a recipe that ensures clarity
and understanding
in the kitchen of Odoo. And let us not
forget security
, where groups
and rules
are named with care, each bearing the mark of its culinary purpose.
But what of inheritance
, you ask? Fear not, for even in the world of XML
, there exists a path for the
brave. Inheriting XML
is a tale of flavors and combinations, where IDs
remain the same, yet hold the power of
transformation within.
So, young chef, as you journey through the kitchen of Odoo, remember these tales of XML
. For they are the recipes to
unlocking the flavors that lie within, guiding you on your quest to become a master of the culinary arts. 🍳👨🍳
Once upon a time in the vibrant world of Odoo, there existed a magical language known as Python
🐍, where developers
wielded the power of code to bring their digital creations to life.
But heed this warning, dear coder, for the path of Python is fraught with peril! Do not venture forth without first
acquainting yourself with the Security Pitfalls
section 🚨, for it holds the secrets to writing code that guards
against nefarious forces.
Now, imagine a realm where code is not just lines on a screen, but a symphony of structure and style
. Enter the world
of PEP8
options, where a linter
acts as a vigilant guardian, ensuring that your code adheres to the standards
of
the Python elders 📏. Though some rules may seem arbitrary, they serve to maintain order and clarity
in the land of
code.
Behold, the Imports
, an organized procession of external
libraries, Odoo
essentials, and module
treasures 📚.
Like ingredients in a grand feast 🍲, they are arranged with care, each serving a specific purpose in the grand recipe of
your code.
But what of the Idiomatics of Programming
, you ask? Ah, here lies the heart of Pythonic wisdom
! From the humble
creation of dictionaries
to the art of list comprehensions
, these are the guiding principles that transform mere
code into elegant expressions
of logic and clarity ✨.
And let us not forget the Symbols
and Conventions
, where even the naming of variables and methods follows a sacred
tradition 🏛️. From camelcase
in Python classes to the meticulous ordering
of attributes and methods within a model,
every detail serves to honor the craftsmanship of coding.
But beware, young developer, for the road ahead is fraught with challenges. Do not be tempted by the allure
of manual commits
or the misuse of translation methods, for they may lead you down a treacherous path of broken code
and lost data
.
In the realm of Odoo, where the digital pursue the perfection, remember these tales of Python. For they are the keys to
unlocking the full potential
of your code, guiding
you on your quest to become a master of the craft 🛠️.
Once upon a time, in the bustling kitchen of Odoo, where digital recipes were concocted, there existed a special
ingredient known as Javascript
. But much like any culinary craft, it had its own recipe book and kitchen rules
,
guiding the chefs as they whipped up their digital delicacies 🍳.
In this savory realm of web development
, where ingredients danced on the digital stove, the organization
of static files
was akin to the meticulous arrangement of ingredients on a chef's cutting board 🥕. Within the pantry
of the static folder
, each file had its designated shelf, carefully arranged according to the culinary conventions
of the Odoo chefs.
Enter the pantry's library
section, a treasure trove of culinary knowledge where the whispers of seasoned recipes
like jQuery
and others could be heard. Here, within its hallowed shelves, chefs sought the wisdom of the culinary
elders to enrich their creations.
But the journey didn't end there, for beyond the libraries
lay the heart of the kitchen - the ingredients cupboard
🌶️. Within its shelves dwelled the source ingredients, divided into sacred sections of spices, herbs, oils, and more.
And so, the chefs were reminded to embrace the culinary traditions
of strict measurements and the guidance
of
kitchen tools 🧊. For in the world of Javascript
, adherence to the culinary rules
was paramount, ensuring that the
recipe remained pure and free from error.
But heed this warning, dear chefs: never succumb to the temptation of prepackaged
ingredients, for they are but
shadows of their fresh counterparts, lacking the flavor that once made them great.
Armed with the knowledge of Javascript
culinary guidelines
, the chefs ventured forth into the digital kitchen, their
code a flavorful dish in the banquet of the web
. For in the kitchen of Odoo, where digital recipes are cooked to
perfection, it is the code that seasons the feast of digital experiences 🍽️.
Once upon a webpage
, in the land of Odoo, where digital designs
flourished like gardens in springtime, there existed
a realm known as CSS
and SCSS
. Here, amidst the cascading stylesheets
and the flavorful SCSS mixins
, a tale of
syntax, formatting, and naming conventions unfolded.
Imagine, if you will, the kitchen of a master chef, where every utensil has its designated place, and every recipe
follows a precise order of preparation. Similarly, in the world of CSS
and SCSS
, indentation
ruled with four-space
indents, ensuring that each line of code stood in its rightful place, much like ingredients lined up on a chef's cutting
board 🍽️.
But let us delve deeper into this culinary adventure. Just as a chef meticulously orders the sequence of cooking steps,
so too must the web developer organize properties
in their CSS
and SCSS
files. From the outside in, starting with
the position and ending with decorative rules, each declaration found its place in the digital cookbook
📜.
And what of the naming conventions
, you ask? Much like labeling ingredients in jars, CSS classes
were prefixed
with 'o_'
followed by the module name
, ensuring transparency and clarity in the code. Just as a chef avoids
cluttering the kitchen with hyper-specific ingredients, web developers refrained from creating overly
specific classes
, opting instead for a more concise and maintainable approach
.
But the true magic lay in the variables
- the seasoning that brought flavor to the dish of design
. In the world of
Odoo, SCSS variables
followed a sacred naming convention, ensuring harmony
and consistency
in the digital kitchen.
Meanwhile, CSS variables danced across the DOM
, adapting the design and layout to specific contexts
, much like a
skilled chef adjusting the recipe to suit the occasion.
As the tale unfolds, we witness the convergence of CSS
and SCSS
, blending the best of both worlds like a perfect
fusion dish. SCSS variables
laid the foundation of the design system
, while CSS variables
added a touch
of contextual adaptation
, creating a harmonious symphony of style.
And so, dear reader, as we bid adieu to this culinary journey through the world of CSS and SCSS, let us remember that
much like cooking, web development
is an art form where creativity and precision go hand in hand. 🎨✨
In the vast realm of Odoo, where developers journey through lines of code like explorers navigating uncharted lands,
there exists a sacred tradition known as Git guidelines
. Passed down through generations of programmers, these
guidelines serve as a beacon of order amidst the ever-changing sea of code.
🌟 Picture, if you will, a seasoned chef preparing a gourmet meal. Just as the chef meticulously organizes ingredients
and follows a recipe, so too must developers configure their Git settings
. By defining user email
and name
,
developers establish their identity
in the digital kitchen, ensuring that each commit
carries their mark 🍳.
But what of the commit message
, you ask? Much like a chef composing a menu, a commit message comprises four parts:
tag, module, short description, and full description.
🏷️ tags
, much like labels on different compartments of a toolbox. Each tag
serves a specific purpose
, from
fixing bugs
to adding new features
or even reverting
changes that have caused unforeseen issues
. These tags
provide clarity and organization, ensuring that every commit is categorized appropriately.
But tags
alone are not enough. Just as a craftsman carefully selects the right tool for the job, developers must craft
meaningful commit message headers
.
Picture yourself as a storyteller, crafting the beginning of a tale that sets the stage for an epic journey. In the
realm of Odoo development, every commit message
is like the opening line of a story, offering insight into
the purpose behind each change
.
As the protagonist of this narrative, the commit message header
takes center stage after the tag and module name. It's
not just a label slapped onto a package, but rather a concise summary
that hints at the adventure to come.
Avoid the temptation to use vague terms like "bugfix"
or "improvements"
– instead, strive for clarity
and brevity
. Imagine your header as the opening scene of a play, succinctly capturing the essence of the change in
about 50 characters
.
🌟 If applied, this commit will...
and let your header
complete the sentence with clarity and purpose. Whether it's
fixing a bug, adding a new feature, or making improvements, each commit message
sets the tone for the next chapter in
the development saga.
Imagine yourself as a seasoned bard 🎶, weaving tales of code changes
and development quests in the land of Odoo. Every
commit message is like a chapter in a grand saga, telling the story of why and how
the code was transformed
.
As the hero of this narrative, the commit message full description
holds great power. It serves as the guiding star
for future adventurers 🌟 who may journey back to your commit in search of wisdom.
Begin by unraveling the mystery behind your code modifications. Why
did you embark on this quest? What purpose
does
your change serve in the greater scheme of things?
Remember, clarity
is your sword 🗡️, and verbosity
your shield 🛡️ – don't hesitate to share the tale behind your
journey.
While the commit
itself reveals the technical changes
, the commit message
is your chance to shed light on the path
you've chosen. Were there any forks
in the road? Any crucial decisions
that led you to this point? Share your
insights with future travelers 🚀, for they may benefit from your wisdom.
Every commit
should focus on a single module
, avoiding the tangled webs of multi-module changes. By splitting your
quests into separate commits
, you create a clearer roadmap 🗺️ for future explorers, allowing them to navigate
each module's history
with ease.
And remember, fellow developer, the importance of your words cannot be overstated. Craft your commit messages
with
care, for they are the legacy you leave behind. Whether it's a refactor
, a bug fix
, or an improvement
, let your
message echo through the halls of code, guiding and inspiring those who follow in your footsteps.
And so, dear reader, as we conclude this tale of Git guidelines
in Odoo, let us remember the lessons learned from the
culinary world. Just as a well-crafted dish delights the palate, a well-composed commit message
brings clarity and
understanding to the realm of code. 🖥️🍽️
Imagine you're designing a database model. Picture it as a table or a spreadsheet. Here, fields are like the columns, storing specific types of data in each row (record).
The type of data a field holds and how it's presented on the user interface (UI) is defined by its widget. 📊
Odoo offers 15 types of fields from a technical perspective, but Studio expands this choice to 20 by offering some field types multiple times with different default widgets.
Let's break down these fields and their widgets in simple terms. 🛠️
-
Text (char) ✉️ 📞 🌐:
- Stores short text.
- Widgets include Badge (non-editable tag), Copy to Clipboard, Email (clickable mailto link), Image (URL-based), Phone (clickable tel link), and URL (clickable link).
-
Multiline Text (text) 📝:
- For longer text.
- Includes Copy to Clipboard widget.
-
Integer (integer) 🔢 📊:
- Stores whole numbers.
- Widgets include Percentage Pie, Progress Bar, and Handle (for ordering records).
-
Decimal (float) 💸 ⏲️:
- Stores decimal numbers.
- Widgets include Monetary, Percentage, Percentage Pie, Progress Bar, and Time (hh:mm format).
-
Monetary (monetary) 💶:
- For monetary values.
- Requires a Currency field.
-
Html (html) 🌐:
- Editable text with HTML.
- Option to disable the HTML editor.
-
Date (date) 📅:
- Select a date from a calendar.
- Widget includes Remaining Days.
-
Date & Time (datetime) 📅⏰:
- Select both date and time.
- Widgets include Date (only date shown) and Remaining Days.
-
Checkbox (boolean) ✅🔲:
- True or false value.
- Widgets include Button and Toggle.
-
Selection (selection) ⭐ 📻:
- Choose from predefined values.
- Widgets include Badge, Badges, Priority (star rating), and Radio buttons.
- Priority (selection) ⭐⭐⭐:
- Three-star rating system, similar to a selection field with predefined values.
- File (binary) 📂 🖼️ 📄:
- Upload any file or sign a form.
- Widgets include Image, PDF Viewer, and Sign.
- Image (binary) 🖼️:
- Upload and display images.
- A specific type of File field.
- Sign (binary) ✍️:
- Electronically sign a form.
- A specific type of File field.
-
Many2One (many2one) 🔗📻:
-
One2Many (one2many) 🔗🔗:
-
Lines (one2many) 📝📊:
- Create a table with rows and columns.
-
Many2Many (many2many) ✅🏷️:
-
Tags (many2many) 🏷️:
- Display multiple values as tags.
- A specific type of Many2Many field.
-
Related Field (related) 🔄:
- Fetch and display information using an existing relationship.
- Invisible: Hide fields from the UI when not necessary. 👻
- Required: Ensure fields are filled before proceeding. 🚦
- Read only: Make fields non-editable. 🔒
- Label: Display name of the field on the UI. 🏷️
- Help Tooltip: Explain the field's purpose with a tooltip. ℹ️
- Placeholder: Provide example text in the field. 💡
- Widget: Change the field's appearance or functionality. 🎨
- Default value: Set a predefined value for new records. 🆕
- Limit visibility to groups: Restrict field visibility to specific user groups. 🔐
By understanding and configuring these fields and widgets in Odoo 17, you can create a robust and user-friendly database model, tailored to your specific needs. 🏗️💼
Here's a summary of the "Views" section in the Odoo 17 documentation, now with some emojis to make it more engaging:
Views in Odoo are like different lenses through which you can look at your data.
Imagine you have a treasure chest of information, and views are the various ways you can arrange and display that treasure to make it useful.
Each model, which you can think of as a type of data collection (like contacts or sales orders), can have several views to present the same data differently.
In Odoo Studio, views are grouped into four main categories: general, multiple records, timeline, and reporting. 🌟
-
Form View ✍️
-
Activity View 📅
-
Search View 🔍
-
Kanban View 🗂️
-
List View 📑
-
Map View 🗺️
-
Calendar View 📆
-
Cohort View 📈
-
Gantt View 📅
-
Pivot View 📊
-
Graph View 📉
-
Dashboard View 📊
- To change a model's default view, navigate to Studio, select Views, use the dropdown menu (⋮), and choose "Set as Default."
- For advanced customization, use the built-in XML editor in Developer mode.
- However, avoid modifying standard views directly; instead, create and edit inherited views to ensure changes persist through updates.
By understanding and utilizing these different views in Odoo 17, you can effectively manage and display your data, tailoring the experience to meet your specific needs. 💡
In the world of Odoo 17, models, modules, and apps are the fundamental building blocks
of your data universe.
Let's dive into their roles and how they shape your business processes, all in an easy-to-understand language.
Imagine models
as the skeletons of your database, defining its structure
and how data is stored and manipulated.
Each model represents a table, and these tables are interconnected to represent various business concepts like sales orders, contacts, or products.
Think of models as the blueprints for organizing your information logically and efficiently.
Modules and apps are like the construction workers that bring your blueprints to life.
They contain all the necessary elements—models, views, data files, web controllers, and static web data—to create a functional and interactive system.
While all apps are essentially modules, the term "apps"
usually refers to larger, standalone modules, whereas other
modules often act as add-ons to enhance these apps.
When creating a new model or app using Odoo Studio
, you can opt for up to 14 features
to streamline the process.
These features bundle fields, default settings, and views commonly used together, offering standard functionalities
from the get-go.
Although most features can be added later, incorporating them early simplifies the model creation process and enhances their interaction.
- Contact Details 📇: Adds fields for linking to contacts, including phone and email, and activates the Map view.
- User Assignment 👤: Allows assigning tasks to internal users and displaying their avatars.
- Date & Calendar 📅: Introduces a Date field and activates the Calendar view.
- Date Range & Gantt 🗓️: Adds start and end date fields and enables the Gantt view.
- Pipeline Stages 📈: Activates the Kanban view with stages like New, In Progress, and Done.
- Tags 🏷️: Adds tagging capabilities to your forms and lists.
- Picture 🖼️: Allows adding images to the top-right of forms.
- Lines 📋: Incorporates a Lines field inside a Tab component.
- Notes 📝: Introduces an HTML field for notes.
- Monetary Value 💰: Adds fields for monetary values and activates Graph and Pivot views.
- Company 🏢: Useful for multi-company environments, adds a company field.
- Custom Sorting 🔄: Enables manual reordering of records with a drag handle.
- Chatter 💬: Adds messaging, note logging, and activity scheduling functionalities.
- Archiving 📦: Introduces the ability to archive records and hide them from searches by default.
Once you've customized your models using Studio, you can export these customizations as a module
named "Studio customizations
".
This makes it easy to transfer your customizations to another database.
Simply export your customizations from the main dashboard, download the ZIP file
, and import it into the new database.
Before importing customizations, ensure that the destination database
contains the same apps
and modules as the
source.
Studio customizations do not automatically add underlying modules as dependencies.
With these tools and features at your disposal, crafting your data in Odoo 17 becomes a seamless and intuitive experience, even for those new to the world of databases. Happy building! 🚀
Imagine a world where your routine tasks are handled automatically
, freeing up your time for more important work.
This is the magic of automation rules
in Odoo 17, where you can set up automatic changes triggered by user actions,
email events, time conditions, or external events.
Let's explore how these automation rules work in a straightforward and simple way.
To begin, open Studio
and navigate to Automations
.
Click on "New
" to create a new rule. Choose your Trigger
, fill in the necessary fields, and then define the action
you want to occur.
Save your rule, and you're done! It's as simple as that. 🚀
Triggers define when your automation rule will kick in.
There are five main types:
- Values Updated 🔄: Triggers based on changes to specific fields, like adding a tag or setting a user.
- Email Events 📧: Triggers when emails are sent or received.
- Timing Conditions 📅: Triggers based on dates, like sending a reminder before an event.
- Custom 📝: Triggers based on saving, deleting, or UI changes.
- External 🌐: Triggers based on external events via webhooks.
Once you have defined your trigger
, you need to specify what action should occur.
Here are the types of actions you can set up:
- Update Record ✍️: Modify the fields of a record.
- Create Activity 📅: Schedule a new activity linked to the record.
- Send Email and Send SMS ✉️📲: Automatically send emails or text messages.
- Add Followers and Remove Followers 👥: Manage who follows a record.
- Create Record 📄: Generate a new record in any model.
- Execute Code 💻: Run custom Python code.
- Send Webhook Notification 🌐: Send data to an external system.
- Execute Existing Actions 🔗: Trigger multiple actions at once.
- Before Update Domain 🔍: Set conditions that must be met before the automation rule is triggered.
- Extra Conditions ✅: Add additional criteria that must be satisfied for the rule to execute.
- Logging 📝: Keep track of the data sent by external systems to ensure everything runs smoothly.
Let's say you want to automate the process of archiving old records.
You could set up a timing condition to trigger this action 7 days after the last update.
Or, if you need to send a reminder email 30 minutes before a meeting, you can create a timing condition based on the event's start time. ⏰📧
Webhooks are powerful tools for integrating Odoo with external systems.
They work by sending HTTP(S) requests to a specified URL when certain events occur.
This allows you to automate actions based on data from other applications, ensuring seamless communication between your systems. 🤝
Automation rules in Odoo 17 are like having an assistant who handles repetitive
tasks for you.
By setting up these rules
, you can streamline your workflow
, save time, and ensure that critical actions
are
taken automatically
.
Whether you're updating records, sending notifications, or integrating with external systems, automation rules
make it
all possible.
Start building your automation rules today and watch your productivity
soar! 🚀✨
Imagine having the power to create and customize
PDF reports that perfectly reflect your company's style and needs.
With Odoo 17's Studio
, you can do just that, making professional and personalized reports
for invoices, quotations,
and more.
Let's dive into this journey of transforming how you present
your business data
.
The journey begins with setting up the default layout for your reports.
Head to the Settings and under the Companies section, click Configure Document Layout.
Here, you can choose from four layouts
: Light, Boxed, Bold, and Striped. You can also select from seven fonts, such as
Lato and Roboto, and upload your company logo.
Adjust the primary and secondary colors
, choose a background (like Geometric or Custom), and add your company's
tagline and details.
This setup applies to all your reports, ensuring consistency
across your documents.
When you need a new report, navigate to the relevant model, toggle Studio, and click on Reports.
Click New, and choose the type of report: External
(with a company logo and footer details), Internal
(with user
and company info), or Blank
(no header or footer).
Once created, you can start editing the report to fit your needs.
To edit an existing report, select it from the Reports section in Studio.
It's recommended to duplicate
the standard report first, ensuring the original remains unchanged.
Use the options on the left to rename
the report, change its paper format, and set its visibility
to specific user
groups.
You can also add the report to the Print menu and reset
it to its default state if needed.
The report editor
is where the real customization happens. You can modify
formatting and content directly.
Use commands to add fields, tables, images, and more. Type /
to open the powerbox and choose what you need.
For instance, add a field by selecting the Field command, find the field you want, and insert it.
Similarly, add data table
s to display relational fields, and format your text using the text editor.
Conditional blocks (dashed rectangles) let you show or hide content based on specific conditions.
For example, display different information depending on the status of an order.
These conditions
are set in XML
, but you can preview
and adjust them in the editor.
Dynamic text, highlighted in blue, automatically updates with field values when the report is generated.
For instance, the SO number or quotation date will appear dynamically
in the final report.
For those needing advanced customization, you can edit the report's XML
directly.
This allows for precise control
over the report's structure and content.
However, be cautious
, as direct XML edits might cause issues during system upgrades. If problems arise, simply copy
your changes from the old database
into the new one.
Creating and editing PDF reports in Odoo 17 is like painting a masterpiece.
With Studio, you have the tools to craft documents that are not only functional
but also beautifully
tailored to
your business's identity.
From setting up the default layout
to diving deep into XML
edits, Odoo empowers you to present your data
in the
best possible light.
Start your journey today and see how easy it is to create stunning reports
that make an impact. 🚀📊
After mastering the art of customizing Odoo 17 with Odoo Studio
, it's time to delve into the powerful world
of Odoo.sh
.
Odoo.sh is a comprehensive platform-as-a-service (PaaS) designed to make deploying, managing, and scaling your Odoo applications a seamless experience.
Let's embark on this journey to understand how Odoo.sh
can revolutionize your Odoo development and deployment process.
Odoo.sh
is a cloud platform tailored specifically for Odoo applications.
It combines the flexibility of cloud hosting
with the robust features of Odoo, allowing you to develop, test, and
deploy your Odoo instances effortlessly.
Whether you're a developer, a business owner, or an IT manager, Odoo.sh
provides the tools you need to ensure your
Odoo environment
is secure, scalable, and easy to manage.
If you prefer watching videos, here is a great tutorial on the topic:
-
Automatic Deployment 🚀
- Odoo.sh automates the deployment process, allowing you to push your changes to a staging environment or directly to production with a single click.
- This ensures that your updates are consistently and reliably applied.
-
Continuous Integration (CI) 🔄
- With
built-in CI
, every change you push is automaticallytested
. - This helps catch and
fix issues
early, ensuring your application remains stable and functional.
- With
-
Backups and Security 🔐
- Odoo.sh takes care of your data with automatic
daily backups
and robust security measures. - This means your data is safe and can be restored easily if needed.
- Odoo.sh takes care of your data with automatic
-
Scalability 📈
- The platform is designed to scale with your business.
- You can easily adjust resources to meet the demands of your growing application, ensuring optimal performance.
-
Collaboration Tools 🤝
- Odoo.sh includes features that facilitate collaboration among team members, such as branch management, merge requests, and automated testing environments.
- This streamlines the development process and enhances team productivity.
Odoo.sh
is more than just a hosting solution; it's a complete platform that streamlines the development, deployment,
and management of your Odoo applications.
With its robust features, automated processes, and collaborative tools, Odoo.sh
empowers you to focus on building and
enhancing your applications without worrying about infrastructure management.
Dive into Odoo.sh
and discover how it can elevate your Odoo projects to new heights. 🚀☁️
Once you're ready to create your Odoo project, head over to Odoo.sh and click on the Deploy your platform button.
Next, sign in with your GitHub
account. If you don't have one, simply click on the Create an account link to get
started.
You'll need to authorize
Odoo.sh to access your GitHub account.
This is crucial because Odoo.sh needs permissions to:
Know
your GitHub login and email.Create
a newrepository
if you’re starting from scratch.Read
your existing repositories if you’re using one.Create
awebhook
for updates when you push changes.Commit
changes to streamline your deployment.
Decide whether to start from scratch or use an existing repository
. Then, name your repository or select an existing
one and choose the Odoo version
you want to use.
If you have a subscription code
, enter it here. This code is tied to your Enterprise subscription
, which
includes Odoo.sh
.
If your subscription isn't valid, it could mean:
- It doesn't exist.
- It’s not a partnership subscription.
- It’s an Enterprise subscription that doesn't include
Odoo.sh
. - It’s another type of subscription (e.g., online subscription).
If you're unsure, contact Odoo support
for assistance.
Your platform is now being created. Soon, you'll be able to connect to your first database
.
You can import your database into your Odoo.sh
project if it’s a supported version.
For custom
or community modules
, add them to a branch in your GitHub repository. Odoo.sh
will detect the folders
containing Odoo addons
.
You can structure your modules
as you like, either at the root or in categorized folders.
For publicly available community modules, consider adding them as submodules
. Make this branch your production branch
or merge it into an existing one.
Access the URL /web/database/manager
of your on-premise database and download a backup.
You'll need the master password
of your database server. If you don't have it, contact your system administrator.
Access your database manager and download a backup. Note that online versions (e.g., saas-*) are not supported
on Odoo.sh
.
In your Odoo.sh
project, go to the backups tab of your production branch and import the backup.
Once imported, you can access the database using the Connect button.
Odoo.sh
provides a default mail server. Ensure no outgoing mail server is enabled in your database settings.
After importing your database, all outgoing email servers are disabled
by default.
Scheduled actions are disabled
after the import to prevent any unintended operations.
If you plan to use the imported database in production, enable
the necessary scheduled actions.
These can be found under Settings ‣ Technical ‣ Automation ‣ Scheduled Actions.
After importing, your subscription will be unlinked
.
Unlink your former database from the subscription
and register the new one by following the database registration
documentation.
Imagine you’re an explorer, setting up your adventure base camp with Odoo.sh
.
Here’s your journey through managing branches
in a way that's easy to grasp, even if you’re new to the tech world.
Your repository is like a tree, and branches are its limbs, each holding different parts of your project.
The branches
view gives you a map of these limbs, helping you see where each one stands.
Think of your branches moving through three main stages: production, staging, and development.
The production
branch is your main
branch, where your live project runs. It’s like the main base camp where
everything is up
and running
.
When you push
new changes
here, your server updates and restarts to include the latest improvements
. If there’s a
hitch, the system rolls back
to the last working version
, ensuring everything stays smooth.
Staging
branches are your testing
grounds, safe zones where you test new features
using real data
without
affecting your main
base camp.
Here, scheduled actions are paused
, emails are intercepted
, and services like payments are set to test mode
.
It’s like practicing
a drill before the actual adventure.
Development
branches are your workshops
. They use demo data
to run tests and ensure your new changes
don’t break
anything.
When you push
updates here, a new environment
is created from scratch, loaded with demo data
, and all tests
are
run automatically.
Merging
branches in Odoo.sh
is like combining paths in your map. You can drag
and drop
branches into each other
to merge them.
For example:
- To
test
new changes,merge
your development branch into a staging branch. - When changes are ready for live use,
merge
your staging branch into the production branch.
You can also use git merge
commands if you prefer working directly from your workstation.
This tab records every change, commit, and event, like a detailed journal
of your adventure.
You can see who
made changes, what
was changed, and the outcome
of each event.
The mail catcher
tab shows all the emails sent from your database, but only for development and staging branches,
ensuring no test emails
bother your real contacts.
This is your command center, where you can run basic commands
and open a shell to interact directly with your
database.
The online
integrated development environment (IDE
) is where you write and edit your code. It supports multiple tabs
and various tools to streamline your development process.
Here, you’ll find graphs and metrics
monitoring your builds
. You can zoom in, adjust time ranges, and see
annotations related to changes.
The logs
tab shows detailed records of server activities. You can view logs
for installations, updates, and
server operations
.
Backups are your safety nets. Odoo.sh
automatically backs up
your production
database daily
, keeping copies for
a month
. You can also manually create backups before major changes
to ensure you have a restore point
if things go
awry.
In the settings tab, you can customize
how branches behave upon new commits, select modules to install, enable or
disable tests, and set the Odoo
version.
You can also configure custom domains
and ensure your outgoing emails comply with SPF
and DKIM
standards for
better deliverability.
By following this storytelling approach, you’ll navigate through Odoo.sh
branches with ease, understanding each step
as part of your exciting journey into Odoo
development. 🌟
Imagine you're setting up a project base in Odoo.sh
. Here’s your journey through understanding and managing builds
,
explained in a way that even beginners can follow.
In Odoo.sh
, a build is like a test run
of your project. It involves loading your database on an Odoo server within
a containerized
environment.
Think of it as a rehearsal to ensure everything works smoothly.
In the builds view, each row
represents a branch
of your project, and each cell
in that row represents a build
of that branch.
Builds are typically created whenever you push
updates to your GitHub repository
branches. They can also occur when
you import
a database into Odoo.sh
or manually trigger a rebuild
for a branch.
- Successful Builds 🟢: Highlighted in
green
, meaning no errors or warnings. - Failed Builds 🔴: Highlighted in
red
, indicating errors occurred. - Almost Successful Builds 🟡: Highlighted in
yellow
, showing warnings but no critical errors.
Builds don't always start a database from scratch.
For example, pushing
changes to the production branch starts the server with your new revision
and tries to load
the current
production database. If it works without errors, it's successful.
The first build
of your production branch creates the main
database. Subsequent pushes
create new builds that
attempt to update
this database with the latest
changes.
If a build fails
, the system reverts to the last successful
build to keep everything running smoothly.
Staging
builds create copies
of your production database. Each new push
on a staging branch uses a fresh copy
,
ensuring you test with up-to-date
data.
Changes made here don’t affect the production
database, so you can experiment freely. Remember, configuration
changes in staging don’t carry over unless applied
to production.
Development builds create new
databases with demo data
and run unit tests
.
These tests check for errors
, and a build is marked as failed
if any tests fail. Successful builds mean all
tests passed
without issues.
Depending on the number of modules, these builds can take up to an hour
.
- Production Branch: Always appears first, followed by other branches
sorted
by the last build created. You canfilter
branches to find what you need. - Accessing Builds: Use the
Connect
link to access a build’s database. Jump to thebranch code
with theGitHub
link. You can create anew build
with the latest revision using therebuild
link, provided no other build is in progress.
For each build:
- Revision Changes: Click the GitHub icon to see what changed.
- Database Access: Use the
Connect
button to access the database as anadmin
. The dropdown menu lets youconnect as
another user, check logs, use the web shell, edit code, manage outgoing emails, and download a database dump.
By following this storytelling approach, you’ll navigate through Odoo.sh
builds with ease, understanding each step as
part of your exciting journey into Odoo development. 🌟
The Status tab on Odoo.sh serves as your main dashboard to monitor the health and performance of your project. It's like a command center where you can keep an eye on your application's vital signs.
The Status tab on Odoo.sh is a powerful tool for maintaining the health and performance of your project. By regularly monitoring this tab, you can anticipate problems, optimize resources, and ensure a smooth and reliable user experience. 🚀
Imagine you're the captain of a ship navigating through the vast ocean of project management on Odoo.sh
. The *
Settings* tab is your control room, where you configure and fine-tune everything to ensure smooth sailing.
First, you name your ship. This name sets the address where your production database can be accessed.
It's like giving your ship a unique identifier. When you rename your project, future builds will sail under this new name, but past voyages retain their original names.
Your crew is essential for a successful voyage. You manage your crew through the Collaborators section. There are two types of crew members:
- Admins: They have full access to all features on
Odoo.sh
, akin to your first mates who can navigate any part of the ship. - Users: These are like your deckhands, skilled in coding but restricted from accessing sensitive areas like the production data or the ship’s logs.
Admins can use all tools available, while Users can only modify code without touching the critical data.
Sometimes, you might want to show off your ship's development progress to the public.By enabling Public Access, you allow visitors to view your development builds, logs, shell, and emails.
However, your production and staging areas remain off-limits, maintaining their security.
If you want your ship to be recognized by multiple names (domains), you can configure this in the Custom Domains section. Each branch of your project can be assigned a different domain, making your ship known by various identities.
Your ship may rely on additional resources from private repositories. To access these, you need to set up **Deploy Keys **.
This is like giving special permission to retrieve secret supplies from these private sources. You provide
the SSH URL
of the private repository, add it, and then copy and paste the public key
to the repository's settings.
Every ship needs to monitor its cargo. The Storage Size section shows how much space your project is using,
including the PostgreSQL
database and disk files in your container.
If you exceed your storage limits, the system automatically synchronizes with your subscription to accommodate the growth.
To handle more tasks simultaneously, you can add more Database Workers. This is like hiring additional crew members to manage the increased workload.
However, it’s important to note that adding more workers won’t solve all performance issues; sometimes the problem lies deeper within the code.
You can develop and test multiple features at once by adding more Staging Branches.
This allows you to conduct various experiments without interfering with your main operations, ensuring that your ship's journey remains uninterrupted.
Finally, the Activation section shows the status of your project's activation. Here, you can change the activation code if needed, ensuring that your ship remains operational and ready to sail.
The Settings tab in Odoo.sh is your essential toolkit for managing and configuring your project. By carefully adjusting these settings, you can ensure that your project runs smoothly and efficiently, just like a well-navigated ship on a successful voyage. 🚀
Imagine you're about to dive into the world of Odoo 17. With Odoo.sh, you have a powerful online editor at your fingertips, accessible right from your web browser 🌐.
This editor allows you to modify the source code of your builds, open terminals, Python consoles, Odoo Shell consoles, and even Notebooks 📚.
Getting to the editor is straightforward 🚀. You can reach it through the branches tabs, the builds dropdown menu, or by
adding /odoo-sh/editor
to your build's domain name.
Within the editor, you find a structured working directory 🗂️:
- home/odoo/src/: Contains the source codes for Odoo Community, Odoo Enterprise, Odoo Themes, and your repository branch.
- home/odoo/data/: Holds database attachments and user session files.
- home/odoo/logs/: Keeps logs for database installations, server runs, database updates, and Python package installations.
You can edit the source code in development and staging builds. However, remember that any changes you make won't persist unless you commit them to your source code 📝.
To edit a file, just double-click it in the file browser 🖱️. Save your changes via the File menu or with the Ctrl+S shortcut 💾.
If you save a Python file within the Odoo server addons path, Odoo will automatically reload it to reflect your changes instantly. For changes stored in the database, like field labels or views, you'll need to update the corresponding module 🔄.
Once you're satisfied with your changes, you can commit and push them to your GitHub repository 📤:
- Open a terminal (File ‣ New ‣ Terminal) 💻.
- Navigate to your user directory:
cd ~/src/user
📂. - Stage your changes:
git add
📋. - Commit your changes:
git commit
✅. - Push your changes:
git push https HEAD:<branch>
🚀.
Use the HTTPS remote of your GitHub repository, as SSH authentication isn't possible through the web-based editor 🔐.
If you have two-factor authentication on GitHub, use a personal access token as your password 🔑.
The editor also provides Python and Odoo Shell consoles 🐍. Python consoles offer rich display capabilities, allowing you to visualize objects in HTML 🌐.
For example, you can use pandas to display cells of a CSV file 📊.
In the Odoo Shell console, you can interact with the Odoo registry and model methods of your database 🛠️.
Be cautious, as changes are automatically committed to the database env
and
display lists and dicts prettily with the Pretty
class 🌟.
In this chapter, we'll walk you through creating your very first Odoo module and deploying it in your Odoo.sh project.
It's a straightforward process, even if you're new to Git and GitHub. Let's get started! 🌟
Before diving in, make sure you have:
- A project on Odoo.sh.
- Your GitHub repository URL.
We'll assume the following setup:
~/src
is your directory for Odoo projects.odoo
is the GitHub user.odoo-addons
is the GitHub repository.feature-1
is your development branch.master
is your production branch.my_module
is your module name.
Feel free to replace these with your own values.
From Odoo.sh:
- Go to the branches view.
- Click the + button next to the development stage.
- Choose the
master
branch in the Fork selection. - Type
feature-1
in the "To" input field.
From Your Computer:
-
Open your terminal and clone your GitHub repository:
mkdir ~/src cd ~/src git clone https://github.com/odoo/odoo-addons.git cd ~/src/odoo-addons
-
Create a new branch:
git checkout -b feature-1 master
Scaffolding the Module:
-
Open a terminal in the Odoo.sh editor or your computer.
-
Run the scaffolding command:
odoo-bin scaffold my_module ~/src/user/
or
./odoo-bin scaffold my_module ~/src/odoo-addons/
This generates the basic structure for your module, making it easier to get started.
my_module/
__init__.py
__manifest__.py
controllers/
__init__.py
controllers.py
demo/
demo.xml
models/
__init__.py
models.py
security/
ir.model.access.csv
views/
templates.xml
views.xml
Uncomment the content in the following files to define your module’s behavior:
models/models.py
views/views.xml
demo/demo.xml
controllers/controllers.py
views/templates.xml
__manifest__.py
-
Stage your changes:
git add my_module
-
Commit your changes:
git commit -m "My first module"
-
Push your changes to GitHub:
From Odoo.sh:
git push https HEAD:feature-1
From your computer:
git push -u origin feature-1
Your new branch should appear in your project's development branches.
You can test your module by accessing the development build and creating new records to see how your features work.
- Make your development branch a staging branch or merge it into an existing staging branch.
- This creates a new staging build using the latest changes from your branch.
Once you're satisfied with your module's performance in staging, merge your branch into the production branch.
This will update your production server with the latest changes.
To add a new field to your module:
-
Open
models/models.py
and add:start_datetime = fields.Datetime('Start time', default=lambda self: fields.Datetime.now())
-
Open
views/views.xml
and add:<field name="start_datetime"/>
-
Update the module version in
__manifest__.py
:'version': '0.2',
-
Stage, commit, and push your changes:
git add my_module git commit -m "[ADD] my_module: add start_datetime field" git push https HEAD:feature-1
The platform will then create a new build for the branch feature-1.
To use an external library like Unidecode:
-
Create a
requirements.txt
file and add:unidecode
-
Use the library in your module:
from unidecode import unidecode @api.model def create(self, values): if 'name' in values: values['name'] = unidecode(values['name']) return super(my_module, self).create(values) def write(self, values): if 'name' in values: values['name'] = unidecode(values['name']) return super(my_module, self).write(values)
-
Update the module version to
0.3
in__manifest__.py
. -
Stage, commit, and push your changes.
With these steps, you've created your first Odoo module, tested it, and deployed it in production.
Congratulations! 🎉
After creating your first module with Odoo.sh, it's time to dive deeper into managing the data that powers your module. This chapter will guide you through the types of data you can define and how to structure and declare them effectively within your Odoo module.
In Odoo, data is categorized into two main types: Master Data and Demo Data.
Master Data is essential for the module to function correctly. It includes technical data like views and actions and business data such as countries, currencies, and legal reports. This data is automatically installed with the module.
Demo Data is used for demonstration and testing purposes. It helps sales representatives perform demos, allows developers to test new features, and ensures that data loads correctly without errors. Demo data is loaded automatically unless you specify otherwise.
To declare data in your module, you need to include it in the module's manifest file. Data can be declared in CSV or XML format, with each file listed under the appropriate key in the manifest.
Manifest Example:
{
"name": "Real Estate",
"depends": ["base"],
"data": [
"security/ir.model.access.csv",
"views/estate_property_offer_views.xml",
"data/master_data.xml",
],
"demo": [
"demo/demo_data.xml",
],
"application": True,
}
CSV files are ideal for simple, long lists of data. They are easy to create and maintain but are limited in functionality compared to XML.
CSV Example:
id,field_a,field_b,related_id:id
id1,valueA1,valueB1,module.relatedid
id2,valueA2,valueB2,module.relatedid
XML is more flexible and powerful, suitable for complex data structures. It allows you to create detailed records and link related data.
XML Example:
<odoo>
<record id="id1" model="tutorial.example">
<field name="field_a">valueA1</field>
<field name="field_b">valueB1</field>
</record>
<record id="id2" model="tutorial.example">
<field name="field_a">valueA2</field>
<field name="field_b">valueB2</field>
</record>
</odoo>
In Odoo, you can extend existing data by adding new fields or enhancing current ones without replacing the original
data. Use the xml_id
of existing records to integrate new information seamlessly.
Extending Example:
<odoo>
<record id="id1" model="tutorial.example">
<field name="field_c">valueC1</field>
</record>
</odoo>
Accessing data in Odoo can be done through Python code, XML references, or CSV declarations. Always code defensively, considering that data can be altered or deleted by users.
Accessing Data Example in XML:
<odoo>
<record id="id1" model="tutorial.example">
<field name="related_id" ref="module.relatedid"/>
</record>
</odoo>
Accessing Data Example in CSV:
id,parent_id:id,name
"child1","module.parent","Name1"
"child2","module.parent","Name2"
Understanding XML ids, the noupdate
flag, and the use of raw SQL for data import are advanced techniques that can
enhance your data management skills. However, these should be used cautiously to maintain data integrity and security.
No Update Example:
The records created with the noupdate flag won’t be updated when upgrading the module that created them, but it will be created if it didn’t exist yet.
<odoo noupdate="1">
<record id="id1" model="model">
<field name="fieldA" eval="True"/>
</record>
</odoo>
By mastering these data management techniques, you'll ensure your Odoo modules are robust, flexible, and reliable, paving the way for more advanced development in the Odoo ecosystem. 🚀
Building on the foundation of module data, this chapter delves into securing your module by restricting access to data.
Ensuring that only authorized users can view or manipulate certain data is critical for maintaining business integrity
and confidentiality
.
In most business environments, security is a key concern.
Without proper restrictions:
- Any employee can create, read, update, or delete properties, property types, or property tags.
- Unauthorized third parties might access sensitive property data.
- Non-agents could view or modify property details.
- Agents might inadvertently alter property types or tags that they shouldn’t.
- Exclusive properties could be managed by unauthorized agents.
- Agents could confirm sales without proper invoicing permissions.
To address these issues, you need to implement security measures that limit access based on user roles and responsibilities.
Odoo uses groups
to manage access rights
and roles. Groups link security rules to users, simplifying the process of
assigning and managing permissions.
Example Groups:
- Real Estate Managers: Can configure the system, manage all property types and tags, and oversee all properties.
- Real Estate Agents: Can manage properties under their care and confirm sales but cannot modify property types or tags.
Groups are defined in the module’s data
files and are crucial for maintaining structured access control.
-
Create the
security.xml
file in the appropriate folder. -
Add to
__manifest__.py
: Include thesecurity.xml
file and set the category field toReal Estate/Brokerage
. -
Define Groups:
<odoo> <record id="estate_group_user" model="res.groups"> <field name="name">Agent</field> <field name="category_id" ref="base.module_category_real_estate_brokerage"/> </record> <record id="estate_group_manager" model="res.groups"> <field name="name">Manager</field> <field name="category_id" ref="base.module_category_real_estate_brokerage"/> <field name="implied_ids" eval="[(4, ref('estate_group_user'))]"/> </record> </odoo>
-
Restart Odoo and update the module to apply changes.
-
Assign the Real Estate Manager role to the admin user and create a new user with the Real Estate Agent role via the web interface.
Access rights allow you to control what users can do with specific models.
Example Access Rights Configuration:
- Real Estate Managers: Full access to all objects.
- Real Estate Agents: Read-only access to property types and tags, no delete rights for properties.
Update your access rights file to reflect these rules and verify by testing with different user roles.
Record rules offer granular
control over access to individual records.
Example Record Rule:
<record id="rule_id" model="ir.rule">
<field name="name">Agent Rule</field>
<field name="model_id" ref="estate.property"/>
<field name="perm_read" eval="True"/>
<field name="perm_write" eval="True"/>
<field name="perm_create" eval="True"/>
<field name="perm_unlink" eval="False"/>
<field name="groups" eval="[(4, ref('estate_group_user'))]"/>
<field name="domain_force">[
'|', ('user_id', '=', user.id),
('user_id', '=', False)
]
</field>
</record>
This rule ensures that agents can only see or modify properties they manage.
In some cases, you may need to bypass
security checks for specific operations. Use sudo()
to temporarily ignore
access rights and record rules.
Example:
property.sudo().write({'state': 'sold'})
Always implement explicit security checks to validate user permissions before bypassing security mechanisms. Use methods
like check_access_rights
and check_access_rule
to ensure the current user has appropriate permissions.
For businesses operating across multiple companies, enforce multi-company rules to restrict access based on the user's company.
def action_sold_property(self):
# Call the super method to perform the default action_sold_property logic
result = super().action_sold_property()
# Ensure the current user has access rights to update properties
self.check_access_rights('write')
self.check_access_rule('write')
...
self.env['account.move'].sudo().create(move_values)
return result
Example Multi-Company Rule:
<record model="ir.rule" id="multi_company_rule">
<field name="name">Multi-Company Rule</field>
<field name="model_id" ref="estate.property"/>
<field name="domain_force">[
'|', ('company_id', '=', False),
('company_id', 'in', company_ids)
]
</field>
</record>
Ensure each property has a company_id
and restrict agents to viewing only properties of their assigned company.
Differentiate between visibility and security:
- Visibility: Controls what is shown in the user interface but doesn’t restrict access.
- Security: Restricts access to data and operations, ensuring unauthorized users cannot interact with them.
Example:
- Visibility: Hide the Settings menu for agents.
- Security: Prevent agents from accessing the Property Types and Property Tags menus.
By following these guidelines, you'll create a secure, well-structured Odoo module, ensuring that users have access to only the data and functions necessary for their roles.
Building upon the security measures from the previous chapter, we now delve into the realm of unit testing. Just as
security ensures data integrity and confidentiality, unit tests ensure the stability
and reliability
of your code.
Imagine you're constructing a skyscraper. Each floor must be sturdy before you build the next one. Similarly, unit tests
are the foundation blocks
of your code, ensuring each part functions correctly before adding new features.
Benefits of Writing Tests:
- Future-proofing: Ensures that changes or new features don't break existing functionality.
- Scope definition: Clearly defines what your code is supposed to do.
- Use case documentation: Provides practical examples of how your code should be used.
- Technical documentation: Offers insights into how the code operates.
- Goal-setting: Helps in defining the objectives before starting the development.
Before writing tests, it's crucial to know how to execute them. Picture yourself at the command line, the control center of your coding environment.
To see the available options, use:
odoo-bin -h
Key options for testing include:
--test-enable
: Activates unit tests.--test-file=TEST_FILE
: Runs a specific test file.--test-tags=TEST_TAGS
: Filters tests based on tags.
To run all tests for the account
module:
odoo-bin -i account --test-enable
Or, to run a specific test file:
odoo-bin --test-file=addons/account/tests/test_account_move_entry.py
In Odoo, CI
ensures that your code remains stable
and bug-free. Each time you push
a commit to GitHub, tools
like Runbot
come into play, automatically running tests to verify the code.
Runbot Insights:
- Commit status: Monitors the state of each commit.
- Batches and builds: A batch includes multiple builds, and a build checks the community and enterprise versions.
- Green signal: A build passes if all tests are successful.
By integrating CI into your workflow, you can catch issues early, ensuring smooth and stable code deployment.
Writing tests is like training a guard dog. They should be independent
and leave no traces
once done. For instance,
if you're fixing a bug, your test should fail
before the fix and pass
afterward.
Test Structure:
Organize tests within your module, similar to how you'd structure the rooms in a house:
estate
├── models
│ ├── *.py
│ └── __init__.py
├── tests
│ ├── test_*.py
│ └── __init__.py
├── __init__.py
└── __manifest__.py
Each test file should start with test_
and be imported in the __init__.py
of the tests folder. Tests
extend odoo.tests.common.TransactionCase
, and you usually define a setUpClass
method to create test data.
Example Test Case:
from odoo.tests.common import TransactionCase
from odoo.exceptions import UserError
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class EstateTestCase(TransactionCase):
@classmethod
def setUpClass(cls):
super(EstateTestCase, cls).setUpClass()
cls.properties = cls.env['estate.property'].create([...])
def test_creation_area(self):
self.properties.living_area = 20
self.assertRecordValues(self.properties, [
{'name': ..., 'total_area': ...},
])
def test_action_sell(self):
self.properties.action_sold()
self.assertRecordValues(self.properties, [
{'name': ..., 'state': ...},
])
Create tests to prevent scenarios where:
- An offer is created for a sold property.
- A property is sold without accepted offers.
These tests act as gatekeepers, ensuring only valid operations are performed.
With experience, tools like Robodoo
and Mergebot
become valuable allies. They help manage code changes, ensuring
smooth merges and maintaining code quality.
By writing and running tests, you ensure your code stands strong, just like a well-built skyscraper. With these practices, you can confidently expand your Odoo module, knowing that each addition is safeguarded by your tests.
Building on the foundation oF previous chapters, we now turn our attention to an essential component in Odoo development—the manifest file.
This file is the passport
of your module
, formally declaring it to Odoo and detailing its key attributes
.
Every Odoo module proudly wears its identity in a file named __manifest__.py
. This file is a simple Python dictionary
containing various metadata
about the module.
{
'name': "A Module",
'version': '1.0',
'depends': ['base'],
'author': "Author Name",
'category': 'Category',
'description': """
Description text
""",
# data files always loaded at installation
'data': [
'views/mymodule_view.xml',
],
# data files containing optionally loaded demonstration data
'demo': [
'demo/demo_data.xml',
],
}
Let’s explore the vital elements that compose this dictionary:
Name and Version:
name
🏷️: This is the human-readable name of your module. It’s the first thing users will see, so choose wisely!version
📅: Following semantic versioning rules, this specifies the version of your module, aiding in tracking updates and compatibility.
Description and Author:
description
📝: Provides an extended description of your module, typically written in reStructuredText. This helps users understand what the module does.author
✍️: The name of the person or organization that developed the module.
Website and License:
website
🌐: A URL for more information about the module or its author.license
📜: Specifies the distribution license for your module. Options include various GPL versions, LGPL-3, and proprietary licenses among others.
Category and Dependencies:
category
🗂️: Classifies the module within Odoo, making it easier to find. While using existing categories is recommended, you can create new ones if necessary.depends
🔗: Lists other Odoo modules that need to be installed first, ensuring all required features and resources are available.
Data and Demo Files:
data
📂: A list of data files that must always be loaded with the module. These are the core files needed for the module to function.demo
🎨: A list of demonstration data files that are loaded only in demo mode, useful for showcasing module features.
Automatic Installation and External Dependencies:
auto_install
🔄: If set to True, the module will be automatically installed if all its dependencies are present. This is useful for modules that provide integration between other modules.external_dependencies
⚙️: A dictionary listing Python and/or binary dependencies required by the module. This ensures all necessary components are available on the host machine.
Application and Assets:
application
🏢: Indicates whether the module is a full-fledged application or just an add-on providing extra functionality.assets
📦: Defines how static files are loaded in various asset bundles, helping to manage resources efficiently.
Installation and Maintenance:
installable
✅: Specifies whether the module can be installed via the web interface.maintainer
🛠️: The person or entity responsible for maintaining the module. By default, this is assumed to be the author.
Hooks:
{pre_init, post_init, uninstall}_hook
🪝: These are special functions that can be executed at different stages of the module’s lifecycle, such as before installation or after uninstallation. They allow for custom setup or cleanup actions.
With this blueprint in place, your __manifest__.py
file ensures your module is properly identified, configured, and
integrated within the Odoo ecosystem. It’s the key that unlocks your module’s potential, declaring its presence and
capabilities for all to see.
As you continue your journey in Odoo development, understanding and crafting this manifest
file will empower you to
create robust, well-defined modules.
Just as unit tests safeguard your code, the manifest file declares your module’s identity and ensures it seamlessly integrates into the Odoo world. 🚀
After mastering the art of module manifests
, our journey in the Odoo development landscape takes us to another
critical aspect— Web Controllers
. These controllers are the gatekeepers
, handling incoming HTTP
requests and
directing them to the right handlers
within the Odoo ecosystem.
Controllers in Odoo are akin to the conductors of an orchestra, ensuring that every request reaches the right endpoint
and is processed correctly. They are created by inheriting from the base Controller
class and defining routes using
the @route()
decorator.
class MyController(odoo.http.Controller):
@route('/some_url', auth='public')
def handler(self):
return "Hello, World!"
This simple piece of code sets up a controller that listens to requests at /some_url
and responds with "Hello, World!"
Just as the Odoo models can be extended, so can the controllers. If you need to modify the behavior of an existing
controller, you can inherit
from it and override its methods. It's important to re-decorate
these methods
with @route()
to ensure they remain accessible.
class Extension(MyController):
@route()
def handler(self):
do_before()
return super(Extension, self).handler()
Without the @route()
decorator, the method becomes unpublished and inaccessible, much like a conductor without a
baton.
The @route()
decorator is the magic wand that maps URLs to controller methods. It supports various parameters to
fine-tune its behavior:
route
: Specifies the URL path(s) this method will handle.type
: Determines the request type, either'json'
or'http'
.auth
: Controls the authentication level required ('user'
,'public'
, or'none'
).methods
: Lists the HTTP methods (GET, POST, etc.) this route accepts.csrf
: Enables or disables CSRF protection.cors
: Configures CORS settings for cross-origin requests.
These parameters allow you to define routes that are as specific or as flexible as needed, ensuring robust and secure handling of requests.
At the heart of every HTTP interaction in Odoo is the request
object. This object wraps around the incoming HTTP
request, providing access to deserialized parameters, session management, and more.
It offers several utilities:
update_env
: Changes the current user or context.csrf_token
: Generates a CSRF token for security.get_http_params
: Extracts key-value pairs from the query string and form data.
These tools ensure that your controllers can handle requests efficiently and securely.
Returning a response in Odoo can be straightforward or complex, depending on your needs. You can return simple strings
for HTML responses, or use helpers like make_json_response()
for JSON data. The Response
class is versatile,
handling everything from cookies to custom headers.
def make_response(data, headers=None, cookies=None, status=200):
return Response(data, headers=headers, cookies=cookies, status=status)
This flexibility allows your controllers to respond appropriately to any situation, ensuring a smooth user experience.
Odoo uses dispatchers
to route and handle different types of requests:
HttpDispatcher
: Handles standard HTTP requests.JsonRPCDispatcher
: Manages JSON-RPC calls, supporting named parameters and custom context.
These dispatchers ensure that each request is processed correctly, whether it’s a simple HTTP call or a complex JSON-RPC interaction.
Web controllers
in Odoo are indispensable, acting as the backbone
of web interactions. By understanding how to
create, extend, and manage these controllers, you unlock the full potential of Odoo's web capabilities.
As we delve deeper into Odoo development, mastering controllers will empower you to build dynamic, responsive, and secure web applications.
With this knowledge in hand, you're now ready to orchestrate your own symphony of web interactions within the Odoo ecosystem. 🚀
Continuing our journey through Odoo development, we arrive at another crucial component—payment methods
.
These are the mechanisms through which customers complete transactions, and understanding how to manage them is essential for ensuring a smooth checkout experience.
The PaymentMethod
class in Odoo serves as the central hub for managing different payment methods. This class provides
the tools needed to handle various payment scenarios efficiently and securely.
When a customer is ready to make a payment, Odoo needs to determine which payment methods are suitable.
The _get_compatible_payment_methods
function plays a vital role here. It searches for and returns payment methods that
meet specific criteria:
- Provider Support: The payment method must be supported by at least one of the specified providers.
- Country Compatibility: If the customer's country is specified, the payment method must support it.
- Primary Methods: Only primary payment methods are considered.
- Additional Filters: Optional parameters can further refine the search, such as requiring tokenization or supporting express checkout.
For example, if security is a priority, you might set the force_tokenization
parameter to True
to ensure that only
payment methods that support tokenization are considered. This helps in handling sensitive card information securely.
In some situations, you need to find a payment method based on a specific code provided by a payment provider.
The _get_from_code
function helps with this.
By using a provider-specific code, it retrieves the corresponding payment method. If you have a mapping of generic codes to provider-specific codes, this function can use it to speed up the search process.
Tokenization is a process that enhances the security of payment methods by replacing
sensitive data, like credit
card numbers, with unique identifiers
known as tokens.
These tokens are randomly generated and have no exploitable
value if intercepted by unauthorized parties.
- Enhanced Security: Tokenization significantly reduces the risk of data breaches because the actual card details are not stored or transmitted during transactions.
- PCI Compliance: By using tokenization, businesses can reduce the scope of PCI DSS (Payment Card Industry Data Security Standard) compliance, as sensitive information is not stored on their servers.
- Customer Trust: Offering tokenized payment methods can increase customer trust, as users are assured that their payment details are handled securely.
In Odoo, when the force_tokenization
parameter is set to True
, the system ensures that only payment methods capable
of tokenization are considered. This adds an extra layer of security
to the payment process, protecting both the
business and its customers from potential fraud.
Let's look at a simple scenario to understand how these functions work:
- Scenario: Your online store supports multiple payment providers like PayPal and Stripe.
- Goal: Ensure only secure payment methods are available for a customer’s transaction.
Using _get_compatible_payment_methods
, you can filter out incompatible methods by setting force_tokenization
to True
. This ensures only secure methods are shown, enhancing the safety of the transaction.
The PaymentMethod
class in Odoo 17 is designed to make managing payment methods straightforward and secure. By
utilizing its powerful functions and understanding the importance of tokenization, businesses can ensure they offer the
best and safest payment options to their customers, thereby fostering trust and reliability in every transaction.
As you continue exploring Odoo, mastering these tools will enable you to create a seamless and secure payment
experience for your users.
Continuing our journey through the intricacies of Odoo 17, we now explore another essential
component: payment providers
. These entities are critical for facilitating transactions, ensuring that each payment is
processed smoothly and efficiently.
Payment providers are integral to Odoo’s payment system, offering a range of features that enhance the payment process.
The capabilities of each provider are determined by specific fields, which are computed using
the _compute_feature_support_fields
method. This method outlines which additional features a provider supports:
- Express Checkout: This feature allows customers to make quick payments without a lengthy checkout process. By
default, it’s set to
False
. - Manual Capture: This feature lets businesses manually capture funds after a payment is authorized. It is
False
by default. - Refunds: Indicates the type of refunds a provider supports, such as no refunds, full refunds only, or partial
refunds. The default setting is
None
. - Tokenization: This feature allows secure storage of payment details for future use. By default, it’s set
to
False
.
To enable these features, a provider must override this method and set the appropriate fields.
class MyPaymentProvider(odoo.addons.payment.models.payment_provider.PaymentProvider):
def _compute_feature_support_fields(self):
self.support_express_checkout = True
self.support_manual_capture = True
self.support_refund = 'partial'
self.support_tokenization = True
Payment providers can also customize their form views using the _compute_view_configuration_fields
method. This method
manages whether specific elements are displayed in the provider's form view:
- Credentials Page: Determines if the “Credentials” page is shown.
- Allow Tokenization: Manages the visibility of the tokenization field.
- Allow Express Checkout: Controls whether the express checkout field is displayed.
- Pre-Authorization Message: Decides if the pre-authorization message field is shown.
- Pending Message: Indicates if the pending message field is displayed.
- Authorization Message: Manages the visibility of the authorization message field.
- Completion Message: Controls whether the completion message field is shown.
- Cancellation Message: Determines if the cancellation message field is displayed.
- Require Currency: Specifies whether the currency selection is mandatory.
By overriding this method, a provider can hide these elements by setting the respective fields to False
.
class MyPaymentProvider(odoo.addons.payment.models.payment_provider.PaymentProvider):
def _compute_view_configuration_fields(self):
self.show_credentials_page = False
self.show_allow_tokenization = True
self.show_allow_express_checkout = False
self.show_pre_msg = False
self.show_pending_msg = True
self.show_auth_msg = True
self.show_done_msg = False
self.show_cancel_msg = True
self.require_currency = True
The _get_compatible_providers
method is crucial for finding payment providers that meet specific criteria:
- Company ID: Providers must belong to the specified company.
- Partner ID: The ID of the partner making the payment.
- Amount: The amount to be paid.
- Currency ID: The currency for the payment.
- Force Tokenization: Indicates if only providers supporting tokenization should be considered.
- Express Checkout: Determines if the payment uses express checkout.
- Validation: Specifies if the operation is a validation.
This method returns the providers that match these criteria, ensuring a seamless and efficient payment process.
The _get_redirect_form_view
method decides which template to use for redirect forms, particularly useful for
distinguishing between validation and other transactions. Providers can override this method to return the appropriate
view based on the is_validation
parameter.
class MyPaymentProvider(odoo.addons.payment.models.payment_provider.PaymentProvider):
def _get_redirect_form_view(self, is_validation=False):
self.ensure_one()
if is_validation:
return self.env.ref('my_module.view_redirect_validation_form')
else:
return self.env.ref('my_module.view_redirect_payment_form')
Several methods help manage validation operations:
- Validation Amount:
_get_validation_amount
returns the amount used for validation.
class MyPaymentProvider(odoo.addons.payment.models.payment_provider.PaymentProvider):
def get_validation_amount(self):
return 5.0 # Montant utilisé pour la validation des paiements
# Exemple d'utilisation
provider = PaymentProvider()
validation_amount = provider.get_validation_amount() # Cela retourne 5.0
- Validation Currency:
_get_validation_currency
returns the currency used for validation.
class MyPaymentProvider(odoo.addons.payment.models.payment_provider.PaymentProvider):
def _get_validation_currency(self, payment_method='JPY'):
supported_currencies = ['EUR', 'USD']
if payment_method in supported_currencies:
return payment_method
else:
return 'EUR' # Devise par défaut de l'entreprise
- Tokenization Requirement:
_is_tokenization_required
indicates if tokenization is necessary based on the payment context.
Providers can override these methods to specify their requirements for validation operations.
The _should_build_inline_form
method decides if an inline payment form should be created based on whether the
operation is a validation.
class MyPaymentProvider(odoo.addons.payment.models.payment_provider.PaymentProvider):
def _should_build_inline_form(self, is_validation=False):
if is_validation:
return False # Pas de formulaire intégré pour les validations
else:
return True # Formulaire intégré pour les paiements directs
The _get_removal_values
method returns values to update a provider when its module is uninstalled, ensuring a smooth
removal process.
class MyPaymentProvider(odoo.addons.payment.models.payment_provider.PaymentProvider):
def _get_removal_values(self):
# Valeurs spécifiques pour la désinstallation
return {
'api_key': '',
'security_token': '',
'config_setting_1': 'default_value'
}
Payment providers in Odoo 17 are designed to handle various aspects of the payment process
, from supporting express
checkout to managing refunds and tokenization.
By understanding and utilizing these methods and fields, developers can ensure their payment processes are secure, efficient, and tailored to meet specific business needs.
This mastery enables the creation of robust payment
solutions within the Odoo ecosystem, enhancing the overall user
experience. 🚀
In our journey through Odoo 17, we now focus on Payment Tokens
, a critical aspect of ensuring secure and seamless
transactions. These tokens handle sensitive payment information, allowing for efficient and safe payment processes.
The _get_available_tokens
method is essential for finding tokens linked to specific providers and partners. To
retrieve these tokens, a module must override this method, providing necessary context through kwargs
.
- Providers IDs: List of IDs for the transaction's available providers.
- Partner ID: ID of the partner involved.
- Validation Flag: Boolean indicating if the transaction is for validation.
- Additional Parameters: Other keyword arguments for additional context.
This method returns the available tokens, ensuring relevant tokens are considered for each transaction.
Creating user-friendly names for tokens is crucial for clear display on interfaces. The _build_display_name
method
constructs these names to be concise and informative.
- Arguments: Passed by QWeb when calling the method.
- Max Length: Default set to 34, fitting the largest IBANs.
- Padding: Determines if the name includes padding characters.
- Additional Data: Optional data for further customization.
The method formats names like "•••• 1234", ensuring they fit within the specified length and adding padding as needed.
When creating tokens, it's often necessary to include provider-specific details. The _get_specific_create_values
method enhances token creation by adding these details.
- Provider Code: Unique code of the token’s managing provider.
- Original Values: Initial values for token creation.
This method returns a dictionary that combines generic and provider-specific information, ensuring tokens are created with all required details.
class MyPaymentProvider(odoo.addons.payment.models.payment_token.PaymentToken):
def _get_specific_create_values(self, provider_code, values):
# Ajouter des valeurs spécifiques au fournisseur
return {
"token_id": "efgh5678",
"paypal_api_key": "abc123"
}
Tokens may need to be archived over time. The _handle_archiving
method manages this process.
Modules can override this method to perform additional operations during archiving, ensuring secure storage or disposal of tokens.
class MyPaymentProvider(odoo.addons.payment.models.payment_token.PaymentToken):
def _handle_archiving(self):
# Supprimer des données liées au token
self.env['my_custom_data'].search([('token_id', '=', self.id)]).unlink()
# Envoyer une notification à l'utilisateur
# ...
Tokens often link to specific records like subscriptions or invoices. The get_linked_records_info
method returns
information about these linked records.
- Description: Description of the record’s model (e.g., "Subscription").
- ID: ID of the linked record.
- Name: Name of the linked record.
- URL: URL to access the record.
Overriding this method allows modules to provide detailed information about documents linked to a token, aiding users in tracking and managing their transactions effectively.
class PaymentToken(odoo.addons.payment.models.payment_token.PaymentToken):
def get_linked_records_info(self):
self.ensure_one()
linked_records = []
# Supposons que nous ayons une relation entre le jeton de paiement et les factures
invoices = self.env['account.move'].search([('payment_token_id', '=', self.id)])
for invoice in invoices:
record_info = {
"description": "Invoice",
"id": invoice.id,
"name": invoice.name,
"url": f"/web#id={invoice.id}&model=account.move&view_type=form"
}
linked_records.append(record_info)
return linked_records
In Odoo 17, Payment Tokens
are vital for secure and efficient transactions.
By understanding and using methods like _get_available_tokens
, _build_display_name
,
and _get_specific_create_values
, developers can ensure tokens are managed effectively.
This enhances the payment experience, contributing to a secure and reliable payment system within Odoo. 🚀
Continuing our journey through Odoo 17, we dive into the mechanics of Payment Transactions
, a crucial aspect of
handling financial operations.
These transactions form the backbone of payment systems
, ensuring every financial action is recorded, processed, and
tracked accurately.
In Odoo, each transaction needs a unique identifier
, known as a reference
.
The _compute_reference
method generates these references by combining a prefix, a separator, and a sequence number.
If no custom prefix is provided, Odoo generates one using _compute_reference_prefix
, which may include transaction
details like invoice IDs.
class MyPaymentProvider(odoo.addons.payment.models.payment_transaction.PaymentTransaction):
def _compute_reference_prefix(self, provider_code, separator, values):
# Ensure we are in sudo mode to access all necessary documents
self = self.sudo()
invoice_number = self.env['account.move'].browse(values['invoice_ids'][0]).name
return f"INV-{invoice_number}"
This meticulous process guarantees that every transaction is uniquely identifiable, even if multiple transactions share similar details.
After a transaction, it’s essential to summarize and display its status clearly. The _get_post_processing_values
method collects relevant data, such as the provider’s name, the transaction amount, and its current state (e.g.,
pending, done, or canceled).
{
'provider_code': 'PayPal',
'provider_name': 'PayPal',
'reference': 'PAY123456',
'amount': 100,
'currency_id': 1, # Supposons que 1 corresponde à USD
'state': 'done',
'state_message': 'Payment completed successfully.',
'operation': 'payment',
'is_post_processed': True,
'landing_route': '/thank_you'
}
Providers can customize
this data, ensuring that users receive the most accurate and relevant information. This
transparency helps in managing transactions effectively and addressing any issues that might arise.
Transactions often require specific details based on the provider’s requirements. The
methods _get_specific_create_values
, _get_specific_processing_values
, and _get_specific_rendering_values
allow for
this customization.
These methods can be overridden to add provider-specific information, ensuring that each transaction is processed with the necessary details, whether it’s during creation, processing, or displaying the payment form.
class MyPaymentProvider(odoo.addons.payment.models.payment_transaction.PaymentTransaction):
def _get_specific_processing_values(self, processing_values):
# Ajouter des valeurs spécifiques au fournisseur
return {
'amount': 100,
'currency': 'USD',
'stripe_api_key': 'sk_test_123',
'stripe_customer_id': 'cus_ABC123'
}
Payment transactions often involve communication
between Odoo and external providers. The _handle_notification_data
and _process_notification_data
methods handle these notifications, ensuring the transaction status
is updated
correctly.
These methods match
incoming data
with the corresponding transaction
, updating its state
to reflect changes like
payment confirmation, refunds, or errors.
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
def _handle_notification_data(self, provider_code, notification_data):
# Find the transaction based on notification data
transaction = self._get_tx_from_notification_data(provider_code, notification_data)
# If transaction is found, update its state
if transaction:
# Example of updating the state based on notification data
status = notification_data.get('status')
if status == 'completed':
transaction.state = 'done'
elif status == 'pending':
transaction.state = 'pending'
elif status == 'failed':
transaction.state = 'error'
else:
transaction.state = 'error'
# Optionally, update other fields based on notification data
transaction.amount = notification_data.get('amount', transaction.amount)
transaction.reference = notification_data.get('transaction_id', transaction.reference)
# Save the changes to the database
transaction._cr.commit()
return transaction
This robust system ensures that transactions are always in sync
with real-world events.
Transactions can involve various operations, such as capturing payments, issuing refunds, or voiding payments. The
methods _send_capture_request
, _send_refund_request
, and _send_void_request
facilitate these actions by sending
the necessary API requests to the provider.
transaction = self.env['payment.transaction'].browse(1)
# capturing payments
capture_transaction = transaction._send_capture_request(amount_to_capture=50)
# issuing refunds
refund_transaction = transaction._send_refund_request(amount_to_refund=50)
# voiding payments
void_transaction = transaction._send_void_request(amount_to_void=50)
These methods ensure that the financial operations
are executed correctly, whether capturing funds from a customer,
returning money, or canceling a transaction.
Throughout their lifecycle, transactions go through different states, like pending, authorized, or canceled.
Methods such as _set_authorized
, _set_done
, _set_canceled
, _set_error
, and _set_pending
manage these
transitions.
transactions = self.env['payment.transaction'].browse([1, 2, 3])
# authorize transaction
transactions._set_authorized(state_message="Autorisation manuelle")
# Cancel transaction
transactions._set_canceled(state_message="Paiement annulé par le client")
These methods update
the transaction’s state
based on specific conditions, ensuring that each transaction reflects
its current status accurately.
In Odoo 17, managing Payment Transactions
involves a complex yet well-organized system of methods and processes.
By leveraging these tools, developers can ensure that transactions are accurately tracked, processed, and managed.
This chapter highlights the importance of maintaining a reliable and transparent payment system, which is crucial for building trust and efficiency in financial operations. 🚀