Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

create a qr code reader #396

Merged
merged 2 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions app/assets/stylesheets/qr_scanner.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
#reader {
width: 100%;
max-width: 600px;
margin: 0 auto;
z-index: 1;
position: relative;
}

#raw-data {
background: #f8f9fa;
border-radius: 4px;
padding: 10px;
word-break: break-all;
}

.modal-body pre {
max-height: 200px;
overflow-y: auto;
}

/* Remove modal backdrop and adjust modal styling */
.modal-backdrop {
display: none !important;
}

.modal {
background: rgba(0, 0, 0, 0.5);
z-index: 1050 !important;
}

.modal-dialog {
z-index: 1051 !important;
position: relative;
margin-top: 2rem;
}

.modal-content {
position: relative;
box-shadow: 0 5px 15px rgba(0,0,0,.5);
border: 1px solid rgba(0,0,0,.2);
border-radius: 12px;
border: none;
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.modal-header {
border-radius: 12px 12px 0 0;
padding: 1.2rem;
}

.modal-body {
padding: 1.5rem;
}

.product-info-card {
background: #fff;
border-radius: 8px;
padding: 1.5rem;
}

.product-header {
text-align: center;
padding-bottom: 1rem;
border-bottom: 1px solid #eee;
}

.product-header h4 {
font-size: 1.5rem;
font-weight: 600;
margin: 0;
color: #2d3748;
}

.info-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1.5rem;
margin-top: 1.5rem;
}

.info-item {
display: flex;
align-items: flex-start;
gap: 1rem;
}

.info-item i {
font-size: 1.2rem;
padding-top: 0.2rem;
}

.info-content {
flex: 1;
}

.info-content label {
display: block;
font-size: 0.875rem;
color: #718096;
margin-bottom: 0.25rem;
}

.info-content .value {
font-size: 1rem;
font-weight: 500;
color: #2d3748;
}

.action-buttons {
margin-top: 2rem;
}

.action-buttons .btn {
padding: 0.75rem 1.5rem;
font-weight: 500;
}

.modal-footer {
border-radius: 0 0 12px 12px;
padding: 1rem 1.5rem;
}

/* Hide the HTML5 QR scanner's continue button when modal is shown */
.modal.show ~ #reader__dashboard_section_csr button {
display: none !important;
}

/* Ensure scanner elements don't overlap modal */
#reader__dashboard_section_csr,
#reader__dashboard_section_swaplink,
#reader__scan_region {
z-index: 1 !important;
}
41 changes: 39 additions & 2 deletions app/controllers/api/v1/products_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,54 @@

module Api
module V1
class ProductsController < ApplicationController
class ProductsController < ActionController::API
include ActionController::MimeResponds
set_current_tenant_through_filter
before_action :set_tenant_from_qr_data

def show_by_id
begin
@product = Product.find_by!(id: params[:id])
render json: ProductSerializer.new(@product).serializable_hash
rescue ActiveRecord::RecordNotFound => e
Rails.logger.error "Product not found: #{e.message}"
render json: { error: 'Product not found' }, status: :not_found
rescue StandardError => e
Rails.logger.error "Error in show_by_id: #{e.message}\n#{e.backtrace.join("\n")}"
render json: { error: 'Internal server error' }, status: :internal_server_error
end
end

def show
@product = Product.find_by(custom_id: params[:custom_id])
@product = Product.find_by!(id: params[:id])
render json: ProductSerializer.new(@product).serializable_hash
rescue ActiveRecord::RecordNotFound => e
render json: { error: 'Product not found' }, status: :not_found
end

def show_product
@product = Product.find(params[:id])
render json: ProductSerializer.new(@product).serializable_hash
end

def index
@products = Product.where(active: true)
render json: ProductSerializer.new(@products).serializable_hash
end

def find_by_sku
@product = Product.find_by!(sku: params[:sku])
render json: ProductSerializer.new(@product).serializable_hash
rescue ActiveRecord::RecordNotFound
render json: { error: 'Product not found' }, status: :not_found
end

private

def set_tenant_from_qr_data
account_id = request.headers['X-Account-ID'] || params[:account_id]
current_account = Account.find_by(id: account_id)
set_current_tenant(current_account)
end
end
end
Expand Down
36 changes: 33 additions & 3 deletions app/controllers/products_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,39 @@ def update_active

def download_qr_code
@product = Product.find(params[:id])
qr_code = RQRCode::QRCode.new(@product.sku)
png = qr_code.as_png(size: 300)
send_data png, type: 'image/png', disposition: 'attachment', filename: "#{@product.name}_qr_code.png"
qr_code_data_url = Services::Product::GenerateQrCode.new(product: @product).call

# Convert data URL to binary
png_data = Base64.decode64(qr_code_data_url.split(',')[1])

send_data png_data,
type: 'image/png',
disposition: 'attachment',
filename: "#{@product.name}_qr_code.png"
end

def scan_qr_code
# Just renders the view with the QR scanner
end

def update_stock_from_qr
@product = Product.find(params[:id])
quantity = params[:quantity].to_i

begin
ActiveRecord::Base.transaction do
# Create a new stock record or update existing
if @product.stock.nil?
@product.create_stock(quantity: quantity)
else
@product.stock.update!(quantity: quantity)
end

render json: { success: true, message: 'Stock updated successfully' }
end
rescue StandardError => e
render json: { success: false, error: e.message }, status: :unprocessable_entity
end
end

private
Expand Down
5 changes: 5 additions & 0 deletions app/controllers/qr_scanner_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class QrScannerController < ApplicationController
def index
# Just renders the view
end
end
2 changes: 1 addition & 1 deletion app/models/services/product/generate_qr_code.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def initialize(product:, width: 300, height: 300)
end

def call
object = { id: @product.id, custom_id: @product.custom_id, name: @product.name }
object = { id: @product.id, account_id: @product.account_id }
RQRCode::QRCode.new(object.to_json).to_img.resize(@width, @height).to_data_url
end
end
Expand Down
37 changes: 16 additions & 21 deletions app/serializers/product_serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,33 +31,28 @@
# fk_rails_... (category_id => categories.id)
#
class ProductSerializer
include FastJsonapi::ObjectSerializer
include JSONAPI::Serializer

attributes :id, :custom_id, :name, :count_purchase_product, :count_sale_product, :active, :sku

attribute :price do |object|
"R$ #{object.price}"
end

attribute :balance, &:balance

attribute :custom_id do |object|
object.custom_id.to_i
end
attributes :id, :name, :sku, :price, :active, :custom_id

attribute :category do |object|
object.category.name
object.category&.name
end

attribute :image_url do |object|
object.image.attached? ? Rails.application.routes.url_helpers.rails_blob_path(object.image, only_path: true) : 'https://purple-stock.s3-sa-east-1.amazonaws.com/images.png'
end

attribute :active do |object|
if object.active
'Sim'
attribute :stock do |object|
if object.stock
object.stock.try(:quantity) || 0
else
'Não'
0
end
end

attribute :formatted_price do |object|
ActionController::Base.helpers.number_to_currency(
object.price,
unit: "R$",
separator: ",",
delimiter: "."
)
end
end
6 changes: 5 additions & 1 deletion app/views/products/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<% end %>

<%= link_to t('.new', :default => t("helpers.links.new")), new_product_path, :class => 'btn btn-primary mb-3' %>
<%= link_to icon('fas fa-camera') + ' Scan QR Code', qr_scanner_path, class: 'btn btn-info mb-3 ml-2' %>

<div class="card">
<div class="card-body">
Expand All @@ -43,7 +44,10 @@
<%= tag.tr id: dom_id(product) do %>
<td><%= link_to (product.image.attached? ? image_tag(rails_blob_path(product.image.variant(:thumb)), class: "thumb-image #{'thumb-image-mobile' if (platform.mobile? || platform.mobile_app?) }") : image_tag('products/product-5-50.png', size: '50', class: "thumb-image #{'thumb-image-mobile' if (platform.mobile? || platform.mobile_app?) }" )), product_path(product), data: { toggle: 'tooltip', turbo: false } %></td>
<td><%= product.name %></td>
<td><%= product.sku %></td>
<td>
<%= product.sku %>
<%= image_tag Services::Product::GenerateQrCode.new(product: product).call, size: '50' %>
</td>
<td><%= product.custom_id %></td>
<td><%= number_to_currency_pt_br(product.price) %></td>
<td><%= Services::Product::CountQuantity.call(product: product, product_command: 'purchase_product') %></td>
Expand Down
72 changes: 72 additions & 0 deletions app/views/products/scan_qr_code.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<div class="section-header">
<div class="page-header">
<h1>Scan QR Code</h1>
</div>
</div>

<div class="section-body">
<div class="card">
<div class="card-body">
<div id="reader"></div>

<div id="result-container" class="mt-4" style="display: none;">
<div class="form-group">
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" class="form-control" min="0">
</div>
<button id="submit-quantity" class="btn btn-primary mt-3">Update Stock</button>
</div>
</div>
</div>
</div>

<%= javascript_include_tag "https://unpkg.com/html5-qrcode" %>

<script>
document.addEventListener('DOMContentLoaded', function() {
const html5QrcodeScanner = new Html5QrcodeScanner(
"reader", { fps: 10, qrbox: 250 });

function onScanSuccess(decodedText, decodedResult) {
// Stop scanning
html5QrcodeScanner.clear();

// Show the quantity input
document.getElementById('result-container').style.display = 'block';

// Handle submit button click
document.getElementById('submit-quantity').addEventListener('click', function() {
const quantity = document.getElementById('quantity').value;

// Send the data to the server
fetch(`/products/${decodedText}/update_stock_from_qr`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content
},
body: JSON.stringify({ quantity: quantity })
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Stock updated successfully!');
window.location.href = '/products';
} else {
alert('Error updating stock: ' + data.error);
}
})
.catch(error => {
console.error('Error:', error);
alert('Error updating stock');
});
});
}

function onScanError(errorMessage) {
// handle scan error
}

html5QrcodeScanner.render(onScanSuccess, onScanError);
});
</script>
Loading
Loading