lbyte-budget 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. checksums.yaml +7 -0
  2. data/.simplecov +25 -0
  3. data/API_DOCUMENTATION.md +526 -0
  4. data/CHANGELOG.md +5 -0
  5. data/CLEANUP.md +85 -0
  6. data/CODE_OF_CONDUCT.md +132 -0
  7. data/INTEGRATION_GUIDE.md +452 -0
  8. data/LICENSE.txt +21 -0
  9. data/RAILS_USAGE.md +510 -0
  10. data/README.md +367 -0
  11. data/Rakefile +19 -0
  12. data/TESTING.md +243 -0
  13. data/TEST_IMPLEMENTATION_SUMMARY.md +246 -0
  14. data/TEST_SUITE.md +253 -0
  15. data/app/controllers/budget/application_controller.rb +10 -0
  16. data/app/controllers/budget/line_items_controller.rb +112 -0
  17. data/app/controllers/budget/payments_controller.rb +108 -0
  18. data/app/controllers/budget/quotes_controller.rb +180 -0
  19. data/app/models/budget/line_item.rb +59 -0
  20. data/app/models/budget/payment.rb +58 -0
  21. data/app/models/budget/quote.rb +158 -0
  22. data/app/views/budget/line_items/index.json.jbuilder +7 -0
  23. data/app/views/budget/line_items/show.json.jbuilder +6 -0
  24. data/app/views/budget/payments/index.json.jbuilder +6 -0
  25. data/app/views/budget/payments/show.json.jbuilder +5 -0
  26. data/app/views/budget/quotes/index.json.jbuilder +15 -0
  27. data/app/views/budget/quotes/show.json.jbuilder +23 -0
  28. data/config/routes.rb +12 -0
  29. data/db/migrate/20251129000001_create_budget_quotes.rb +17 -0
  30. data/db/migrate/20251129000002_create_budget_line_items.rb +17 -0
  31. data/db/migrate/20251129000003_create_budget_payments.rb +18 -0
  32. data/examples/basic_usage.rb +130 -0
  33. data/examples/test_examples.rb +113 -0
  34. data/lib/budget/engine.rb +25 -0
  35. data/lib/budget/line_item.rb +66 -0
  36. data/lib/budget/payment.rb +56 -0
  37. data/lib/budget/quote.rb +163 -0
  38. data/lib/budget/version.rb +5 -0
  39. data/lib/budget.rb +10 -0
  40. data/lib/generators/budget/INSTALL +46 -0
  41. data/lib/generators/budget/install_generator.rb +33 -0
  42. data/sig/budget.rbs +4 -0
  43. metadata +115 -0
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
@@ -0,0 +1,452 @@
1
+ # Integration Guide: Linking Prescriptions with Budget Quotes
2
+
3
+ This guide explains how to integrate the Budget engine with your existing Rails application that has `Patient` and `Prescription` models.
4
+
5
+ ## Your Application Structure
6
+
7
+ ```
8
+ Patient (has_many) → Prescription (has_one) → Budget::Quote
9
+ ```
10
+
11
+ ## Step-by-Step Integration
12
+
13
+ ### Step 1: Add Foreign Key Migration
14
+
15
+ In your **main Rails application** (not in the engine), create a migration to add `prescription_id` to the `budget_quotes` table:
16
+
17
+ ```bash
18
+ rails generate migration AddPrescriptionToBudgetQuotes prescription:references
19
+ ```
20
+
21
+ This creates:
22
+
23
+ ```ruby
24
+ class AddPrescriptionToBudgetQuotes < ActiveRecord::Migration[7.0]
25
+ def change
26
+ add_reference :budget_quotes, :prescription, foreign_key: true, index: true
27
+ end
28
+ end
29
+ ```
30
+
31
+ Run the migration:
32
+
33
+ ```bash
34
+ rails db:migrate
35
+ ```
36
+
37
+ ### Step 2: Update Your Prescription Model
38
+
39
+ Add the relationship to your `Prescription` model:
40
+
41
+ ```ruby
42
+ # app/models/prescription.rb
43
+ class Prescription < ApplicationRecord
44
+ belongs_to :patient
45
+ has_one :quote, class_name: 'Budget::Quote', foreign_key: 'prescription_id', dependent: :destroy
46
+
47
+ # Optional: Automatically create a quote when a prescription is created
48
+ after_create :create_initial_quote
49
+
50
+ # Delegate common methods to the quote for convenience
51
+ delegate :total, :total_paid, :remaining_balance, :fully_paid?, to: :quote, allow_nil: true
52
+
53
+ private
54
+
55
+ def create_initial_quote
56
+ Budget::Quote.create!(
57
+ prescription_id: id,
58
+ customer_name: patient.full_name,
59
+ customer_contact: patient.phone || patient.email,
60
+ notes: "Prescription ##{id}"
61
+ )
62
+ end
63
+ end
64
+ ```
65
+
66
+ ### Step 3: Extend the Budget::Quote Model
67
+
68
+ In your **main application**, create a decorator or initializer to add the `belongs_to :prescription` association:
69
+
70
+ **Option A: Using a Decorator (Recommended)**
71
+
72
+ Create `app/models/budget/quote_decorator.rb`:
73
+
74
+ ```ruby
75
+ # app/models/budget/quote_decorator.rb
76
+ Budget::Quote.class_eval do
77
+ belongs_to :prescription, optional: true
78
+
79
+ # Add custom scopes or methods specific to your app
80
+ scope :for_patient, ->(patient_id) {
81
+ joins(:prescription).where(prescriptions: { patient_id: patient_id })
82
+ }
83
+
84
+ # Helper method to get the patient
85
+ def patient
86
+ prescription&.patient
87
+ end
88
+ end
89
+ ```
90
+
91
+ **Option B: Using an Initializer**
92
+
93
+ Create `config/initializers/budget.rb`:
94
+
95
+ ```ruby
96
+ # config/initializers/budget.rb
97
+ Rails.application.config.to_prepare do
98
+ Budget::Quote.class_eval do
99
+ belongs_to :prescription, optional: true
100
+
101
+ def patient
102
+ prescription&.patient
103
+ end
104
+ end
105
+ end
106
+ ```
107
+
108
+ ### Step 4: Update Your Patient Model
109
+
110
+ ```ruby
111
+ # app/models/patient.rb
112
+ class Patient < ApplicationRecord
113
+ has_many :prescriptions, dependent: :destroy
114
+ has_many :quotes, through: :prescriptions, class_name: 'Budget::Quote'
115
+
116
+ # Get all quotes for this patient
117
+ def all_quotes
118
+ Budget::Quote.joins(:prescription).where(prescriptions: { patient_id: id })
119
+ end
120
+
121
+ # Calculate total amount owed across all quotes
122
+ def total_outstanding
123
+ all_quotes.sum { |quote| quote.remaining_balance }
124
+ end
125
+ end
126
+ ```
127
+
128
+ ## Usage Examples
129
+
130
+ ### Creating a Prescription with Quote
131
+
132
+ ```ruby
133
+ # Create patient
134
+ patient = Patient.create!(
135
+ name: "María González",
136
+ email: "maria@example.com",
137
+ phone: "555-1234"
138
+ )
139
+
140
+ # Create prescription (automatically creates quote via callback)
141
+ prescription = patient.prescriptions.create!(
142
+ doctor: "Dr. Smith",
143
+ prescription_details: "OD: -2.00, OS: -1.75"
144
+ )
145
+
146
+ # Access the quote
147
+ quote = prescription.quote
148
+ # => #<Budget::Quote id: 1, customer_name: "María González", ...>
149
+
150
+ # Add line items to the quote
151
+ quote.add_line_item(
152
+ description: "Lentes progresivos",
153
+ price: 150.00,
154
+ category: :lente,
155
+ quantity: 1
156
+ )
157
+
158
+ quote.add_line_item(
159
+ description: "Montura premium",
160
+ price: 80.00,
161
+ category: :montura
162
+ )
163
+
164
+ # Record initial payment (adelanto)
165
+ quote.add_payment(
166
+ amount: 115.00,
167
+ payment_method: "efectivo",
168
+ notes: "Adelanto - 50%"
169
+ )
170
+
171
+ # Check status
172
+ puts quote.total # => 230.0
173
+ puts quote.total_paid # => 115.0
174
+ puts quote.remaining_balance # => 115.0
175
+ puts quote.fully_paid? # => false
176
+ ```
177
+
178
+ ### Working with API Endpoints
179
+
180
+ ```ruby
181
+ # In your controllers, you can pass prescription_id when creating quotes
182
+
183
+ # POST /budget/quotes
184
+ {
185
+ "quote": {
186
+ "prescription_id": 123,
187
+ "customer_name": "María González",
188
+ "customer_contact": "555-1234"
189
+ }
190
+ }
191
+
192
+ # Or create through prescription
193
+ prescription = Prescription.find(params[:id])
194
+ quote = prescription.create_quote!(
195
+ customer_name: prescription.patient.name,
196
+ customer_contact: prescription.patient.phone
197
+ )
198
+ ```
199
+
200
+ ### Querying Across Models
201
+
202
+ ```ruby
203
+ # Find all quotes for a specific patient
204
+ patient = Patient.find(1)
205
+ patient.quotes
206
+ # or
207
+ patient.all_quotes
208
+
209
+ # Find quote by prescription
210
+ prescription = Prescription.find(1)
211
+ quote = prescription.quote
212
+
213
+ # Find prescription from quote
214
+ quote = Budget::Quote.find(1)
215
+ prescription = quote.prescription
216
+ patient = quote.patient
217
+
218
+ # Get all pending quotes for a patient
219
+ patient.quotes.joins(:payments)
220
+ .group('budget_quotes.id')
221
+ .having('SUM(budget_payments.amount) < ?', patient.quotes.sum(&:total))
222
+ ```
223
+
224
+ ### Controller Example
225
+
226
+ ```ruby
227
+ # app/controllers/prescriptions_controller.rb
228
+ class PrescriptionsController < ApplicationController
229
+ def show
230
+ @prescription = Prescription.includes(quote: [:line_items, :payments]).find(params[:id])
231
+ @quote = @prescription.quote
232
+ end
233
+
234
+ def create
235
+ @prescription = current_patient.prescriptions.build(prescription_params)
236
+
237
+ if @prescription.save
238
+ # Quote is created automatically via callback
239
+ # Or create manually:
240
+ # @prescription.create_quote!(
241
+ # customer_name: current_patient.name,
242
+ # customer_contact: current_patient.phone
243
+ # )
244
+
245
+ redirect_to @prescription, notice: 'Prescription and quote created.'
246
+ else
247
+ render :new
248
+ end
249
+ end
250
+ end
251
+ ```
252
+
253
+ ### View Example
254
+
255
+ ```erb
256
+ <!-- app/views/prescriptions/show.html.erb -->
257
+ <h1>Prescription #<%= @prescription.id %></h1>
258
+
259
+ <h2>Patient Information</h2>
260
+ <p>Name: <%= @prescription.patient.name %></p>
261
+ <p>Contact: <%= @prescription.patient.phone %></p>
262
+
263
+ <h2>Quote Summary</h2>
264
+ <% if @prescription.quote %>
265
+ <p>Total: $<%= number_to_currency(@prescription.quote.total) %></p>
266
+ <p>Paid: $<%= number_to_currency(@prescription.quote.total_paid) %></p>
267
+ <p>Balance: $<%= number_to_currency(@prescription.quote.remaining_balance) %></p>
268
+ <p>Status: <%= @prescription.quote.fully_paid? ? 'PAID' : 'PENDING' %></p>
269
+
270
+ <h3>Line Items</h3>
271
+ <ul>
272
+ <% @prescription.quote.line_items.each do |item| %>
273
+ <li><%= item.description %> - $<%= item.subtotal %></li>
274
+ <% end %>
275
+ </ul>
276
+
277
+ <h3>Payments</h3>
278
+ <ul>
279
+ <% @prescription.quote.payments.each do |payment| %>
280
+ <li>
281
+ <%= payment.payment_date.strftime('%Y-%m-%d') %> -
282
+ $<%= payment.amount %>
283
+ (<%= payment.payment_method_name %>)
284
+ </li>
285
+ <% end %>
286
+ </ul>
287
+ <% else %>
288
+ <p>No quote created yet.</p>
289
+ <%= link_to 'Create Quote', create_quote_prescription_path(@prescription), method: :post %>
290
+ <% end %>
291
+ ```
292
+
293
+ ## API Integration
294
+
295
+ ### Creating Quote with Prescription
296
+
297
+ ```javascript
298
+ // Create prescription with quote
299
+ const response = await fetch('/prescriptions', {
300
+ method: 'POST',
301
+ headers: { 'Content-Type': 'application/json' },
302
+ body: JSON.stringify({
303
+ prescription: {
304
+ patient_id: 123,
305
+ doctor: "Dr. Smith",
306
+ prescription_details: "OD: -2.00"
307
+ }
308
+ })
309
+ });
310
+
311
+ const prescription = await response.json();
312
+ const quoteId = prescription.quote.id;
313
+
314
+ // Add items to the quote
315
+ await fetch(`/budget/quotes/${quoteId}/line_items`, {
316
+ method: 'POST',
317
+ headers: { 'Content-Type': 'application/json' },
318
+ body: JSON.stringify({
319
+ line_item: {
320
+ description: "Lentes progresivos",
321
+ price: 150.00,
322
+ category: "lente"
323
+ }
324
+ })
325
+ });
326
+ ```
327
+
328
+ ### Fetching Quote for Prescription
329
+
330
+ ```javascript
331
+ // Get prescription with quote details
332
+ const response = await fetch(`/prescriptions/${prescriptionId}`);
333
+ const prescription = await response.json();
334
+
335
+ console.log(prescription.quote.total);
336
+ console.log(prescription.quote.remaining_balance);
337
+ ```
338
+
339
+ ## Database Schema
340
+
341
+ After integration, your schema will look like:
342
+
343
+ ```
344
+ patients
345
+ ├── id
346
+ ├── name
347
+ ├── email
348
+ ├── phone
349
+ └── ...
350
+
351
+ prescriptions
352
+ ├── id
353
+ ├── patient_id (FK → patients)
354
+ ├── doctor
355
+ ├── prescription_details
356
+ └── ...
357
+
358
+ budget_quotes
359
+ ├── id
360
+ ├── prescription_id (FK → prescriptions) ← NEW!
361
+ ├── customer_name
362
+ ├── customer_contact
363
+ ├── quote_date
364
+ └── ...
365
+
366
+ budget_line_items
367
+ ├── id
368
+ ├── budget_quote_id (FK → budget_quotes)
369
+ ├── description
370
+ ├── price
371
+ └── ...
372
+
373
+ budget_payments
374
+ ├── id
375
+ ├── budget_quote_id (FK → budget_quotes)
376
+ ├── amount
377
+ ├── payment_date
378
+ └── ...
379
+ ```
380
+
381
+ ## Best Practices
382
+
383
+ 1. **Use Callbacks Wisely**: Automatically create quotes when prescriptions are created
384
+ 2. **Delegate Methods**: Use `delegate` in Prescription to avoid `prescription.quote.total`
385
+ 3. **Validations**: Ensure prescription_id is present when needed
386
+ 4. **Eager Loading**: Use `includes` to avoid N+1 queries
387
+ 5. **Soft Deletes**: Consider using `dependent: :destroy` or `dependent: :nullify`
388
+
389
+ ## Testing
390
+
391
+ ```ruby
392
+ # spec/models/prescription_spec.rb
393
+ RSpec.describe Prescription, type: :model do
394
+ describe 'associations' do
395
+ it { should belong_to(:patient) }
396
+ it { should have_one(:quote).class_name('Budget::Quote') }
397
+ end
398
+
399
+ describe 'callbacks' do
400
+ it 'creates a quote after creation' do
401
+ patient = create(:patient)
402
+ prescription = patient.prescriptions.create!(doctor: 'Dr. Smith')
403
+
404
+ expect(prescription.quote).to be_present
405
+ expect(prescription.quote.customer_name).to eq(patient.name)
406
+ end
407
+ end
408
+
409
+ describe 'delegations' do
410
+ it 'delegates total to quote' do
411
+ prescription = create(:prescription)
412
+ prescription.quote.add_line_item(description: 'Test', price: 100)
413
+
414
+ expect(prescription.total).to eq(100)
415
+ end
416
+ end
417
+ end
418
+ ```
419
+
420
+ ## Troubleshooting
421
+
422
+ ### Quote not being created automatically
423
+
424
+ Make sure the callback is defined correctly and the patient has a name:
425
+
426
+ ```ruby
427
+ after_create :create_initial_quote, if: -> { patient.present? }
428
+ ```
429
+
430
+ ### Association not found error
431
+
432
+ Ensure you've restarted your Rails server after adding the initializer:
433
+
434
+ ```bash
435
+ rails restart
436
+ # or
437
+ touch tmp/restart.txt
438
+ ```
439
+
440
+ ### Foreign key constraint fails
441
+
442
+ The `prescription_id` column must allow NULL if you want to create standalone quotes:
443
+
444
+ ```ruby
445
+ add_reference :budget_quotes, :prescription, foreign_key: true, null: true
446
+ ```
447
+
448
+ ## Questions?
449
+
450
+ See also:
451
+ - [RAILS_USAGE.md](RAILS_USAGE.md) - General Rails integration
452
+ - [API_DOCUMENTATION.md](API_DOCUMENTATION.md) - API endpoints reference
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Ruben Paz Chuspe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.