fix: Extract filename from URL for WhatsApp template document attachment

This commit is contained in:
Muhsin Keloth
2025-08-23 00:05:11 +05:30
parent 7f56cd92f8
commit 5ecf39a3a7
2 changed files with 40 additions and 3 deletions
@@ -96,7 +96,8 @@ class Whatsapp::PopulateTemplateParametersService
when 'video'
build_video_parameter(sanitized_url)
when 'document'
build_document_parameter(sanitized_url)
filename = extract_filename_from_url(sanitized_url)
build_document_parameter(sanitized_url, filename)
else
raise ArgumentError, "Unsupported media type: #{media_type}"
end
@@ -110,8 +111,10 @@ class Whatsapp::PopulateTemplateParametersService
{ type: 'video', video: { link: url } }
end
def build_document_parameter(url)
{ type: 'document', document: { link: url } }
def build_document_parameter(url, filename = nil)
document_param = { link: url }
document_param[:filename] = filename if filename.present?
{ type: 'document', document: document_param }
end
def rich_formatting?(text)
@@ -145,4 +148,19 @@ class Whatsapp::PopulateTemplateParametersService
rescue URI::InvalidURIError => e
raise ArgumentError, "Invalid URL format: #{e.message}. Please enter a valid URL like https://example.com/document.pdf"
end
def extract_filename_from_url(url)
return nil if url.blank?
begin
uri = URI.parse(url)
path = uri.path
filename = File.basename(path)
# Return filename only if it has an extension, otherwise return nil
filename.include?('.') ? filename : nil
rescue URI::InvalidURIError
nil
end
end
end
@@ -182,6 +182,25 @@ describe Whatsapp::SendOnWhatsappService do
expect(message.reload.source_id).to eq('123456789')
end
it 'handles template with document header parameters and extracts filename' do
processed_params = {
'body' => { '1' => 'Order123' },
'header' => { 'media_url' => 'https://example.com/documents/receipt.pdf', 'media_type' => 'document' }
}
document_template_params = build_sample_template_params(processed_params)
message = create_message_with_template('', document_template_params)
components = [
{ type: 'header',
parameters: [{ type: 'document', document: { link: 'https://example.com/documents/receipt.pdf', filename: 'receipt.pdf' } }] },
{ type: 'body', parameters: [{ type: 'text', text: 'Order123' }] }
]
stub_sample_template_request(components)
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end
it 'handles empty processed_params gracefully' do
empty_template_params = {
name: 'sample_shipping_confirmation',