(2026年10月29日 追記:記事どおりに再現できるよう、必要なコードと手順を追加しました)
見積書をメールで届けたら、次は「受注が決まったので請求書を出す」場面です。Excelで見積書をコピーして請求書に書き換える運用は、金額の転記ミスや二重発行の原因になりがちです。この第7回では、Ruby on Rails 8で作っている見積・請求管理システムに、受注済みの見積書から請求書を自動で作る機能を入れます。
前回の第6回:見積書をメールで送るでは、メール送信を裏側に回しました。今回は見積書の「状態」を管理し、請求書をデータとして持つところまでを作ります。
「見積書を請求書にするとき、Excelで書き写していて金額が合わなくなったり、同じ請求書を2回出してしまったりして困る」
先に結論です。見積書に「見積中→受注→請求書発行済み」という状態を持たせ、順番どおりにしか進めない作りにします。 請求書は見積書の明細を「写して」別のデータとして保存します。こうすると、二重発行を防げて、発行後に見積書やマスタを直しても過去の請求書の金額が変わりません。
この記事では、状態遷移(=状態が決まった順番でだけ変わる仕組み)の実装、請求番号の付け方、インボイス制度(適格請求書)の記載事項への対応、自動テストまでを、実際に動かしたコードで解説します。
請求書を「見積書の書き換え」で済ませてはいけない理由
見積書の画面に「請求書として表示」ボタンを付けるだけなら簡単です。しかし、見積書そのものを請求書として使い回すと、次の問題が起きます。
| 方式 | 動き | 起きやすい問題 |
|---|---|---|
| 見積書を使い回す | 同じデータを見せ方だけ変える | 受注後に見積書を直すと、発行済みの請求書の金額も変わってしまう。請求日・支払期日・請求番号を持てない |
| 請求書を別データとして作る(※今回採用) | 受注時点の明細を写して、請求書を新しく保存する | 「写す」処理と「二重に作らない」仕組みが要る |
請求書は取引先に渡し、会計や税務の記録にも使う書類です。発行した内容があとから変わらないことが大切なので、別データにして固定します。
仕組み:見積書の状態は一方通行で進める
見積書に状態を持たせ、次の順にだけ進められるようにします。
- 見積中(quoted):作成直後。取引先に見積書を送っている段階
- 受注(ordered):取引先から発注の返事をもらった状態
- 請求書発行済み(invoiced):請求書を作った状態。ここで終わり
「見積中のものだけ受注にできる」「受注済みのものだけ請求書にできる」と決めておくと、請求書の二重発行や、見積中の見積書から請求書ができてしまう事故を、画面の操作ミスがあっても防げます。
Railsでは enum(=決まった選択肢のどれか1つを持つ項目を作る機能)で状態を表せます。
📰 出典:Rails API「ActiveRecord::Enum」
公式ドキュメントでは、enumは選択肢に対応する値を持つ項目を宣言し、ordered? のような確認用のメソッドや invoiced! のような更新用のメソッドを自動で用意する仕組みとされています。
実装1:データベースに状態と請求書の置き場所を作る
まず、マイグレーション・モデル・コントローラーの雛形を生成します。請求明細のテーブルは、請求書と同じマイグレーションで作るので --no-migration を付けます。マイグレーションのファイル名の数字は実行した日時になるので、記事のファイル名と読み替えてください。
bin/rails generate migration AddStatusToEstimates status:string ordered_at:datetime
bin/rails generate model Invoice estimate:references customer:references number:string:uniq title:string \
issued_on:date due_on:date issuer_name:string registration_number:string note:text --no-test-framework
bin/rails generate model InvoiceLine invoice:references position:integer name:string unit:string \
quantity:integer unit_price:integer tax_rate:integer --no-migration --no-test-framework
bin/rails generate controller Invoices index show --skip-routes --no-helper --no-test-framework
見積書に状態と受注日時の列を足します。生成された db/migrate/20261005100000_add_status_to_estimates.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/db/migrate/20261005100000_add_status_to_estimates.rb
+++ b/db/migrate/20261005100000_add_status_to_estimates.rb
@@ -1,6 +1,7 @@
class AddStatusToEstimates < ActiveRecord::Migration[8.1]
def change
- add_column :estimates, :status, :string
+ # quoted(見積中)→ ordered(受注)→ invoiced(請求書発行済み)
+ add_column :estimates, :status, :string, null: false, default: "quoted"
add_column :estimates, :ordered_at, :datetime
end
end
次に請求書と請求明細のテーブルです。生成された db/migrate/20261005100100_create_invoices.rb に次の変更を加えます(+ が追加、- が削除)。終わったら bin/rails db:migrate を実行します。
--- a/db/migrate/20261005100100_create_invoices.rb
+++ b/db/migrate/20261005100100_create_invoices.rb
@@ -1,18 +1,29 @@
class CreateInvoices < ActiveRecord::Migration[8.1]
def change
create_table :invoices do |t|
- t.references :estimate, null: false, foreign_key: true
+ t.references :estimate, null: false, foreign_key: true, index: { unique: true } # 1つの見積書から請求書は1通だけ
t.references :customer, null: false, foreign_key: true
t.string :number
- t.string :title
- t.date :issued_on
- t.date :due_on
- t.string :issuer_name
- t.string :registration_number
+ t.string :title, null: false
+ t.date :issued_on, null: false
+ t.date :due_on, null: false
+ # 発行時点の発行事業者名と登録番号を請求書に写す(あとで会社情報を変えても過去の請求書は変わらない)
+ t.string :issuer_name, null: false
+ t.string :registration_number, null: false
t.text :note
-
t.timestamps
end
add_index :invoices, :number, unique: true
+
+ create_table :invoice_lines do |t|
+ t.references :invoice, null: false, foreign_key: true
+ t.integer :position, null: false, default: 0
+ t.string :name, null: false
+ t.string :unit
+ t.integer :quantity, null: false, default: 1
+ t.integer :unit_price, null: false, default: 0
+ t.integer :tax_rate, null: false, default: 10
+ t.timestamps
+ end
end
end
ポイントは2つあります。
estimate_idに一意(ユニーク)制約を付けています。アプリ側の確認をすり抜けても、データベースが「同じ見積書から2通目の請求書」を拒否します- 発行事業者名と登録番号は、請求書の側に写して保存します。会社名や登録番号を後で変更しても、過去の請求書は発行時のままになります
請求明細(invoice_lines)は、見積明細と同じ項目(品名・数量・単価・税率)を持つ別テーブルです。
実装2:状態を進めるメソッドを、モデルに書く
状態を進める処理は、画面(コントローラー)ではなくモデルに書きます。ルールをモデルに集めておくと、画面が増えても、テストでも同じルールが守られるからです。app/models/estimate.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/models/estimate.rb
+++ b/app/models/estimate.rb
@@ -4,6 +4,13 @@ class Estimate < ApplicationRecord
has_many :lines, -> { order(:position, :id) }, class_name: "EstimateLine", dependent: :destroy, inverse_of: :estimate
accepts_nested_attributes_for :lines, allow_destroy: true, reject_if: ->(attrs) { attrs["name"].blank? }
+ has_one :invoice, dependent: :restrict_with_error
+
+ # quoted: 見積中 / ordered: 受注 / invoiced: 請求書発行済み(順番どおりにしか進めない)
+ enum :status, { quoted: "quoted", ordered: "ordered", invoiced: "invoiced" }, default: :quoted
+
+ class InvalidTransition < StandardError; end
+
validates :title, presence: true, length: { maximum: 100 }
validates :issued_on, presence: true
validates :valid_until, comparison: { greater_than_or_equal_to: :issued_on }, allow_blank: true, if: :issued_on
@@ -18,6 +25,31 @@ class Estimate < ApplicationRecord
delegate :subtotal, :tax, :total, to: :tax_calculator
+ # 受注にする。見積中のものだけ。同時に2回押されても二重に進めないよう、行をロックして状態を読み直す
+ def place_order!(at: Time.current)
+ with_lock do
+ raise InvalidTransition, "見積中の見積書だけを受注にできます(現在: #{status_label})" unless quoted?
+ update!(status: :ordered, ordered_at: at)
+ end
+ end
+
+ # 受注済みの見積書から請求書を作る。見積書の状態更新と請求書の作成は、1つのトランザクションで行う
+ def issue_invoice!(issued_on: Date.current, due_on: nil, registration_number: Invoice.registration_number_from_env)
+ with_lock do
+ raise InvalidTransition, "受注済みの見積書だけ請求書にできます(現在: #{status_label})" unless ordered?
+ create_invoice!(
+ customer: customer, title: title, note: note,
+ issued_on: issued_on, due_on: due_on || issued_on.next_month.end_of_month, # 既定は翌月末払い
+ issuer_name: Invoice.issuer_name_from_env, registration_number: registration_number,
+ lines: lines.map { |l| InvoiceLine.new(l.slice(:position, :name, :unit, :quantity, :unit_price, :tax_rate)) }
+ )
+ invoiced!
+ invoice
+ end
+ end
+
+ def status_label = I18n.t("activerecord.attributes.estimate/status.#{status}")
+
private
def active_lines = lines.reject(&:marked_for_destruction?)
with_lock は、その見積書の行をデータベース上でロック(=処理が終わるまで他の人が同時に触れないようにする)して、最新の状態を読み直してから中の処理を実行します。
📰 出典:Rails API「ActiveRecord::Locking::Pessimistic」
公式ドキュメントでは、with_lock はトランザクションを開始し、レコードをロックして読み込み直したうえでブロックを実行するものと説明されています。ボタンの二度押しや、2人が同時に操作したときに、二重に請求書ができる事故を防ぐ用途に向いています。
請求書を作るのは、上の差分の issue_invoice! です。
- 見積書の明細を
InvoiceLineにコピーして請求書に持たせています - 請求書の作成と、見積書の状態を「請求書発行済み」にする更新は、
with_lockのトランザクションの中で行います。途中で失敗したら、どちらも元に戻ります - 支払期日の既定は「発行日の翌月末」としています。実際の締め日・支払条件は取引先ごとに違うため、サンプルでは引数で変えられるようにしてあります(画面からの指定は未実装)
- 発行事業者名と登録番号は環境変数(
ISSUER_NAME、INVOICE_REGISTRATION_NUMBER)から読み、コードに実値を書きません
実装3:請求番号は保存後のIDから作る
請求番号は、見積番号(Q-00012)と同じ考え方で、保存後のIDから作ります(assign_number)。請求書のモデルには、明細・合計の計算・登録番号の確認もまとめて書きます。生成された app/models/invoice.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/models/invoice.rb
+++ b/app/models/invoice.rb
@@ -1,4 +1,30 @@
+# 請求書。見積書の明細を「写して」持つ(品目マスタや見積書があとで変わっても、発行済みの請求書は変わらない)。
class Invoice < ApplicationRecord
+ # インボイス制度の登録番号は「T」+13桁の数字
+ REGISTRATION_NUMBER_FORMAT = /\AT\d{13}\z/
+
belongs_to :estimate
belongs_to :customer
+ has_many :lines, -> { order(:position, :id) }, class_name: "InvoiceLine", dependent: :destroy, inverse_of: :invoice
+
+ validates :title, :issuer_name, presence: true
+ validates :issued_on, :due_on, presence: true
+ validates :due_on, comparison: { greater_than_or_equal_to: :issued_on }, if: -> { issued_on && due_on }
+ validates :registration_number, format: { with: REGISTRATION_NUMBER_FORMAT }
+
+ after_create :assign_number
+
+ def tax_calculator = TaxCalculator.new(lines)
+
+ delegate :subtotal, :tax, :total, to: :tax_calculator
+
+ # 発行事業者名・登録番号は環境変数から読む(コードに書かない)
+ def self.issuer_name_from_env = ENV.fetch("ISSUER_NAME", "株式会社サンプル")
+ def self.registration_number_from_env = ENV.fetch("INVOICE_REGISTRATION_NUMBER", "T0000000000000")
+
+ private
+ # 請求番号は保存後のIDから作る(例: INV-00012)。重複しない
+ def assign_number
+ update_column(:number, format("INV-%05d", id))
+ end
end
請求明細の app/models/invoice_line.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/models/invoice_line.rb
+++ b/app/models/invoice_line.rb
@@ -1,3 +1,6 @@
class InvoiceLine < ApplicationRecord
belongs_to :invoice
+
+ # 金額(税抜)= 数量 × 単価
+ def amount = quantity * unit_price
end
number には一意制約を付けてあるので、重複はありません。ただし、IDは作成に失敗した分も進むことがあり、番号が飛ぶ(欠番が出る)ことがあります。インボイス制度では、請求書番号は「連番であること」が条件ではなく、後から探しやすい一意の番号であればよいとされています。厳密に連番にしたい場合は、年ごとの採番テーブルを作るなどの工夫が必要で、本連載では扱いません。
実装4:インボイス(適格請求書)の記載事項を満たす
インボイス制度の請求書に必要な記載事項は、国税庁の資料で次のように整理されています。
📰 出典:国税庁「インボイス制度の概要」
国税庁の説明では、インボイスには、交付を受ける相手方の氏名又は名称、売手の氏名又は名称及び登録番号、取引年月日、取引内容(軽減税率の対象品目である旨)、10%・8%それぞれの対価の額及び適用税率、10%・8%それぞれの消費税額等を記載するとされています。登録番号は「T」から始まる13桁の数字です。
これをサンプルの請求書にどう対応させたかを表にします。
| 記載事項 | サンプルでの対応 |
|---|---|
| 相手方の名称 | 請求先として取引先名を表示(customer.name) |
| 売手の名称と登録番号 | issuer_name と registration_number を請求書に保存して表示 |
| 取引年月日 | 発行日(issued_on)で代用(※下記の注意を参照) |
| 取引内容(軽減税率の対象である旨) | 税率8%の品目に「※」を付け、「※は軽減税率の対象品目です」と注記 |
| 税率ごとの税抜金額・適用税率 | 第4回で作った TaxCalculator の税率ごとの集計をそのまま表示 |
| 税率ごとの消費税額 | 同上。税率ごとに1回だけ端数処理した結果 |
登録番号の形式は、モデルで検証します(上の app/models/invoice.rb の REGISTRATION_NUMBER_FORMAT と validates :registration_number)。
形式が正しくなければ請求書は保存されず、見積書の状態も「受注」のまま残ります(自動テストで確認しています)。なお、これは形式の確認だけで、番号が本当に登録されているかの確認(国税庁の公表サイトとの照合)は行いません。
請求書の画面側では、軽減税率の品目に「※」を付けます。生成された詳細画面を、記載事項を並べた画面に直します。app/views/invoices/show.html.erb に次の変更を加えます(+ が追加、- が削除)。
app/views/invoices/show.html.erb の差分(54行)
--- a/app/views/invoices/show.html.erb
+++ b/app/views/invoices/show.html.erb
@@ -1,2 +1,49 @@
-<h1>Invoices#show</h1>
-<p>Find me in app/views/invoices/show.html.erb</p>
+<% content_for :title, @invoice.number %>
+<h1>請求書:<%= @invoice.title %></h1>
+
+<%# インボイス(適格請求書)の記載事項: 発行事業者の名称と登録番号/取引年月日/取引内容(軽減税率の対象は明示)/税率ごとの税抜金額・適用税率・消費税額/交付先の名称 %>
+<dl>
+ <dt><%= Invoice.human_attribute_name(:number) %></dt><dd><%= @invoice.number %></dd>
+ <dt>請求先</dt><dd><%= @invoice.customer.name %> 御中</dd>
+ <dt><%= Invoice.human_attribute_name(:issuer_name) %></dt><dd><%= @invoice.issuer_name %></dd>
+ <dt><%= Invoice.human_attribute_name(:registration_number) %></dt><dd><%= @invoice.registration_number %></dd>
+ <dt><%= Invoice.human_attribute_name(:issued_on) %></dt><dd><%= @invoice.issued_on.strftime("%Y/%m/%d") %></dd>
+ <dt><%= Invoice.human_attribute_name(:due_on) %></dt><dd><%= @invoice.due_on.strftime("%Y/%m/%d") %></dd>
+</dl>
+
+<table>
+ <thead>
+ <tr><th>品名</th><th class="num">数量</th><th>単位</th><th class="num">単価</th><th>税率</th><th class="num">金額(税抜)</th></tr>
+ </thead>
+ <tbody>
+ <% @invoice.lines.each do |line| %>
+ <tr>
+ <%# 軽減税率(8%)の対象品目には「※」を付け、下の注記で意味を示す %>
+ <td><%= line.name %><%= "※" if line.tax_rate == 8 %></td>
+ <td class="num"><%= line.quantity %></td>
+ <td><%= line.unit %></td>
+ <td class="num"><%= number_with_delimiter(line.unit_price) %></td>
+ <td><%= line.tax_rate %>%</td>
+ <td class="num"><%= number_with_delimiter(line.amount) %></td>
+ </tr>
+ <% end %>
+ </tbody>
+ <tfoot>
+ <% calc = @invoice.tax_calculator %>
+ <% calc.groups.each do |group| %>
+ <tr class="tax-group">
+ <th colspan="5" class="num"><%= group.rate %>%対象(税抜 <%= number_with_delimiter(group.subtotal) %>円)の消費税</th>
+ <td class="num"><%= number_with_delimiter(group.tax) %>円</td>
+ </tr>
+ <% end %>
+ <tr class="grand-total"><th colspan="5" class="num">ご請求額(税込)</th><td class="num"><%= number_with_delimiter(calc.total) %>円</td></tr>
+ </tfoot>
+</table>
+<% if @invoice.lines.any? { |l| l.tax_rate == 8 } %><p class="muted">※ は軽減税率(8%)の対象品目です。</p><% end %>
+
+<% if @invoice.note.present? %><p><%= simple_format(h(@invoice.note)) %></p><% end %>
+
+<div class="actions">
+ <%= link_to "元の見積書 #{@invoice.estimate.number}", @invoice.estimate %>
+ <%= link_to "一覧へ戻る", invoices_path %>
+</div>
請求書の一覧も作ります。app/views/invoices/index.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/invoices/index.html.erb
+++ b/app/views/invoices/index.html.erb
@@ -1,2 +1,22 @@
-<h1>Invoices#index</h1>
-<p>Find me in app/views/invoices/index.html.erb</p>
+<% content_for :title, "請求書一覧" %>
+
+<h1>請求書</h1>
+
+<table>
+ <thead>
+ <tr><th>請求番号</th><th>件名</th><th>取引先</th><th>発行日</th><th>支払期日</th><th class="num">請求額(税込)</th></tr>
+ </thead>
+ <tbody>
+ <% @invoices.each do |invoice| %>
+ <tr>
+ <td><%= link_to invoice.number, invoice %></td>
+ <td><%= invoice.title %></td>
+ <td><%= invoice.customer.name %></td>
+ <td><%= invoice.issued_on.strftime("%Y/%m/%d") %></td>
+ <td><%= invoice.due_on.strftime("%Y/%m/%d") %></td>
+ <td class="num"><%= number_with_delimiter(invoice.total) %>円</td>
+ </tr>
+ <% end %>
+ </tbody>
+</table>
+<% if @invoices.empty? %><p class="muted">請求書はまだありません。</p><% end %>
注意: 取引年月日が発行日と異なる(納品日と請求日が違う、月末にまとめて請求するなど)場合は、取引年月日の列を別に持つ必要があります。サンプルでは簡略化のため発行日で代用しています。税務上の要件の最終的な判断は、顧問税理士や国税庁の最新の案内で確認してください。
実装5:画面とルーティング
画面の操作は2つのボタンだけです。見積中なら「受注にする」、受注済みなら「請求書を発行する」を出し、状態も表示します。app/views/estimates/show.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/estimates/show.html.erb
+++ b/app/views/estimates/show.html.erb
@@ -4,6 +4,7 @@
<dl>
<dt><%= Estimate.human_attribute_name(:number) %></dt><dd><%= @estimate.number %></dd>
<dt><%= Estimate.human_attribute_name(:customer_id) %></dt><dd><%= link_to @estimate.customer.name, @estimate.customer %></dd>
+ <dt><%= Estimate.human_attribute_name(:status) %></dt><dd><%= @estimate.status_label %></dd>
<dt><%= Estimate.human_attribute_name(:issued_on) %></dt><dd><%= @estimate.issued_on.strftime("%Y/%m/%d") %></dd>
<dt><%= Estimate.human_attribute_name(:valid_until) %></dt><dd><%= @estimate.valid_until&.strftime("%Y/%m/%d") || "—" %></dd>
</dl>
@@ -52,6 +53,15 @@
<% end %>
<% end %>
+<% if Current.user.can_edit? %>
+ <% if @estimate.quoted? %>
+ <%= button_to "受注にする", order_estimate_path(@estimate), form: { data: { turbo_confirm: "この見積書を受注にしますか?" } } %>
+ <% elsif @estimate.ordered? %>
+ <%= button_to "請求書を発行する", estimate_invoice_path(@estimate), form: { data: { turbo_confirm: "請求書を発行しますか?(発行後は取り消せません)" } } %>
+ <% end %>
+<% end %>
+<% if @estimate.invoice %><p><%= link_to "請求書 #{@estimate.invoice.number} を見る", @estimate.invoice %></p><% end %>
+
<div class="actions">
<%= link_to "編集", edit_estimate_path(@estimate) if Current.user.can_edit? %>
<%= link_to "PDFをダウンロード", estimate_path(@estimate, format: :pdf) %>
一覧にも状態の列を足します。app/views/estimates/index.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/estimates/index.html.erb
+++ b/app/views/estimates/index.html.erb
@@ -8,7 +8,7 @@
<table>
<thead>
- <tr><th>見積番号</th><th>件名</th><th>取引先</th><th>発行日</th><th class="num">合計(税込)</th></tr>
+ <tr><th>見積番号</th><th>件名</th><th>取引先</th><th>状態</th><th>発行日</th><th class="num">合計(税込)</th></tr>
</thead>
<tbody>
<% @estimates.each do |estimate| %>
@@ -16,6 +16,7 @@
<td><%= link_to estimate.number, estimate %></td>
<td><%= estimate.title %></td>
<td><%= estimate.customer.name %></td>
+ <td><%= estimate.status_label %></td>
<td><%= estimate.issued_on.strftime("%Y/%m/%d") %></td>
<td class="num"><%= number_with_delimiter(estimate.total) %>円</td>
</tr>
ログイン済みでも、閲覧のみの権限の人にはボタン自体を出さず、サーバー側(コントローラー)でも権限を確認します(第2回の仕組み)。画面で隠すだけでは、URLを直接叩かれたときに防げないためです。
ルーティングは次の追加だけです。config/routes.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -17,5 +17,8 @@ Rails.application.routes.draw do
resources :items
resources :estimates do
post :deliver, on: :member
+ post :order, on: :member
+ resource :invoice, only: :create
end
+ resources :invoices, only: %i[ index show ]
end
請求書は「見積書から作る」ものなので、作成は見積書の下のURLにし、請求書の一覧・詳細だけを独立させています。コントローラーは、モデルのメソッドを呼んで、ルール違反の例外を画面のメッセージに変えるだけです。生成された app/controllers/invoices_controller.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/controllers/invoices_controller.rb
+++ b/app/controllers/invoices_controller.rb
@@ -1,7 +1,25 @@
+# 請求書は見積書から作る(InvoicesController#create は /estimates/:estimate_id/invoice)。ここでは閲覧だけ。
class InvoicesController < ApplicationController
+ require_permission :can_edit?, only: :create
+ before_action :set_estimate, only: :create
+
def index
+ @invoices = Invoice.includes(:customer, :lines).order(issued_on: :desc, id: :desc)
end
def show
+ @invoice = Invoice.includes(:lines).find(params.expect(:id))
+ end
+
+ def create
+ invoice = @estimate.issue_invoice!
+ redirect_to invoice, notice: "請求書 #{invoice.number} を発行しました。", status: :see_other
+ rescue Estimate::InvalidTransition => e
+ redirect_to @estimate, alert: e.message, status: :see_other
end
+
+ private
+ def set_estimate
+ @estimate = Estimate.find(params.expect(:estimate_id))
+ end
end
「受注にする」は見積書のコントローラーに足します。app/controllers/estimates_controller.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/controllers/estimates_controller.rb
+++ b/app/controllers/estimates_controller.rb
@@ -1,7 +1,7 @@
class EstimatesController < ApplicationController
require_permission :can_edit?, except: %i[ index show ]
require_permission :can_destroy?, only: :destroy
- before_action :set_estimate, only: %i[ show edit update destroy deliver ]
+ before_action :set_estimate, only: %i[ show edit update destroy deliver order ]
def index
@estimates = Estimate.includes(:customer, :lines).order(issued_on: :desc, id: :desc)
@@ -56,6 +56,13 @@ class EstimatesController < ApplicationController
end
end
+ def order
+ @estimate.place_order!
+ redirect_to @estimate, notice: "受注にしました。請求書を発行できます。", status: :see_other
+ rescue Estimate::InvalidTransition => e
+ redirect_to @estimate, alert: e.message, status: :see_other
+ end
+
def destroy
@estimate.destroy!
redirect_to estimates_path, notice: "#{Estimate.model_name.human}を削除しました。", status: :see_other
取引先には請求書もつながるので、請求書がある取引先も削除できないようにします。あわせて、ヘッダーのメニューと項目名の日本語を足します。
app/models/customer.rb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/models/customer.rb
+++ b/app/models/customer.rb
@@ -1,6 +1,7 @@
class Customer < ApplicationRecord
# 見積書がある取引先は削除できない(見積の記録を残すため)
has_many :estimates, dependent: :restrict_with_error
+ has_many :invoices, dependent: :restrict_with_error
validates :name, presence: true, length: { maximum: 100 }
validates :postal_code, format: { with: /\A\d{3}-?\d{4}\z/ }, allow_blank: true
app/views/layouts/application.html.erb に次の変更を加えます(+ が追加、- が削除)。
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -24,6 +24,7 @@
<%= link_to "取引先", customers_path %>
<%= link_to "品目", items_path %>
<%= link_to "見積書", estimates_path %>
+ <%= link_to "請求書", invoices_path %>
</nav>
<div class="account">
<%= Current.user.email_address %>(<%= User.human_attribute_name("role.#{Current.user.role}") %>)
config/locales/ja.yml に次の変更を加えます(+ が追加、- が削除)。
--- a/config/locales/ja.yml
+++ b/config/locales/ja.yml
@@ -5,6 +5,8 @@ ja:
item: 品目
estimate: 見積書
estimate_line: 見積明細
+ invoice: 請求書
+ invoice_line: 請求明細
attributes:
customer:
name: 取引先名
@@ -39,6 +41,19 @@ ja:
lines: 明細
sent_at: 送信日時
sent_to: 送信先
+ status: 状態
+ ordered_at: 受注日時
+ estimate/status:
+ quoted: 見積中
+ ordered: 受注
+ invoiced: 請求書発行済み
+ invoice:
+ number: 請求番号
+ title: 件名
+ issued_on: 発行日
+ due_on: 支払期日
+ registration_number: 登録番号
+ issuer_name: 発行事業者
estimate_line:
name: 品名
quantity: 数量
動作確認:自動テストで「やってはいけないこと」を固定する
状態遷移は、正しい操作が動くことより「やってはいけない操作が止まること」を確かめるのが大切です。テスト用に「受注済み」の見積書と明細を足します。test/fixtures/estimates.yml に次の変更を加えます(+ が追加、- が削除)。
--- a/test/fixtures/estimates.yml
+++ b/test/fixtures/estimates.yml
@@ -4,3 +4,11 @@ website:
title: コーポレートサイト制作
issued_on: 2026-10-01
valid_until: 2026-10-31
+
+ordered:
+ customer: sakura
+ number: Q-00002
+ title: 保守契約
+ issued_on: 2026-10-02
+ status: ordered
+ ordered_at: 2026-10-03 09:00:00
test/fixtures/estimate_lines.yml に次の変更を加えます(+ が追加、- が削除)。
--- a/test/fixtures/estimate_lines.yml
+++ b/test/fixtures/estimate_lines.yml
@@ -16,3 +16,12 @@ lunch:
quantity: 5
unit_price: 1000
tax_rate: 8
+
+maintenance:
+ estimate: ordered
+ position: 1
+ name: 月額保守費
+ unit: 月
+ quantity: 3
+ unit_price: 50000
+ tax_rate: 10
test/models/estimate_status_test.rb を新しく作ります。
# test/models/estimate_status_test.rb
require "test_helper"
class EstimateStatusTest < ActiveSupport::TestCase
test "見積中の見積書は受注にできる" do
estimate = estimates(:website)
estimate.place_order!(at: Time.zone.local(2026, 10, 5, 10))
assert estimate.reload.ordered?
assert_equal Time.zone.local(2026, 10, 5, 10), estimate.ordered_at
end
test "受注済みの見積書をもう一度受注にはできない" do
assert_raises(Estimate::InvalidTransition) { estimates(:ordered).place_order! }
end
test "見積中のままでは請求書にできない" do
assert_no_difference "Invoice.count" do
assert_raises(Estimate::InvalidTransition) { estimates(:website).issue_invoice! }
end
end
test "受注済みの見積書から、明細と金額が同じ請求書ができる" do
estimate = estimates(:ordered)
invoice = estimate.issue_invoice!(issued_on: Date.new(2026, 10, 5), registration_number: "T1234567890123")
assert estimate.reload.invoiced?
assert_match(/\AINV-\d{5}\z/, invoice.number)
assert_equal Date.new(2026, 11, 30), invoice.due_on # 既定は翌月末
assert_equal [ [ "月額保守費", 3, 50_000, 10 ] ], invoice.lines.map { |l| [ l.name, l.quantity, l.unit_price, l.tax_rate ] }
assert_equal estimate.total, invoice.total
assert_equal 165_000, invoice.total
end
test "請求書は二重に発行されない" do
estimate = estimates(:ordered)
estimate.issue_invoice!(registration_number: "T1234567890123")
assert_no_difference "Invoice.count" do
assert_raises(Estimate::InvalidTransition) { estimate.issue_invoice!(registration_number: "T1234567890123") }
end
end
test "発行後に見積書の明細を変えても、請求書は変わらない" do
estimate = estimates(:ordered)
invoice = estimate.issue_invoice!(registration_number: "T1234567890123")
estimate.lines.first.update!(unit_price: 1)
assert_equal 165_000, invoice.reload.total
end
test "登録番号の形式が正しくないと保存できない" do
assert_raises(ActiveRecord::RecordInvalid) { estimates(:ordered).issue_invoice!(registration_number: "1234567890123") }
assert estimates(:ordered).reload.ordered?, "失敗したら見積書の状態も元のまま"
end
end
コントローラーのテストでは、担当者が「受注にする→請求書を発行する」まで進められること、閲覧のみの人は受注にも発行にもできないことを確認します。test/controllers/invoices_controller_test.rb を新しく作ります。
# test/controllers/invoices_controller_test.rb
require "test_helper"
class InvoicesControllerTest < ActionDispatch::IntegrationTest
test "担当者は受注にして、請求書を発行できる" do
sign_in_as users(:staff)
estimate = estimates(:website)
post order_estimate_url(estimate)
assert estimate.reload.ordered?
assert_difference "Invoice.count", 1 do
post estimate_invoice_url(estimate)
end
assert_redirected_to invoice_url(estimate.invoice)
follow_redirect!
assert_select "dd", "T0000000000000"
assert_select "td", /打合せ用弁当※/
assert_select "tr.grand-total td", "335,400円"
end
test "見積中のまま請求書を発行しようとすると、見積書に戻って警告が出る" do
sign_in_as users(:staff)
assert_no_difference "Invoice.count" do
post estimate_invoice_url(estimates(:website))
end
assert_redirected_to estimate_url(estimates(:website))
assert_equal "受注済みの見積書だけ請求書にできます(現在: 見積中)", flash[:alert]
end
test "閲覧のみの人は受注にも請求書の発行にもできない" do
sign_in_as users(:viewer)
post order_estimate_url(estimates(:website))
assert estimates(:website).reload.quoted?
post estimate_invoice_url(estimates(:ordered))
assert_equal 0, Invoice.count
end
test "請求書の一覧と詳細を見られる" do
invoice = estimates(:ordered).issue_invoice!
sign_in_as users(:viewer)
get invoices_url
assert_select "td", invoice.number
get invoice_url(invoice)
assert_response :success
end
end
実行すると、既存のテストを含めて次の結果になりました(Ruby 3.3・Rails 8・PostgreSQL 16の開発環境)。
bin/rails test
# 78 runs, 231 assertions, 0 failures, 0 errors, 0 skips
コード整形のチェック(RuboCop)も指摘なしです。なお、この環境では請求書のPDF出力は作っていません。ブラウザで実際に画面を操作する確認も行っていないため、画面は自動テスト(HTMLの出力内容)で確認した範囲です。
つまずきやすい点・注意
- 発行済みの請求書を直したくなったとき:このサンプルは「発行後は変更しない」前提で、修正や取消の機能はありません。実務では、間違えた請求書を取り消して新しく出し直す(訂正の請求書を出す)運用が必要です。訂正の扱いは税務の要件が絡むため、顧問税理士に確認してください
- 同じ見積書を、部分的に請求したい場合:分割請求(着手金・中間金・残金など)には、この「1見積書につき1請求書」の作りでは足りません。請求書を複数持てるようデータの作りを変える必要があります
- 請求番号の連番:前述のとおり、欠番が出ます。会計ソフトの連携や社内ルールで連番が必須なら、最初に決めておきましょう
- 電子帳簿保存法:電子で作った請求書の保存には、別途要件があります。本連載では扱いません
発注者向けメモ:請求書機能を開発会社に頼むときの確認点
「請求書は『見積書の見た目違い』ではなく、税務の記録になる書類です。最初に決めておくことが意外と多いんです。」
発注者がやることチェックリスト
- 請求書の記載項目(登録番号、軽減税率の表記など)を、顧問税理士に確認してもらってから依頼する
- 請求のパターンを洗い出す(1回請求のみか、分割請求・月額請求・締め日ごとの請求があるか)
- 発行済みの請求書を間違えたときの手順(取消・訂正)を、業務として決めておく
- 請求番号のルール(連番が必要か、年度で区切るか)を決める
- 誰が受注を確定でき、誰が請求書を発行できるか(権限)を決める
- 会計ソフトに取り込みたい場合は、その形式を依頼前に伝える
開発会社への質問例
- 「請求書を発行した後に、見積書やマスタを直しても、発行済みの請求書の金額が変わらない作りになっていますか?」
- 「同じ請求書が二重に発行されないよう、データベース側でも防ぐ仕組みはありますか?」
- 「分割請求や月額請求に対応する場合、今の作りから追加でどのくらいの作業が増えますか?」
- 「請求書の取消・訂正は、どのような操作と記録の残し方になりますか?」
- 「インボイスの記載事項について、どの項目を、どの画面・帳票で満たしているか一覧で教えてもらえますか?」
請求書の機能は、画面の数が少なく見えても、パターン(分割・月額・訂正)が増えるほど作業が大きく変わる部分です。最初の相談で「請求のパターン」を伝えておくと、見積もりのズレを減らせます。
まとめと次回予告
この第7回では、見積書に状態(見積中→受注→請求書発行済み)を持たせ、受注済みの見積書から請求書を別データとして作る機能を入れました。ポイントは次の4つです。
- 状態は一方通行で進め、ルールは画面ではなくモデルに書く
with_lockと一意制約で、二重発行を2段構えで防ぐ- 請求書は見積書の明細を写して固定し、発行後に変わらないようにする
- インボイスの記載事項を請求書の項目に対応づけ、登録番号の形式を検証する
次の第8回では、入金管理と督促の一覧を作ります。請求書ごとの入金状況を記録し、支払期日を過ぎても入金されていない請求書を一覧で抜き出します。
この連載の記事一覧
この記事は連載「Railsで作る見積・請求管理システム」の1回です。連載のほかの回は次のとおりです(連載の一覧ページ)。
- 【Railsで作る見積・請求管理システム 第0回】Rails 8の雛形を動かして、Excel見積からの脱却を始める
- 【Railsで作る見積・請求管理システム 第1回】取引先と品目のマスタを作る(scaffoldと入力チェック)
- 【Railsで作る見積・請求管理システム 第2回】ログインを付ける(Rails 8標準の認証と権限の分け方)
- 【Railsで作る見積・請求管理システム 第3回】見積書と明細を作る(Hotwireで明細行をその場で追加)
- 【Railsで作る見積・請求管理システム 第4回】金額・消費税・端数処理を正しく計算する(税率ごとに1回だけ丸める)
- 【Railsで作る見積・請求管理システム 第5回】見積書をPDFで出力する(Prawnで日本語フォントを扱う)
- 【Railsで作る見積・請求管理システム 第6回】見積書をメールで送る(Solid Queueで送信を非同期にする)
- 【Railsで作る見積・請求管理システム 第7回】受注から請求書へ変換する(状態遷移と請求番号、インボイスの記載事項)(この記事)
- 【Railsで作る見積・請求管理システム 第8回】入金管理と督促の一覧を作る(一部入金・期限超過の抽出)
- 【Railsで作る見積・請求管理システム 第9回】Kamalでサーバーに配備する(Dockerイメージ・SSL・秘密情報・運用の注意)










コメント
コメント一覧 (2件)
[…] 第8回では、前回の記事で作った請求書に入金を記録し、期限を過ぎても入金がない請求書を一覧で抜き出す仕組みを、Ruby on Rails 8で作ります。前回は受注から請求書へ変換するところまで進めました。 […]
[…] 【Railsで作る見積・請求管理システム 第7回】受注から請求書へ変換する(… […]