From f6d5b520fb0c3c20de610159ea39ab6c910d5087 Mon Sep 17 00:00:00 2001 From: Seth Call Date: Wed, 17 Feb 2016 15:44:57 -0600 Subject: [PATCH] * wip --- db/up/lessons.sql | 43 +- ruby/Gemfile | 2 + ruby/lib/jam_ruby.rb | 2 + ruby/lib/jam_ruby/app/mailers/user_mailer.rb | 40 + .../student_lesson_request.html.erb | 11 + .../student_lesson_request.text.erb | 3 + .../teacher_lesson_request.html.erb | 11 + .../teacher_lesson_request.text.erb | 3 + ruby/lib/jam_ruby/lib/stats.rb | 28 +- ruby/lib/jam_ruby/models/lesson_booking.rb | 63 +- .../jam_ruby/models/lesson_booking_slot.rb | 1 + .../models/lesson_package_purchase.rb | 28 +- .../jam_ruby/models/lesson_package_type.rb | 24 + ruby/lib/jam_ruby/models/lesson_session.rb | 38 +- ruby/lib/jam_ruby/models/sale.rb | 96 +- ruby/lib/jam_ruby/models/sale_line_item.rb | 11 +- ruby/lib/jam_ruby/models/shopping_cart.rb | 4 + ruby/lib/jam_ruby/models/teacher.rb | 15 + ruby/lib/jam_ruby/models/user.rb | 59 + ruby/spec/factories.rb | 49 + .../jam_ruby/models/lesson_booking_spec.rb | 26 +- .../models/lesson_package_purchase_spec.rb | 3 +- .../jam_ruby/models/lesson_session_spec.rb | 39 + ruby/spec/jam_ruby/models/sale_spec.rb | 78 + ruby/spec/jam_ruby/models/user_spec.rb | 31 + ruby/spec/mailers/render_emails_spec.rb | 19 + ruby/spec/spec_helper.rb | 2 + ruby/spec/support/utilities.rb | 12 + web/Gemfile | 7 +- web/app/assets/javascripts/application.js | 1 + web/app/assets/javascripts/jam_rest.js | 21 + .../BookLessonFree.js.jsx.coffee | 1 + .../FreeLessonPayment.js.jsx.coffee | 139 - .../JamClassStudentScreen.js.jsx.coffee | 154 + .../LessonPayment.js.jsx.coffee | 324 +- .../actions/UserActions.js.coffee | 1 + .../mixins/ICheckMixin.js.coffee | 40 + .../stores/UserStore.js.coffee | 7 + .../client/jamtrack_landing.css.scss | 2 + .../FreeLessonPayment.css.scss | 100 - .../JamClassStudentScreen.css.scss | 86 + .../react-components/LessonPayment.css.scss | 105 + web/app/controllers/api_controller.rb | 4 + .../api_lesson_bookings_controller.rb | 12 +- .../api_lesson_sessions_controller.rb | 14 + web/app/controllers/api_stripe_controller.rb | 11 + web/app/helpers/client_helper.rb | 1 + web/app/views/api_jamblasters/get_tokens.rabl | 2 +- web/app/views/api_lesson_bookings/show.rabl | 4 +- web/app/views/api_lesson_sessions/index.rabl | 11 + web/app/views/api_lesson_sessions/show.rabl | 31 + web/app/views/api_stripe/store.rabl | 14 + web/app/views/api_users/show.rabl | 4 +- web/app/views/clients/index.html.erb | 2 +- .../jamclass/_free_lesson_payment.html.slim | 10 - .../jamclass/_jamclass_student.html.slim | 10 + .../jamclass/_lesson_payment.html.slim | 2 +- web/app/views/errors/stripe_error.rabl | 13 + web/app/views/layouts/client.html.erb | 1 + web/app/views/shared/_stripe.html.slim | 6 + web/config/application.rb | 11 +- web/config/initializers/stripe.rb | 1 + web/config/initializers/zip_codes.rb | 1 + web/config/routes.rb | 3 + .../assets/javascripts/jquery.inputmask.js | 2653 +++++++++++++++++ .../assets/javascripts/jquery.payment.js | 651 ++++ .../lib/jam_websockets/router.rb | 1 - 67 files changed, 4872 insertions(+), 330 deletions(-) create mode 100644 ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/student_lesson_request.html.erb create mode 100644 ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/student_lesson_request.text.erb create mode 100644 ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/teacher_lesson_request.html.erb create mode 100644 ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/teacher_lesson_request.text.erb create mode 100644 ruby/spec/jam_ruby/models/lesson_session_spec.rb delete mode 100644 web/app/assets/javascripts/react-components/FreeLessonPayment.js.jsx.coffee create mode 100644 web/app/assets/javascripts/react-components/JamClassStudentScreen.js.jsx.coffee create mode 100644 web/app/assets/javascripts/react-components/mixins/ICheckMixin.js.coffee delete mode 100644 web/app/assets/stylesheets/client/react-components/FreeLessonPayment.css.scss create mode 100644 web/app/assets/stylesheets/client/react-components/JamClassStudentScreen.css.scss create mode 100644 web/app/controllers/api_lesson_sessions_controller.rb create mode 100644 web/app/controllers/api_stripe_controller.rb create mode 100644 web/app/views/api_lesson_sessions/index.rabl create mode 100644 web/app/views/api_lesson_sessions/show.rabl create mode 100644 web/app/views/api_stripe/store.rabl delete mode 100644 web/app/views/clients/jamclass/_free_lesson_payment.html.slim create mode 100644 web/app/views/clients/jamclass/_jamclass_student.html.slim create mode 100644 web/app/views/errors/stripe_error.rabl create mode 100644 web/app/views/shared/_stripe.html.slim create mode 100644 web/config/initializers/stripe.rb create mode 100644 web/config/initializers/zip_codes.rb create mode 100644 web/vendor/assets/javascripts/jquery.inputmask.js create mode 100644 web/vendor/assets/javascripts/jquery.payment.js diff --git a/db/up/lessons.sql b/db/up/lessons.sql index 97cc823b0..a47d253f0 100644 --- a/db/up/lessons.sql +++ b/db/up/lessons.sql @@ -19,16 +19,39 @@ CREATE TABLE lesson_package_purchases ( updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ); +CREATE TABLE lesson_bookings ( + id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id VARCHAR(64) REFERENCES users(id) NOT NULL, + lesson_type VARCHAR(64) NOT NULL, + recurring BOOLEAN NOT NULL, + lesson_length INTEGER NOT NULL, + payment_style VARCHAR(64) NOT NULL, + description VARCHAR, + teacher_id VARCHAR(64) REFERENCES users(id) NOT NULL, + card_presumed_ok BOOLEAN NOT NULL DEFAULT FALSE, + sent_notices BOOLEAN NOT NULL DEFAULT FALSE, + status VARCHAR, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +); + CREATE TABLE lesson_sessions ( id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4(), music_session_id VARCHAR(64) REFERENCES music_sessions(id) NOT NULL, lesson_type VARCHAR(64) NOT NULL, - teacher_id VARCHAR(64) REFERENCES teachers(id) NOT NULL, + teacher_id VARCHAR(64) REFERENCES users(id) NOT NULL, lesson_package_purchase_id VARCHAR(64) REFERENCES lesson_package_purchases(id), + lesson_booking_id VARCHAR(64) REFERENCES lesson_bookings(id), duration INTEGER NOT NULL, price NUMERIC(8,2) NOT NULL, teacher_complete BOOLEAN DEFAULT FALSE NOT NULL, student_complete BOOLEAN DEFAULT FALSE NOT NULL, + student_canceled BOOLEAN DEFAULT FALSE NOT NULL, + teacher_canceled BOOLEAN DEFAULT FALSE NOT NULL, + student_canceled_at TIMESTAMP, + teacher_canceled_at TIMESTAMP, + student_canceled_reason VARCHAR, + teacher_canceled_reason VARCHAR, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ); @@ -42,19 +65,6 @@ INSERT INTO lesson_package_types (id, name, description, package_type, price) VA INSERT INTO lesson_package_types (id, name, description, package_type, price) VALUES ('single-free', 'Free Lesson', 'A free, single lesson.', 'single-free', 0.00); INSERT INTO lesson_package_types (id, name, description, package_type, price) VALUES ('test-drive', 'Test Drive', 'Four reduced-price lessons which you can use to find that ideal teacher.', 'test-drive', 49.99); -CREATE TABLE lesson_bookings ( - id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4(), - user_id VARCHAR(64) REFERENCES users(id) NOT NULL, - lesson_type VARCHAR(64) NOT NULL, - recurring BOOLEAN NOT NULL, - lesson_length INTEGER NOT NULL, - payment_style VARCHAR(64) NOT NULL, - description VARCHAR, - teacher_id VARCHAR(64) REFERENCES users(id) NOT NULL, - card_presumed_ok BOOLEAN NOT NULL DEFAULT FALSE, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP -); CREATE TABLE lesson_booking_slots ( id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4(), @@ -64,6 +74,7 @@ CREATE TABLE lesson_booking_slots ( day_of_week INTEGER, hour INTEGER, minute INTEGER, + timezone VARCHAR NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ); @@ -73,3 +84,7 @@ ALTER TABLE chat_messages ADD COLUMN lesson_booking_id VARCHAR(64) REFERENCES le ALTER TABLE users ADD COLUMN remaining_free_lessons INTEGER NOT NULL DEFAULT 1; ALTER TABLE users ADD COLUMN stored_credit_card BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE users ADD COLUMN remaining_test_drives INTEGER NOT NULL DEFAULT 0; +ALTER TABLE users ADD COLUMN stripe_token VARCHAR(200); +ALTER TABLE users ADD COLUMN stripe_customer_id VARCHAR(200); +ALTER TABLE users ADD COLUMN stripe_zip_code VARCHAR(200); +ALTER TABLE sales ADD COLUMN stripe_charge_id VARCHAR(200); diff --git a/ruby/Gemfile b/ruby/Gemfile index 0680c23cb..561c4efa8 100644 --- a/ruby/Gemfile +++ b/ruby/Gemfile @@ -52,6 +52,8 @@ gem 'sanitize' gem 'influxdb', '0.1.8' gem 'recurly' gem 'sendgrid_toolkit', '>= 1.1.1' +gem 'stripe' +gem 'zip-codes' group :test do gem 'simplecov', '~> 0.7.1' diff --git a/ruby/lib/jam_ruby.rb b/ruby/lib/jam_ruby.rb index fa7619211..817f0f91e 100755 --- a/ruby/lib/jam_ruby.rb +++ b/ruby/lib/jam_ruby.rb @@ -21,6 +21,8 @@ require 'rest-client' require 'zip' require 'csv' require 'tzinfo' +require 'stripe' +require 'zip-codes' require "jam_ruby/constants/limits" require "jam_ruby/constants/notification_types" diff --git a/ruby/lib/jam_ruby/app/mailers/user_mailer.rb b/ruby/lib/jam_ruby/app/mailers/user_mailer.rb index 84355a1ae..ec73a6d9f 100644 --- a/ruby/lib/jam_ruby/app/mailers/user_mailer.rb +++ b/ruby/lib/jam_ruby/app/mailers/user_mailer.rb @@ -621,6 +621,46 @@ end end + def student_lesson_request(lesson_booking) + email = lesson_booking.user.email + subject = "You have sent a lesson request to #{lesson_booking.teacher.name}!" + unique_args = {:type => "student_lesson_request"} + + @sender = lesson_booking.teacher + @lesson_booking = lesson_booking + + sendgrid_category "Notification" + sendgrid_unique_args :type => unique_args[:type] + + sendgrid_recipients([email]) + sendgrid_substitute('@USERID', [lesson_booking.user.id]) + + mail(:to => email, :subject => subject) do |format| + format.text + format.html { render :layout => "from_user_mailer" } + end + end + + def teacher_lesson_request(lesson_booking) + email = lesson_booking.teacher.email + subject = "You have received a lesson request through JamKazam!" + unique_args = {:type => "teacher_lesson_request"} + + @sender = lesson_booking.user + @lesson_booking = lesson_booking + + sendgrid_category "Notification" + sendgrid_unique_args :type => unique_args[:type] + + sendgrid_recipients([email]) + sendgrid_substitute('@USERID', [lesson_booking.teacher.id]) + + mail(:to => email, :subject => subject) do |format| + format.text + format.html { render :layout => "from_user_mailer" } + end + end + # def send_notification(email, subject, msg, unique_args) # @body = msg # sendgrid_category "Notification" diff --git a/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/student_lesson_request.html.erb b/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/student_lesson_request.html.erb new file mode 100644 index 000000000..ab60f3f5b --- /dev/null +++ b/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/student_lesson_request.html.erb @@ -0,0 +1,11 @@ +<% provide(:title, "Lesson Request sent to #{@sender.name}") %> +<% provide(:photo_url, @sender.resolved_photo_url) %> + +<% content_for :note do %> +

You have requested a <%= @lesson_booking.display_type %> lesson.

Click the button below to see your lesson request. You will receive another email when the teacher accepts or reject the request.

+

+ VIEW LESSON REQUEST +

+<% end %> + + diff --git a/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/student_lesson_request.text.erb b/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/student_lesson_request.text.erb new file mode 100644 index 000000000..068228c3e --- /dev/null +++ b/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/student_lesson_request.text.erb @@ -0,0 +1,3 @@ +You have requested a lesson from <%= @sender.name %>. + +To see this lesson request, click here: <%= @lesson_booking.home_url %> \ No newline at end of file diff --git a/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/teacher_lesson_request.html.erb b/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/teacher_lesson_request.html.erb new file mode 100644 index 000000000..e3f0e537a --- /dev/null +++ b/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/teacher_lesson_request.html.erb @@ -0,0 +1,11 @@ +<% provide(:title, "Lesson Request from #{@sender.name}") %> +<% provide(:photo_url, @sender.resolved_photo_url) %> + +<% content_for :note do %> +

This student has requested to schedule a <%= @lesson_booking.display_type %> lesson.

Click the button below to get more information and to respond to this lesson request. You must respond to this lesson request promptly, or it will be cancelled, thank you!

+

+ VIEW LESSON REQUEST +

+<% end %> + + diff --git a/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/teacher_lesson_request.text.erb b/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/teacher_lesson_request.text.erb new file mode 100644 index 000000000..c28cf0142 --- /dev/null +++ b/ruby/lib/jam_ruby/app/views/jam_ruby/user_mailer/teacher_lesson_request.text.erb @@ -0,0 +1,3 @@ +<%= @sender.name %> has requested a lesson. + +To see this lesson request, click here: <%= @lesson_booking.home_url %> \ No newline at end of file diff --git a/ruby/lib/jam_ruby/lib/stats.rb b/ruby/lib/jam_ruby/lib/stats.rb index 697965526..17506a27e 100644 --- a/ruby/lib/jam_ruby/lib/stats.rb +++ b/ruby/lib/jam_ruby/lib/stats.rb @@ -82,8 +82,32 @@ module JamRuby return if self.ignore # doing any writes in a test environment cause annoying puts to occur if @client && data && data.length > 0 - data['host'] = @host - data['time'] = Time.now.to_i + if data.has_key?('values') || data.has_key?(:values) + @client.write_point(name, data) + data['timestamp'] = Time.now.to_i + + tags = data['tags'] + key = 'tags' if tags + tags ||= data[:tags] + key = :tags if key.nil? + tags ||= {} + key = :tags if key.nil? + + tags['host'] = @host + data[key] = tags + else + tags = {} + values = {} + for k,v in data + if v.is_a?(String) + tags[k] = v + else + values[k] = v + end + end + data = {tags: tags, values: values} + end + @client.write_point(name, data) end end diff --git a/ruby/lib/jam_ruby/models/lesson_booking.rb b/ruby/lib/jam_ruby/models/lesson_booking.rb index 993590e45..c340a0d65 100644 --- a/ruby/lib/jam_ruby/models/lesson_booking.rb +++ b/ruby/lib/jam_ruby/models/lesson_booking.rb @@ -4,6 +4,13 @@ module JamRuby @@log = Logging.logger[LessonBooking] + STATUS_REQUESTED = 'requested' + STATUS_CANCELED = 'canceled' + STATUS_MISSED = 'missed' + STATUS_COMPLETED = 'completed' + + STATUS_TYPES = [STATUS_REQUESTED, STATUS_CANCELED, STATUS_MISSED, STATUS_COMPLETED] + LESSON_TYPE_FREE = 'single-free' LESSON_TYPE_TEST_DRIVE = 'test-drive' LESSON_TYPE_PAID = 'paid' @@ -20,11 +27,15 @@ module JamRuby belongs_to :user, class_name: "JamRuby::User" belongs_to :teacher, class_name: "JamRuby::User" has_many :lesson_booking_slots, class_name: "JamRuby::LessonBookingSlot" + has_many :lesson_sessions, class_name: "JamRuby::LessonSession" validates :user, presence: true validates :teacher, presence: true validates :lesson_type, presence: true, inclusion: {in: LESSON_TYPES} + validates :status, presence: true, inclusion: {in: STATUS_TYPES} validates :recurring, inclusion: {in: [true, false]} + validates :sent_notices, inclusion: {in: [true, false]} + validates :card_presumed_ok, inclusion: {in: [true, false]} validates :lesson_length, presence: true, inclusion: {in: [30, 45, 60, 90, 120]} validates :payment_style, inclusion: {in: PAYMENT_STYLES} validates :description, no_profanity: true, length: {minimum: 10, maximum: 20000}, presence: true @@ -35,6 +46,40 @@ module JamRuby validate :validate_lesson_length validate :validate_payment_style + after_create :after_create + def after_create + if card_presumed_ok && !sent_notices + send_notices + end + end + + def send_notices + UserMailer.student_lesson_request(self).deliver + UserMailer.teacher_lesson_request(self).deliver + LessonBooking.where(id: id).update_all(sent_notices: true) + end + + def display_type + if is_single_free? + "Free" + elsif is_test_drive? + "TestDrive" + elsif is_normal? + "Lesson Purchase" + end + end + + # determine the price of this booking based on what the user wants, and the teacher's pricing + def booked_price + if is_single_free? + 0 + elsif is_test_drive? + LessonPackageType.test_drive.price + elsif is_normal? + teacher.teacher.booking_price(lesson_length, payment_style != PAYMENT_STYLE_MONTHLY) + end + end + def is_single_free? lesson_type == LESSON_TYPE_FREE end @@ -47,6 +92,13 @@ module JamRuby lesson_type == LESSON_TYPE_PAID end + def card_approved + LessonBooking.where(id: id).update_all(card_presumed_ok: true) + if !sent_notices + send_notices + end + end + def validate_user if is_single_free? if !user.has_free_lessons? @@ -124,6 +176,7 @@ module JamRuby lesson_booking = LessonBooking.new lesson_booking.user = user lesson_booking.card_presumed_ok = user.has_stored_credit_card? + lesson_booking.sent_notices = false lesson_booking.teacher = teacher lesson_booking.lesson_type = lesson_type lesson_booking.lesson_booking_slots = lesson_booking_slots @@ -131,6 +184,7 @@ module JamRuby lesson_booking.lesson_length = lesson_length lesson_booking.payment_style = payment_style lesson_booking.description = description + lesson_booking.status = STATUS_REQUESTED if lesson_booking.save @@ -152,8 +206,15 @@ module JamRuby end def self.unprocessed(current_user) - LessonBooking.where(user_id: current_user.id).where(card_presumed_ok: false).first + LessonBooking.where(user_id: current_user.id).where(card_presumed_ok: false) end + def home_url + APP_CONFIG.external_root_url + "/client#/jamclass" + end + + def web_url + APP_CONFIG.external_root_url + "/client#/jamclass/lesson-request/" + id + end end end diff --git a/ruby/lib/jam_ruby/models/lesson_booking_slot.rb b/ruby/lib/jam_ruby/models/lesson_booking_slot.rb index ae286d5e3..564c86d3d 100644 --- a/ruby/lib/jam_ruby/models/lesson_booking_slot.rb +++ b/ruby/lib/jam_ruby/models/lesson_booking_slot.rb @@ -16,6 +16,7 @@ module JamRuby validates :day_of_week, numericality: {only_integer: true}, allow_blank: true # 0 = sunday - 6 = saturday validates :hour, numericality: {only_integer: true} validates :minute, numericality: {only_integer: true} + validates :timezone, presence: true validate :validate_slot_type diff --git a/ruby/lib/jam_ruby/models/lesson_package_purchase.rb b/ruby/lib/jam_ruby/models/lesson_package_purchase.rb index d255a0398..88bff5b92 100644 --- a/ruby/lib/jam_ruby/models/lesson_package_purchase.rb +++ b/ruby/lib/jam_ruby/models/lesson_package_purchase.rb @@ -9,16 +9,40 @@ module JamRuby end # who purchased the lesson package? - belongs_to :user, class_name: "JamRuby::User" + belongs_to :user, class_name: "JamRuby::User", :foreign_key => "user_id", inverse_of: :lesson_purchases belongs_to :lesson_package_type, class_name: "JamRuby::LessonPackageType" belongs_to :teacher, class_name: "JamRuby::Teacher" - def self.create(user, lesson_package_type) + validates :lesson_package_type, presence: true + validates :price, presence: true + + after_save :after_save + + def after_save + + if self.lesson_package_type.is_test_drive? + new_test_drives = user.remaining_test_drives + 4 + User.where(id:user.id).update_all(remaining_test_drives: new_test_drives) + user.remaining_test_drives = user.remaining_test_drives + 4 + end + + end + + def self.create(user, lesson_package_type, lesson_booking) purchase = LessonPackagePurchase.new purchase.user = user purchase.lesson_package_type = lesson_package_type + purchase.price = lesson_package_type.booked_price(lesson_booking) purchase.save purchase end + + def price_in_cents + (price * 100).to_i + end + + def description(lesson_booking) + lesson_package_type.description(lesson_booking) + end end end diff --git a/ruby/lib/jam_ruby/models/lesson_package_type.rb b/ruby/lib/jam_ruby/models/lesson_package_type.rb index 298007853..054619b69 100644 --- a/ruby/lib/jam_ruby/models/lesson_package_type.rb +++ b/ruby/lib/jam_ruby/models/lesson_package_type.rb @@ -34,6 +34,30 @@ module JamRuby LessonPackageType.find(SINGLE) end + def booked_price(lesson_booking) + if is_single_free? + 0 + elsif is_test_drive? + LessonPackageType.test_drive.price + elsif is_normal? + lesson_booking.teacher.teacher.booking_price(lesson_booking.lesson_length, lesson_booking.payment_style == LessonBooking::PAYMENT_STYLE_SINGLE) + end + end + + def description(lesson_booking) + if is_single_free? + "Single Free Lesson" + elsif is_test_drive? + "Test Drive" + elsif is_normal? + if recurring + "Recurring #{lesson_booking.payment_style == PAYMENT_STYLE_WEEKLY ? "Weekly" : "Monthly"} #{lesson_booking.lesson_length}m" + else + "Single #{lesson_booking.lesson_length}m lesson" + end + end + end + def is_single_free? id == SINGLE_FREE end diff --git a/ruby/lib/jam_ruby/models/lesson_session.rb b/ruby/lib/jam_ruby/models/lesson_session.rb index b149cc2dd..bcf313d29 100644 --- a/ruby/lib/jam_ruby/models/lesson_session.rb +++ b/ruby/lib/jam_ruby/models/lesson_session.rb @@ -10,14 +10,50 @@ module JamRuby LESSON_TYPES = [LESSON_TYPE_SINGLE, LESSON_TYPE_SINGLE_FREE, LESSON_TYPE_TEST_DRIVE] belongs_to :music_session, class_name: "JamRuby::MusicSession" - belongs_to :teacher, class_name: "JamRuby::Teacher" + belongs_to :teacher, class_name: "JamRuby::User" belongs_to :lesson_package_purchase, class_name: "JamRuby::LessonPackagePurchase" + belongs_to :lesson_booking, class_name: "JamRuby::LessonBooking" validates :duration, presence: true, numericality: {only_integer: true} + validates :lesson_booking, presence: true validates :lesson_type, inclusion: {in: LESSON_TYPES} validates :price, presence: true validates :teacher_complete, inclusion: {in: [true, false]} validates :student_complete, inclusion: {in: [true, false]} + validates :teacher_cancelled, inclusion: {in: [true, false]} + validates :student_cancelled, inclusion: {in: [true, false]} + + def self.index(user, params = {}) + limit = params[:per_page] + limit ||= 100 + limit = limit.to_i + + query = LessonSession.joins(:music_session).joins(music_session: :creator) + query = query.includes([:teacher, :music_session]) + query = query.order('music_sessions.scheduled_start DESC') + + if params[:as_teacher] + query = query.where('lesson_sessions.teacher_id = ?', user.id) + else + query = query.where('music_sessions.user_id = ?', user.id) + end + + + + current_page = params[:page].nil? ? 1 : params[:page].to_i + next_page = current_page + 1 + + # will_paginate gem + query = query.paginate(:page => current_page, :per_page => limit) + + if query.length == 0 # no more results + { query: query, next_page: nil} + elsif query.length < limit # no more results + { query: query, next_page: nil} + else + { query: query, next_page: next_page } + end + end end end diff --git a/ruby/lib/jam_ruby/models/sale.rb b/ruby/lib/jam_ruby/models/sale.rb index 7fb4e073a..d70507367 100644 --- a/ruby/lib/jam_ruby/models/sale.rb +++ b/ruby/lib/jam_ruby/models/sale.rb @@ -4,6 +4,7 @@ module JamRuby class Sale < ActiveRecord::Base JAMTRACK_SALE = 'jamtrack' + LESSON_SALE = 'lesson' belongs_to :user, class_name: 'JamRuby::User' has_many :sale_line_items, class_name: 'JamRuby::SaleLineItem' @@ -32,12 +33,12 @@ module JamRuby # will_paginate gem query = query.paginate(:page => current_page, :per_page => limit) - if query.length == 0 # no more results - { query: query, next_page: nil} - elsif query.length < limit # no more results - { query: query, next_page: nil} + if query.length == 0 # no more results + {query: query, next_page: nil} + elsif query.length < limit # no more results + {query: query, next_page: nil} else - { query: query, next_page: next_page } + {query: query, next_page: next_page} end end @@ -76,7 +77,7 @@ module JamRuby def self.validateIOSReceipt(receipt) # these are all 'in cents' (as painfully named to be very clear), and all expected to be integers - price_info = {subtotal_in_cents:nil, total_in_cents:nil, tax_in_cents:nil, currency: 'USD'} + price_info = {subtotal_in_cents: nil, total_in_cents: nil, tax_in_cents: nil, currency: 'USD'} # communicate with Apple; populate price_info @@ -180,6 +181,75 @@ module JamRuby free && non_free end + def self.purchase_test_drive(current_user) + self.purchase_lesson(current_user, LessonPackageType.test_drive) + end + + # this is easy to make generic, but right now, it just purchases lessons + def self.purchase_lesson(current_user, lesson_package_type) + sale = nil + # everything needs to go into a transaction! If anything goes wrong, we need to raise an exception to break it + Sale.transaction do + + sale = create_lesson_sale(current_user) + + if sale.valid? + + price_info = charge_stripe_for_lesson(current_user, lesson_package_type) + + SaleLineItem.create_from_lesson_package(current_user, sale, lesson_package_type) + + # sale.source = 'stripe' + sale.recurly_subtotal_in_cents = price_info[:subtotal_in_cents] + sale.recurly_tax_in_cents = price_info[:tax_in_cents] + sale.recurly_total_in_cents = price_info[:total_in_cents] + sale.recurly_currency = price_info[:currency] + sale.stripe_charge_id = price_info[:charge_id] + sale.save + else + # should not get out of testing. This would be very rare (i.e., from a big regression). Sale is always valid at this point. + raise "invalid sale object" + end + + end + sale + end + + + def self.charge_stripe_for_lesson(current_user, lesson_package_type, lesson_booking = nil) + current_user.sync_stripe_customer + + purchase = LessonPackagePurchase.create(current_user, lesson_package_type, lesson_booking) + + subtotal_in_cents = purchase.price_in_cents + tax_percent = 0 + if current_user.stripe_zip_code + lookup =ZipCodes.identify(current_user.stripe_zip_code) + if lookup && lookup[:state_code] == 'TX' + tax_percent = 0.0825 + end + end + + tax_in_cents = (subtotal_in_cents * tax_percent).round + total_in_cents = subtotal_in_cents + tax_in_cents + + charge = Stripe::Charge.create( + :amount => total_in_cents, + :currency => "usd", + :customer => current_user.stripe_customer_id, + :description => purchase.description(lesson_booking) + ) + + price_info = {} + price_info[:subtotal_in_cents] = subtotal_in_cents + price_info[:tax_in_cents] = tax_in_cents + price_info[:total_in_cents] = total_in_cents + price_info[:currency] = 'USD' + price_info[:charge_id] = charge.id + price_info + end + + # this method will either return a valid sale, or throw a RecurlyClientError or ActiveRecord validation error (save! failed) # it may return an nil sale if the JamTrack(s) specified by the shopping carts are already owned def self.order_jam_tracks(current_user, shopping_carts) @@ -338,7 +408,6 @@ module JamRuby end - if account # ask the shopping cart to create the correct Recurly adjustment attributes for a JamTrack adjustments = shopping_cart.create_adjustment_attributes(current_user) @@ -454,6 +523,10 @@ module JamRuby sale_type == JAMTRACK_SALE end + def is_lesson_sale? + sale_type == LESSON_SALE + end + def self.create_jam_track_sale(user) sale = Sale.new sale.user = user @@ -463,6 +536,15 @@ module JamRuby sale end + def self.create_lesson_sale(user) + sale = Sale.new + sale.user = user + sale.sale_type = LESSON_SALE # gift cards and jam tracks are sold with this type of sale + sale.order_total = 0 + sale.save + sale + end + # this checks just jamtrack sales appropriately def self.check_integrity_of_jam_track_sales Sale.select([:total, :voided]).find_by_sql( diff --git a/ruby/lib/jam_ruby/models/sale_line_item.rb b/ruby/lib/jam_ruby/models/sale_line_item.rb index e105f966b..91365820a 100644 --- a/ruby/lib/jam_ruby/models/sale_line_item.rb +++ b/ruby/lib/jam_ruby/models/sale_line_item.rb @@ -5,6 +5,7 @@ module JamRuby JAMCLOUD = 'JamCloud' JAMTRACK = 'JamTrack' GIFTCARD = 'GiftCardType' + LESSON = 'LessonPackageType' belongs_to :sale, class_name: 'JamRuby::Sale' belongs_to :jam_track, class_name: 'JamRuby::JamTrack' @@ -13,7 +14,7 @@ module JamRuby belongs_to :affiliate_referral, class_name: 'JamRuby::AffiliatePartner', foreign_key: :affiliate_referral_id has_many :recurly_transactions, class_name: 'JamRuby::RecurlyTransactionWebHook', inverse_of: :sale_line_item, foreign_key: 'subscription_id', primary_key: 'recurly_subscription_uuid' - validates :product_type, inclusion: {in: [JAMBLASTER, JAMCLOUD, JAMTRACK, GIFTCARD]} + validates :product_type, inclusion: {in: [JAMBLASTER, JAMCLOUD, JAMTRACK, GIFTCARD, LESSON]} validates :unit_price, numericality: {only_integer: false} validates :quantity, numericality: {only_integer: true} validates :free, numericality: {only_integer: true} @@ -81,6 +82,14 @@ module JamRuby line_item end + # in a shopping-cart less world (ios purchase), let's reuse as much logic as possible + def self.create_from_lesson_package(current_user, sale, lesson_package_type) + shopping_cart = ShoppingCart.create(current_user, lesson_package_type, 1) + line_item = create_from_shopping_cart(sale, shopping_cart, nil, nil, nil) + shopping_cart.destroy + line_item + end + def self.create_from_shopping_cart(sale, shopping_cart, recurly_subscription_uuid, recurly_adjustment_uuid, recurly_adjustment_credit_uuid) product_info = shopping_cart.product_info diff --git a/ruby/lib/jam_ruby/models/shopping_cart.rb b/ruby/lib/jam_ruby/models/shopping_cart.rb index fb531c2bd..d531daf8c 100644 --- a/ruby/lib/jam_ruby/models/shopping_cart.rb +++ b/ruby/lib/jam_ruby/models/shopping_cart.rb @@ -115,6 +115,10 @@ module JamRuby cart_type == GiftCardType::PRODUCT_TYPE end + def is_lesson? + cart_type == LessonPackageType::PRODUCT_TYPE + end + # returns an array of adjustments for the shopping cart def create_adjustment_attributes(current_user) raise "not a jam track or gift card" unless is_jam_track? || is_gift_card? diff --git a/ruby/lib/jam_ruby/models/teacher.rb b/ruby/lib/jam_ruby/models/teacher.rb index 8b6a8e394..22c9b86cb 100644 --- a/ruby/lib/jam_ruby/models/teacher.rb +++ b/ruby/lib/jam_ruby/models/teacher.rb @@ -235,6 +235,21 @@ module JamRuby teacher end + def booking_price(length, single) + price = nil + if single + price = self["price_per_lesson_#{lesson_length}_cents"] + else + price = self["price_per_month_#{lesson_length}_cents"] + end + + if !price.nil? + price.to_i + else + price + end + end + def offer_pricing unless prices_per_lesson.present? || prices_per_month.present? errors.add(:offer_pricing, "Must choose to price per lesson or per month") diff --git a/ruby/lib/jam_ruby/models/user.rb b/ruby/lib/jam_ruby/models/user.rb index f0743a4de..a13e51fb0 100644 --- a/ruby/lib/jam_ruby/models/user.rb +++ b/ruby/lib/jam_ruby/models/user.rb @@ -170,6 +170,9 @@ module JamRuby has_many :jam_track_rights, :class_name => "JamRuby::JamTrackRight", :foreign_key => "user_id" has_many :purchased_jam_tracks, :through => :jam_track_rights, :class_name => "JamRuby::JamTrack", :source => :jam_track, :order => :created_at + # lessons + has_many :lesson_purchases, :class_name => "JamRuby::LessonPackagePurchase", :foreign_key => "user_id", inverse_of: :user + # Shopping carts has_many :shopping_carts, :class_name => "JamRuby::ShoppingCart" @@ -1841,6 +1844,62 @@ module JamRuby remaining_test_drives > 0 end + def fetch_stripe_customer + Stripe::Customer.retrieve(stripe_customer_id) + end + + # if the user already has a stripe customer, then keep it synced. otherwise create it + def sync_stripe_customer + if self.stripe_customer_id + # we already have a customer for this user; re-use it + customer = fetch_stripe_customer + + if customer.email.nil? || customer.email.downcase != email.downcase + customer.email = email + customer.save + end + else + customer = Stripe::Customer.create( + :description => "JK ID: #{id}", + :source => stripe_token, + :email => email) + end + self.stripe_customer_id = customer.id + User.where(id: id).update_all(stripe_customer_id: customer.id) + + customer + end + def card_approved(token, zip) + + approved_lesson = nil + User.transaction do + self.stripe_token = token + self.stripe_zip_code = zip + customer = sync_stripe_customer + self.stripe_customer_id = customer.id + if self.save + # we can also 'unlock' any booked sessions that still need to be done so + LessonBooking.unprocessed(self).each do |lesson| + approved_lesson = lesson.card_approved + end + end + end + approved_lesson + end + + def payment_update(params) + lesson = nil + test_drive = nil + User.transaction do + lesson = card_approved(params[:token], params[:zip]) + if params[:test_drive] + test_drive = Sale.purchase_test_drive(self) + end + end + + {lesson: lesson, test_drive: test_drive} + end + private def create_remember_token self.remember_token = SecureRandom.urlsafe_base64 diff --git a/ruby/spec/factories.rb b/ruby/spec/factories.rb index b67d87169..2123e2508 100644 --- a/ruby/spec/factories.rb +++ b/ruby/spec/factories.rb @@ -95,6 +95,11 @@ FactoryGirl.define do connection = FactoryGirl.create(:connection, :user => user, :music_session => active_music_session) end end + factory :teacher_user do + after(:create) do |user, evaluator| + teacher = FactoryGirl.create(:teacher, user: user) + end + end end factory :teacher, :class => JamRuby::Teacher do @@ -149,6 +154,9 @@ FactoryGirl.define do end factory :music_session, :class => JamRuby::MusicSession do + ignore do + student nil + end sequence(:name) { |n| "Music Session #{n}" } sequence(:description) { |n| "Music Session Description #{n}" } fan_chat true @@ -910,6 +918,7 @@ FactoryGirl.define do sequence(:sibling_key ) { |n| "sibling_key#{n}" } end + factory :lesson_booking_slot, class: 'JamRuby::LessonBookingSlot' do factory :lesson_booking_slot_single do slot_type 'single' @@ -917,6 +926,7 @@ FactoryGirl.define do day_of_week nil hour 12 minute 30 + timezone 'UTC' end factory :lesson_booking_slot_recurring do @@ -925,8 +935,47 @@ FactoryGirl.define do day_of_week 0 hour 12 minute 30 + timezone 'UTC' end end + + factory :lesson_booking, class: 'JamRuby::LessonBooking' do + association :user, factory: :user + association :teacher, factory: :teacher_user + card_presumed_ok false + sent_notices false + recurring false + lesson_length 30 + lesson_type JamRuby::LessonBooking::LESSON_TYPE_FREE + payment_style JamRuby::LessonBooking::PAYMENT_STYLE_ELSEWHERE + description "Oh my goodness!" + status JamRuby::LessonBooking::STATUS_REQUESTED + lesson_booking_slots [FactoryGirl.build(:lesson_booking_slot_single), FactoryGirl.build(:lesson_booking_slot_single)] + end + + factory :lesson_package_purchase, class: "JamRuby::LessionPackagePurchase" do + lesson_package_type { JamRuby::LessonPackageType.single } + association :user, factory: :user + association :teacher, factory: :teacher + price 30.00 + end + + + factory :lesson_session, class: 'JamRuby::LessonSession' do + + ignore do + student nil + end + + music_session {FactoryGirl.create(:music_session, creator: student)} + lesson_booking {FactoryGirl.create(:lesson_booking, user: student, teacher: teacher)} + association :teacher, factory: :teacher_user + lesson_type JamRuby::LessonSession::LESSON_TYPE_SINGLE + duration 30 + price 49.99 + #teacher_complete true + #student_complete true + end factory :ip_blacklist, class: "JamRuby::IpBlacklist" do remote_ip '1.1.1.1' diff --git a/ruby/spec/jam_ruby/models/lesson_booking_spec.rb b/ruby/spec/jam_ruby/models/lesson_booking_spec.rb index 62c19df41..9bd9706c7 100644 --- a/ruby/spec/jam_ruby/models/lesson_booking_spec.rb +++ b/ruby/spec/jam_ruby/models/lesson_booking_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' # collissions with teacher's schedule? describe LessonBooking do - let(:user) {FactoryGirl.create(:user, stored_credit_card: true, remaining_free_lessons: 1, remaining_test_drives: 1)} + let(:user) {FactoryGirl.create(:user, stored_credit_card: false, remaining_free_lessons: 1, remaining_test_drives: 1)} let(:teacher) {FactoryGirl.create(:teacher)} let(:teacher_user) {teacher.user} let(:lesson_booking_slot_single1) {FactoryGirl.build(:lesson_booking_slot_single)} @@ -33,6 +33,16 @@ describe LessonBooking do user.reload user.remaining_free_lessons.should eq 0 user.remaining_test_drives.should eq 1 + + booking.card_presumed_ok.should eq false + booking.sent_notices.should eq false + + user.card_approved(create_stripe_token, '78759') + user.save! + booking.reload + booking.sent_notices.should eq true + booking.card_presumed_ok.should eq true + end it "allows long message to flow through chat" do @@ -55,7 +65,7 @@ describe LessonBooking do booking = LessonBooking.book_free(user, teacher_user, valid_single_slots, "Hey I've heard of you before.") booking.errors.any?.should be true - booking.errors[:user].should eq ["has no remaining free lessons"] + booking.errors[:user].should eq ["have no remaining free lessons"] ChatMessage.count.should eq 1 end @@ -65,8 +75,7 @@ describe LessonBooking do user.save! booking = LessonBooking.book_free(user, teacher_user, valid_single_slots, "Hey I've heard of you before.") - booking.errors.any?.should be true - booking.errors[:user].should eq ["has no credit card stored"] + booking.errors.any?.should be false end it "must have 2 lesson booking slots" do @@ -127,7 +136,7 @@ describe LessonBooking do booking = LessonBooking.book_test_drive(user, teacher_user, valid_single_slots, "Hey I've heard of you before.") booking.errors.any?.should be true - booking.errors[:user].should eq ["has no remaining test drives"] + booking.errors[:user].should eq ["have no remaining test drives"] ChatMessage.count.should eq 1 end @@ -221,13 +230,14 @@ describe LessonBooking do ChatMessage.count.should eq 2 end - it "prevents user without stored credit card" do + it "does not prevent user without a stored credit card" do user.stored_credit_card = false user.save! booking = LessonBooking.book_normal(user, teacher_user, valid_recurring_slots, "Hey I've heard of you before.", true, LessonBooking::PAYMENT_STYLE_WEEKLY, 60) - booking.errors.any?.should be true - booking.errors[:user].should eq ["has no credit card stored"] + booking.errors.any?.should be false + booking.card_presumed_ok.should eq false + booking.sent_notices.should eq false end diff --git a/ruby/spec/jam_ruby/models/lesson_package_purchase_spec.rb b/ruby/spec/jam_ruby/models/lesson_package_purchase_spec.rb index ab05738d1..485fd4810 100644 --- a/ruby/spec/jam_ruby/models/lesson_package_purchase_spec.rb +++ b/ruby/spec/jam_ruby/models/lesson_package_purchase_spec.rb @@ -3,9 +3,10 @@ require 'spec_helper' describe LessonPackagePurchase do let(:user) {FactoryGirl.create(:user)} + let(:lesson_booking) {FactoryGirl.create(:lesson_booking)} it "creates" do - purchase = LessonPackagePurchase.create(user, LessonPackageType.single_free) + purchase = LessonPackagePurchase.create(user, LessonPackageType.single_free, lesson_booking) purchase.valid?.should be_true end end diff --git a/ruby/spec/jam_ruby/models/lesson_session_spec.rb b/ruby/spec/jam_ruby/models/lesson_session_spec.rb new file mode 100644 index 000000000..3c07eaa2f --- /dev/null +++ b/ruby/spec/jam_ruby/models/lesson_session_spec.rb @@ -0,0 +1,39 @@ +require 'spec_helper' + +describe LessonSession do + + let(:user) {FactoryGirl.create(:user, stored_credit_card: false, remaining_free_lessons: 1, remaining_test_drives: 1)} + let(:teacher) {FactoryGirl.create(:teacher_user)} + + let(:lesson_session) {FactoryGirl.create(:lesson_session, student: user, teacher: teacher)} + let(:lesson_session2) {FactoryGirl.create(:lesson_session, student: user, teacher: teacher)} + describe "index" do + it "finds single lesson as student" do + + # just sanity check that the lesson_session Factory is doing what it should + lesson_session.music_session.creator.should eql lesson_session.lesson_booking.user + lesson_session.lesson_booking.teacher.should eql teacher + + query = LessonSession.index(user)[:query] + query.length.should eq 1 + + # make sure some random nobody can see this lesson session + query = LessonSession.index(FactoryGirl.create(:user))[:query] + query.length.should eq 0 + end + + it "finds single lesson as teacher" do + + # just sanity check that the lesson_session Factory is doing what it should + lesson_session.music_session.creator.should eql lesson_session.lesson_booking.user + lesson_session.lesson_booking.teacher.should eql teacher + + query = LessonSession.index(teacher, {as_teacher: true})[:query] + query.length.should eq 1 + + # make sure some random nobody can see this lesson session + query = LessonSession.index(FactoryGirl.create(:user), {as_teacher: true})[:query] + query.length.should eq 0 + end + end +end diff --git a/ruby/spec/jam_ruby/models/sale_spec.rb b/ruby/spec/jam_ruby/models/sale_spec.rb index fc89145cb..42814de4b 100644 --- a/ruby/spec/jam_ruby/models/sale_spec.rb +++ b/ruby/spec/jam_ruby/models/sale_spec.rb @@ -567,6 +567,84 @@ describe Sale do end end + describe "purchase_test_drive" do + + it "book single" do + + end + + it "book recurring, single" do + + end + + it "book recurring, monthly" do + + end + + it "can succeed" do + user.stripe_token = create_stripe_token + user.save! + + sale = Sale.purchase_test_drive(user) + + sale.reload + + sale.stripe_charge_id.should_not be_nil + sale.recurly_tax_in_cents.should be 0 + sale.recurly_total_in_cents.should eql 4999 + sale.recurly_subtotal_in_cents.should eql 4999 + sale.recurly_currency.should eql 'USD' + line_item = sale.sale_line_items[0] + line_item.quantity.should eql 1 + line_item.product_type.should eql SaleLineItem::LESSON + line_item.product_id.should eq LessonPackageType.test_drive.id + + + user.reload + user.stripe_customer_id.should_not be nil + user.lesson_purchases.length.should eql 1 + user.remaining_test_drives.should eql 4 + lesson_purchase = user.lesson_purchases[0] + lesson_purchase.price.should eql 49.99 + lesson_purchase.lesson_package_type.is_test_drive?.should eql true + + customer = Stripe::Customer.retrieve(user.stripe_customer_id) + customer.email.should eql user.email + end + + it "can succeed with tax" do + user.stripe_token = create_stripe_token + user.stripe_zip_code = '78759' + user.save! + + sale = Sale.purchase_test_drive(user) + + sale.reload + + sale.stripe_charge_id.should_not be_nil + sale.recurly_tax_in_cents.should be (4999 * 0.0825).round + sale.recurly_total_in_cents.should eql 4999 + (4999 * 0.0825).round + sale.recurly_subtotal_in_cents.should eql 4999 + sale.recurly_currency.should eql 'USD' + line_item = sale.sale_line_items[0] + line_item.quantity.should eql 1 + line_item.product_type.should eql SaleLineItem::LESSON + line_item.product_id.should eq LessonPackageType.test_drive.id + + + user.reload + user.stripe_customer_id.should_not be nil + user.lesson_purchases.length.should eql 1 + user.remaining_test_drives.should eql 4 + lesson_purchase = user.lesson_purchases[0] + lesson_purchase.price.should eql 49.99 + lesson_purchase.lesson_package_type.is_test_drive?.should eql true + + customer = Stripe::Customer.retrieve(user.stripe_customer_id) + customer.email.should eql user.email + end + end + describe "check_integrity_of_jam_track_sales" do let(:user) { FactoryGirl.create(:user) } diff --git a/ruby/spec/jam_ruby/models/user_spec.rb b/ruby/spec/jam_ruby/models/user_spec.rb index 89abe6e16..ff2753057 100644 --- a/ruby/spec/jam_ruby/models/user_spec.rb +++ b/ruby/spec/jam_ruby/models/user_spec.rb @@ -760,6 +760,37 @@ describe User do end end + describe "sync_stripe_customer" do + let(:user) { FactoryGirl.create(:user) } + let(:token1) { create_stripe_token } + let(:token2) { create_stripe_token(2018) } + + # possible Stripe::InvalidRequestError + it "reuses user on card update" do + user.stripe_customer_id.should be_nil + user.payment_update({stripe_token: token1}) + user.reload + user.stripe_customer_id.should_not be_nil + customer1 = user.stripe_customer_id + + # let's change email address too + user.email = 'unique+1@jamkazam.com' + user.save! + + token2.should_not eql token1 + user.payment_update({stripe_token: token2}) + user.reload + user.stripe_customer_id.should_not be_nil + customer2 = user.stripe_customer_id + + customer1.should eql customer2 + # double-check that the stripe customer db record got it's email synced + customer = user.fetch_stripe_customer + customer.email.should eql 'unique+1@jamkazam.com' + + end + end + =begin describe "update avatar" do diff --git a/ruby/spec/mailers/render_emails_spec.rb b/ruby/spec/mailers/render_emails_spec.rb index dfc84cef3..e1d554f06 100644 --- a/ruby/spec/mailers/render_emails_spec.rb +++ b/ruby/spec/mailers/render_emails_spec.rb @@ -39,6 +39,25 @@ describe "RenderMailers", :slow => true do it { @filename="text_message"; UserMailer.text_message(user, user2.id, user2.name, user2.resolved_photo_url, 'Get online!!').deliver } it { @filename="friend_request"; UserMailer.friend_request(user, 'So and so has sent you a friend request.', friend_request.id).deliver} end + + describe "student/teacher" do + let(:teacher) { u = FactoryGirl.create(:teacher); u.user } + let(:user) { FactoryGirl.create(:user) } + + it "teacher_lesson_request" do + @filename = "teacher_lesson_request" + + lesson_booking = FactoryGirl.create(:lesson_booking) + UserMailer.teacher_lesson_request(lesson_booking).deliver + end + + it "student_lesson_request" do + @filename = "student_lesson_request" + + lesson_booking = FactoryGirl.create(:lesson_booking) + UserMailer.student_lesson_request(lesson_booking).deliver + end + end end describe "InvitedUserMailer emails" do diff --git a/ruby/spec/spec_helper.rb b/ruby/spec/spec_helper.rb index 0f28a82de..45efd9da8 100644 --- a/ruby/spec/spec_helper.rb +++ b/ruby/spec/spec_helper.rb @@ -60,6 +60,8 @@ CarrierWave.configure do |config| config.enable_processing = false end +Stripe.api_key = "sk_test_OkjoIF7FmdjunyNsdVqJD02D" + #uncomment the following line to use spork with the debugger #require 'spork/ext/ruby-debug' diff --git a/ruby/spec/support/utilities.rb b/ruby/spec/support/utilities.rb index 193f5ed76..1ca51cc02 100644 --- a/ruby/spec/support/utilities.rb +++ b/ruby/spec/support/utilities.rb @@ -258,6 +258,7 @@ def app_config true end + private def audiomixer_workspace_path @@ -328,3 +329,14 @@ def friend(user1, user2) FactoryGirl.create(:friendship, user: user1, friend: user2) FactoryGirl.create(:friendship, user: user2, friend: user1) end + +def create_stripe_token(exp_month = 2017) + Stripe::Token.create( + :card => { + :number => "4111111111111111", + :exp_month => 2, + :exp_year => exp_month, + :cvc => "314" + }, + ).id +end \ No newline at end of file diff --git a/web/Gemfile b/web/Gemfile index a2054a95c..0a59a5a3a 100644 --- a/web/Gemfile +++ b/web/Gemfile @@ -59,7 +59,6 @@ gem 'carmen' gem 'carrierwave', '0.9.0' gem 'carrierwave_direct' gem 'fog' -gem 'jquery-payment-rails' gem 'haml-rails' gem 'unf' #optional fog dependency gem 'devise', '3.3.0' #3.4.0 causes uninitialized constant ActionController::Metal (NameError) @@ -89,12 +88,14 @@ gem 'htmlentities' gem 'sanitize' gem 'recurly' #gem 'guard', '2.7.3' -gem 'influxdb', '0.1.8' -gem 'influxdb-rails', '0.1.10' +gem 'influxdb' #, '0.1.8' +gem 'influxdb-rails'# , '0.1.10' gem 'sitemap_generator' gem 'bower-rails', "~> 0.9.2" gem 'react-rails', '~> 1.0' gem 'sendgrid_toolkit', '>= 1.1.1' +gem 'stripe' +gem 'zip-codes' #gem "browserify-rails", "~> 0.7" source 'https://rails-assets.org' do diff --git a/web/app/assets/javascripts/application.js b/web/app/assets/javascripts/application.js index 019ddfcda..6b8e803af 100644 --- a/web/app/assets/javascripts/application.js +++ b/web/app/assets/javascripts/application.js @@ -39,6 +39,7 @@ //= require jquery.payment //= require jquery.visible //= require jquery.jstarbox +//= require jquery.inputmask //= require fingerprint2.min //= require ResizeSensor //= require classnames diff --git a/web/app/assets/javascripts/jam_rest.js b/web/app/assets/javascripts/jam_rest.js index 5138ee5a5..031e5cb8c 100644 --- a/web/app/assets/javascripts/jam_rest.js +++ b/web/app/assets/javascripts/jam_rest.js @@ -2142,6 +2142,25 @@ }); } + function submitStripe(options) { + return $.ajax({ + type: "POST", + url: '/api/stripe', + dataType: "json", + contentType: 'application/json', + data: JSON.stringify(options) + }) + } + + function getLessonSessions(options) { + return $.ajax({ + type: "GET", + url: "/api/lesson_sessions?" + $.param(query), + dataType: "json", + contentType: 'application/json' + }); + } + function initialize() { return self; } @@ -2335,6 +2354,8 @@ this.portOverCarts = portOverCarts; this.bookLesson = bookLesson; this.getUnprocessedLesson = getUnprocessedLesson; + this.submitStripe = submitStripe; + this.getLessonSessions = getLessonSessions; return this; }; })(window,jQuery); diff --git a/web/app/assets/javascripts/react-components/BookLessonFree.js.jsx.coffee b/web/app/assets/javascripts/react-components/BookLessonFree.js.jsx.coffee index c54a98f74..2f337ff57 100644 --- a/web/app/assets/javascripts/react-components/BookLessonFree.js.jsx.coffee +++ b/web/app/assets/javascripts/react-components/BookLessonFree.js.jsx.coffee @@ -115,6 +115,7 @@ UserStore = context.UserStore options.payment_style = 'elsewhere' options.lesson_type = 'single-free' options.slots = [@getSlotData(0), @getSlotData(1)] + options.timezone = Ajstz.determine().name() description = @root.find('textarea.user-description').val() if description == '' description == null diff --git a/web/app/assets/javascripts/react-components/FreeLessonPayment.js.jsx.coffee b/web/app/assets/javascripts/react-components/FreeLessonPayment.js.jsx.coffee deleted file mode 100644 index e661d746f..000000000 --- a/web/app/assets/javascripts/react-components/FreeLessonPayment.js.jsx.coffee +++ /dev/null @@ -1,139 +0,0 @@ -context = window -rest = context.JK.Rest() -logger = context.JK.logger - -UserStore = context.UserStore - -@FreeLessonPayment = React.createClass({ - - mixins: [ - Reflux.listenTo(AppStore, "onAppInit"), - Reflux.listenTo(UserStore, "onUserChanged") - ] - - onAppInit: (@app) -> - @app.bindScreen('jamclass/free-lesson-payment', - {beforeShow: @beforeShow, afterShow: @afterShow, beforeHide: @beforeHide}) - - onUserChanged: (userState) -> - @setState({user: userState?.user}) - - componentDidMount: () -> - @root = $(@getDOMNode()) - - getInitialState: () -> - {user: null, - lesson: null, - updating: false} - - beforeHide: (e) -> - @resetErrors() - - beforeShow: (e) -> - - afterShow: (e) -> - @resetState() - @resetErrors() - @setState({updating:true}) - rest.getUnprocessedLesson().done((response) => @unprocessLoaded(response)).fail((jqXHR) => @failedBooking(jqXHR)) - - resetState: () -> - @setState({update: false, lesson: null}) - - unprocessLoaded: (response) -> - @setState({updating: false}) - @setState({lesson: response}) - - failedUnprocessLoad: (jqXHR) -> - @setState({updating: false}) - @app.layout.notify({title: 'Unable to load lesson', text: 'Please attempt to book a free lesson first or refresh this page.'}) - - onBack: (e) -> - e.preventDefault() - - - onSubmit: (e) -> - e.preventDefault() - - - render: () -> - - disabled = @state.updating - - if @state.updating - photo_url = '/assets/shared/avatar_generic.png' - name = 'Loading ...' - teacherDetails = `
-
- -
- {name} -
` - else - if @state.lesson? - photo_url = @state.lesson.teacher.photo_url - name = @state.lesson.teacher.name - if !photo_url? - photo_url = '/assets/shared/avatar_generic.png' - teacherDetails = `
-
- -
- {name} -
` - - if lesson.lesson_type == 'single-free' - bookingInfo = `

You are booking a single free {this.state.lesson.lesson_length}-minute lesson.

` - bookingDetail = `

To book this lesson, you will need to enter your credit card information. - You will absolutely not be charged for this free lesson, and you have no further commitment to purchase - anything. We have to collect a credit card to prevent abuse by some users who would otherwise set up - multiple free accounts to get multiple free lessons. -
- -

jamclass - policies
-

` - else if lesson.lesson_type == 'test-drive' - bookingInfo = `

This is not the correct page to pay for TestDrive.

` - bookingDetail = '' - else if lesson.lesson_type == 'paid' - bookingInfo = `

This is not the correct page for entering pay for a normal lesson.

` - bookingDetail = '' - - `
-
-

enter card info

Your card wil not be charged.
See explanation to the right.
- -
- - -
-
- - -
-
- - -
- -
- - -
-
-
- {teacherDetails} -
- {bookingInfo} - - {bookingDetail} -
-
-
- BACKSUBMIT CARD INFORMATION -
- -
` - -}) \ No newline at end of file diff --git a/web/app/assets/javascripts/react-components/JamClassStudentScreen.js.jsx.coffee b/web/app/assets/javascripts/react-components/JamClassStudentScreen.js.jsx.coffee new file mode 100644 index 000000000..5657d5ef7 --- /dev/null +++ b/web/app/assets/javascripts/react-components/JamClassStudentScreen.js.jsx.coffee @@ -0,0 +1,154 @@ +context = window +rest = context.JK.Rest() +logger = context.JK.logger + +UserStore = context.UserStore + +@JamClassStudentScreen = React.createClass({ + + mixins: [ + @ICheckMixin, + Reflux.listenTo(AppStore, "onAppInit"), + Reflux.listenTo(UserStore, "onUserChanged") + ] + + onAppInit: (@app) -> + @app.bindScreen('jamclass', + {beforeShow: @beforeShow, afterShow: @afterShow, beforeHide: @beforeHide}) + + onUserChanged: (userState) -> + @setState({user: userState?.user}) + + componentDidMount: () -> + + componentDidUpdate: () -> + + getInitialState: () -> + { + user: null, + } + + beforeHide: (e) -> + @resetErrors() + + beforeShow: (e) -> + + afterShow: (e) -> + @setState({updating: true}) + rest.getLessonSessions().done((response) => @jamClassLoaded(response)).fail((jqXHR) => @failedJamClassLoad(jqXHR)) + + resetState: () -> + @setState({updating: false, lesson: null}) + + jamClassLoaded: (response) -> + @setState({updating: false}) + @setState({summary: response}) + + failedJamClassLoad: (jqXHR) -> + @setState({updating: false}) + @setState({summary: response}) + if jqXHR.status == 404 + @app.layout.notify({title: "Unable to load JamClass info", text: "Try refreshing the web page"}) + + render: () -> + disabled = @state.updating + + classes = [] + if @state.updating + classes = [`Loading...`] + else + + `
+
+
+

my lessons

+ + + + + + + + + + + + {classes} + +
TEACHERDATE/TIMESTATUSACTIONS
+ +
+ Don't miss a lesson! Integrate your lessons into your calendar. +
+
+
+

search teachers

+ +

JamClass instructors are each individually screened to ensure that they are highly qualified music + teachers, + equipped to teach effectively online, and background checked. +

+ +
+ SEARCH TEACHERS +
+
+
+
+
+

learn about jamclass

+ +

+ JamClass is the best way to make music lessons, offering significant advantadges over both traditional + face-to-face lessons + and online skype lessons. +

+ +
+ LEARN MORE +
+
+
+

sign up for testdrive

+ +

+ There are two awesome, painless ways to get started with JamClass. +

+ +

+ Sign up for TestDrive and take 4 full 30-minute lessons - one each from 4 different instructors - for just + $49.99. + You wouldn't marry the first person you date, right? Find the best teacher for you. It's the most important + factor in the success for your lessons! +

+ +

+ Or take one JamClass lesson free. It's on us! We're confident you'll take more. +

+ +

+ Sign up for TestDrive using the button below, or to take one free lesson, search our teachers, and click the + Book Free Lesson on your favorite. +

+ +
+ SIGN UP FOR TESTDRIVE + or + SEARCH TEACHERS +
+
+
+

get ready for your first lesson

+ +

Be sure to set up and test the JamKazam app in an online music session a few days before + your first lesson! We're happy to help, and we'll even get in a session with you to make sure everything + is working properly. Ping us at support@jamkazam.com anytime, and + read our + JamClass user guide to learn how to use all the lesson features. +

+
+
+
+
` + +}) \ No newline at end of file diff --git a/web/app/assets/javascripts/react-components/LessonPayment.js.jsx.coffee b/web/app/assets/javascripts/react-components/LessonPayment.js.jsx.coffee index cf04951d7..5be92e02e 100644 --- a/web/app/assets/javascripts/react-components/LessonPayment.js.jsx.coffee +++ b/web/app/assets/javascripts/react-components/LessonPayment.js.jsx.coffee @@ -7,23 +7,36 @@ UserStore = context.UserStore @LessonPayment = React.createClass({ mixins: [ + @ICheckMixin, Reflux.listenTo(AppStore, "onAppInit"), Reflux.listenTo(UserStore, "onUserChanged") ] onAppInit: (@app) -> - @app.bindScreen('jamclass/payment', + @app.bindScreen('jamclass/lesson-payment', {beforeShow: @beforeShow, afterShow: @afterShow, beforeHide: @beforeHide}) onUserChanged: (userState) -> @setState({user: userState?.user}) componentDidMount: () -> + @checkboxes = [{selector: 'input.billing-address-in-us', stateKey: 'billingInUS'}] + @root = $(@getDOMNode()) + @root.find('input.expiration').payment('formatCardExpiry') + @root.find("input.card-number").payment('formatCardNumber') + @root.find("input.cvv").payment('formatCardCVC') + @iCheckify() + componentDidUpdate: () -> + @iCheckify() getInitialState: () -> - {user: null, - lesson: null} + { + user: null, + lesson: null, + updating: false, + billingInUS: true + } beforeHide: (e) -> @resetErrors() @@ -31,15 +44,165 @@ UserStore = context.UserStore beforeShow: (e) -> afterShow: (e) -> + @resetState() @resetErrors() - rest.getUnprocessedLesson().done((response) => @booked(response)).fail((jqXHR) => @failedBooking(jqXHR)) + @setState({updating: true}) + rest.getUnprocessedLesson().done((response) => @unprocessLoaded(response)).fail((jqXHR) => @failedBooking(jqXHR)) + + resetErrors: () -> + @setState({ccError: null, cvvError: null, expiryError: null, billingInUSError: null, zipCodeError: null}) + + checkboxChanged: (e) -> + checked = $(e.target).is(':checked') + + @setState({billingInUS: checked}) + + resetState: () -> + @setState({updating: false, lesson: null}) + + unprocessLoaded: (response) -> + @setState({updating: false}) + @setState({lesson: response}) + + failedBooking: (jqXHR) -> + @setState({updating: false}) + @setState({lesson: null}) + if jqXHR.status == 404 + # no unprocessed lessons. That's arguably OK; the user is just going to enter their info up front. + console.log("nothing") + + failedUnprocessLoad: (jqXHR) -> + @setState({updating: false}) + @app.layout.notify({ + title: 'Unable to load lesson', + text: 'Please attempt to book a free lesson first or refresh this page.' + }) + + onBack: (e) -> + e.preventDefault() + + onSubmit: (e) -> + @resetErrors() + + e.preventDefault() + + if !window.Stripe? + @app.layout.notify({ + title: 'Payment System Not Loaded', + text: "Please refresh this page and try to enter your info again. Sorry for the inconvenience!" + }) + else + ccNumber = @root.find('input.card-number').val() + expiration = @root.find('input.expiration').val() + cvv = @root.find('input.cvv').val() + inUS = @root.find('input.billing-address-in-us').is(':checked') + zip = @root.find('input.zip').val() + + error = false + if !$.payment.validateCardNumber(ccNumber) + @setState({ccError: true}) + error = true + + bits = expiration.split('/') + + if bits.length == 2 + month = bits[0].trim(); + year = bits[1].trim() + + month = new Number(month) + year = new Number(year) + + if year < 2000 + year += 2000 + + if !$.payment.validateCardExpiry(month, year) + @setState({expiryError: true}) + error = true + else + @setState({expiryError: true}) + error = true + + + cardType = $.payment.cardType(ccNumber) + + if !$.payment.validateCardCVC(cvv, cardType) + @setState({cvvError: true}) + error = true + + if inUS && (!zip? || zip == '') + @setState({zipCodeError: true}) + + if error + return + + data = { + number: ccNumber, + cvc: cvv, + exp_month: month, + exp_year: year, + } + + window.Stripe.card.createToken(data, (status, response) => (@stripeResponseHandler(status, response))); + + stripeResponseHandler: (status, response) -> + console.log("response", response) + + + if response.error + if response.error.code == "invalid_number" + @setState({ccError: true, cvvError: null, expiryError: null}) + else if response.error.code == "invalid_cvc" + @setState({ccError: null, cvvError: true, expiryError: null}) + else if response.error.code == "invalid_expiry_year" || response.error.code == "invalid_expiry_month" + @setState({ccError: null, cvvError: null, expiryError: true}) + else + if this.state.billingInUS + zip = @root.find('input.zip').val() + + rest.submitStripe({ + token: response.id, + zip: zip, + test_drive: @state.lesson?.lesson_type == 'test-drive' + }).done((response) => @stripeSubmitted(response)).fail((jqXHR) => @stripeSubmitFailure(jqXHR)) + + stripeSubmitted: (response) -> + logger.debug("stripe submitted", response) + + # if the response has a lesson, take them there + if response.lesson?.id? + context.Banner.showNotice({ + title: "Lesson Requested", + text: "The teacher has been notified of your lesson request, and should respond soon.

We've taken you automatically to the page for this request, and sent an email to you with a link here as well. All communication with the teacher will show up on this page and in email." + }) + window.location = "/client#/jamclass/lesson-request/" + response.lesson.id + else if response.test_drive? + context.Banner.showNotice({ + title: "Test Drive Purchased", + text: "You now have 4 lessons that you can take with 4 different teachers.

We've taken you automatically to the Teacher Search screen, so you can search for teachers right for you." + }) + window.location = "/client#/teachers/search" + else + window.location = "/client#/teachers/search" + + stripeSubmitFailure: (jqXHR) -> + @app.layout.notifyServerError(jqXHR, 'Credit Card Not Stored') render: () -> + disabled = @state.updating if @state.updating + photo_url = '/assets/shared/avatar_generic.png' + name = 'Loading ...' + teacherDetails = `
+
+ +
+ {name} +
` else if @state.lesson? photo_url = @state.lesson.teacher.photo_url + name = @state.lesson.teacher.name if !photo_url? photo_url = '/assets/shared/avatar_generic.png' teacherDetails = `
@@ -50,50 +213,149 @@ UserStore = context.UserStore
` if lesson.lesson_type == 'single-free' - bookingInfo = `

This is not the correct page to pay for TestDrive.

` + header = `

enter card info

+ +
Your card wil not be charged.
See explanation to the right.
+
` + bookingInfo = `

You are booking a single free {this.state.lesson.lesson_length}-minute lesson.

` + bookingDetail = `

To book this lesson, you will need to enter your credit card information. + You will absolutely not be charged for this free lesson, and you have no further commitment to purchase + anything. We have to collect a credit card to prevent abuse by some users who would otherwise set up + multiple free accounts to get multiple free lessons. +
+ +

jamclass + policies
+

` else if lesson.lesson_type == 'test-drive' - bookingInfo = `

This is not the correct page to pay for TestDrive.

` + header = `

enter payment info for test drive

` + bookingInfo = `

` + bookingDetail = `

You are purchasing the TestDrive package of JamClass by JamKazam. This purchase entitles + you to take 4 private online music lessons - 1 each from 4 different instructors in the JamClass instructor + community. +
+ + jamclass + policies +

` else if lesson.lesson_type == 'paid' - bookingInfo = `

You are booking a {this.state.lesson.lesson_length} minute lesson for ${this.state.lesson.booked_price.toFixed(2)}

` + header = `

enter payment info for lesson

` + if this.state.lesson.recurring + if this.state.lesson.payment_style == 'single' + bookingInfo = `

You are booking a {this.state.lesson.lesson_length} minute lesson for + ${this.state.lesson.booked_price.toFixed(2)}

` + bookingDetail = `

+ Your card will not be charged until the day of the lesson. You must cancel at least 24 hours before your + lesson is scheduled, or you will be charged for the lesson in full. +
+ + jamclass + policies +

` + else if this.state.lesson.payment_style == 'weekly' + bookingInfo = `

You are booking a weekly recurring series of {this.state.lesson.lesson_length}-minute + lessons, to be paid individually as each lesson is taken, until cancelled.

` + bookingDetail = `

+ Your card will be charged on the day of each lesson. If you need to cancel a lesson, you must do so at + least 24 hours before the lesson is scheduled, or you will be charged for the lesson in full. +
+ + jamclass + policies +

` + else if this.state.lesson.payment_style == 'monthly' + bookingInfo = `

You are booking a weekly recurring series of {this.state.lesson.lesson_length}-minute + lessons, to be paid for monthly until cancelled.

` + bookingDetail = `

+ Your card will be charged on the first day of each month. Canceling individual lessons does not earn a + refund when buying monthly. To cancel, you must cancel at least 24 hours before the beginning of the + month, or you will be charged for that month in full. +
+ + jamclass + policies +

` + else + bookingInfo = `

You are booking a {this.state.lesson.lesson_length} minute lesson for + ${this.state.lesson.booked_price.toFixed(2)}

` + bookingDetail = `

+ Your card will not be charged until the day of the lesson. You must cancel at least 24 hours before your + lesson is scheduled, or you will be charged for the lesson in full. +
+ + jamclass + policies +

` + else + header = `

enter payment info

` + bookingInfo = `

You are entering your credit card info so that later checkouts go quickly. You can skip this + for now.

` + bookingDetail = ` +

+ Your card will not be charged until the day of the lesson. You must cancel at least 24 hours before your + lesson is scheduled, or you will be charged for the lesson in full. +
+ + jamclass policies +

` + submitClassNames = {'button-orange': true, disabled: disabled} + backClassNames = {'button-grey': true, disabled: disabled} + cardNumberFieldClasses = {field: true, "card-number": true, error: @state.ccError} + expirationFieldClasses = {field: true, "expiration": true, error: @state.expiryError} + cvvFieldClasses = {field: true, "card-number": true, error: @state.cvvError} + inUSClasses = {field: true, "billing-in-us": true, error: @state.billingInUSError} + zipCodeClasses = {field: true, "zip-code": true, error: @state.zipCodeError} `
-

enter payment info for lesson

+ {header} -
- - -
-
- - -
-
- - -
- -
- - -
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
{teacherDetails}
-

{bookingInfo}

+ {bookingInfo} -

BOOKING DETAIL TODO
- -

jamclass - policies
-

+ {bookingDetail}
+
+
+ BACKSUBMIT CARD INFORMATION +
+
` }) \ No newline at end of file diff --git a/web/app/assets/javascripts/react-components/actions/UserActions.js.coffee b/web/app/assets/javascripts/react-components/actions/UserActions.js.coffee index daf5708ab..815277def 100644 --- a/web/app/assets/javascripts/react-components/actions/UserActions.js.coffee +++ b/web/app/assets/javascripts/react-components/actions/UserActions.js.coffee @@ -3,5 +3,6 @@ context = window @UserActions = Reflux.createActions({ loaded: {} modify: {} + refresh: {} }) diff --git a/web/app/assets/javascripts/react-components/mixins/ICheckMixin.js.coffee b/web/app/assets/javascripts/react-components/mixins/ICheckMixin.js.coffee new file mode 100644 index 000000000..c07ca1ec1 --- /dev/null +++ b/web/app/assets/javascripts/react-components/mixins/ICheckMixin.js.coffee @@ -0,0 +1,40 @@ +context = window +teacherActions = window.JK.Actions.Teacher + +@ICheckMixin = { + + iCheckIgnore: false + checkboxes: [] + + iCheckify: () -> + @setCheckboxState() + @enableICheck() + + setCheckboxState: () -> + for checkbox in @checkboxes + selector = checkbox.selector + stateKey = checkbox.stateKey + enabled = @state[stateKey] + + @iCheckIgnore = true + if enabled + @root.find(selector).iCheck('check').attr('checked', true); + else + @root.find(selector).iCheck('uncheck').attr('checked', false); + @iCheckIgnore = false + + enableICheck: (e) -> + checkboxes = @root.find('input[type="checkbox"]') + context.JK.checkbox(checkboxes) + checkboxes.on('ifChanged', (e) => @checkIfCanFire(e)) + true + + checkIfCanFire: (e) -> + if @iCheckIgnore + return + + if @checkboxChanged? + @checkboxChanged(e) + else + logger.warn("no checkbox changed implemented") +} \ No newline at end of file diff --git a/web/app/assets/javascripts/react-components/stores/UserStore.js.coffee b/web/app/assets/javascripts/react-components/stores/UserStore.js.coffee index 5aaa11202..02b7d7a3a 100644 --- a/web/app/assets/javascripts/react-components/stores/UserStore.js.coffee +++ b/web/app/assets/javascripts/react-components/stores/UserStore.js.coffee @@ -1,6 +1,7 @@ $ = jQuery context = window logger = context.JK.logger +rest = context.JK.Rest @UserStore = Reflux.createStore( { @@ -26,6 +27,12 @@ logger = context.JK.logger @user = $.extend({}, @user, changes) @changed() + onRefresh: () -> + rest.getUserDetail().done((response) => @onLoaded(response)).fail((jqXHR) => @onUserFail(jqXHR)) + + onUserFail:(jqXHR) -> + @app.layout.notify({title: 'Unable to Update User Info', text: "We recommend you refresh the page."}) + changed:() -> @trigger({user: @user}) diff --git a/web/app/assets/stylesheets/client/jamtrack_landing.css.scss b/web/app/assets/stylesheets/client/jamtrack_landing.css.scss index 238c58190..a32770611 100644 --- a/web/app/assets/stylesheets/client/jamtrack_landing.css.scss +++ b/web/app/assets/stylesheets/client/jamtrack_landing.css.scss @@ -65,6 +65,8 @@ tbody { } + + margin-bottom:20px; } .search-area { diff --git a/web/app/assets/stylesheets/client/react-components/FreeLessonPayment.css.scss b/web/app/assets/stylesheets/client/react-components/FreeLessonPayment.css.scss deleted file mode 100644 index 4499dfff8..000000000 --- a/web/app/assets/stylesheets/client/react-components/FreeLessonPayment.css.scss +++ /dev/null @@ -1,100 +0,0 @@ -@import "client/common"; - -#free-lesson-payment { - - .content-body-scroller { - height:100%; - padding:30px; - } - - h2 { - font-size: 20px; - font-weight:700; - margin-bottom: 20px !important; - display:inline-block; - } - .no-charge { - float:right; - } - .column { - @include border_box_sizing; - width:50%; - } - .column-left { - float:left; - padding-right:20px; - } - .column-right { - float:right; - padding-left:20px; - } - label { - display:inline-block; - } - select { - display:inline-block; - } - - input { - display:inline-block; - width: calc(100% - 150px); - @include border_box_sizing; - } - textarea { - width:100%; - @include border_box_sizing; - height:125px; - } - .field { - position:relative; - display:block; - margin-top:15px; - margin-bottom:25px; - - label { - width:150px; - } - } - p { - line-height:125% !important; - font-size:14px !important; - margin:0 0 20px 0 !important; - } - .avatar { - display:inline-block; - padding:1px; - width:48px; - height:48px; - background-color:#ed4818; - margin:10px 20px 0 0; - -webkit-border-radius:24px; - -moz-border-radius:24px; - border-radius:24px; - float:none; - } - .avatar img { - width: 48px; - height: 48px; - -webkit-border-radius:24px; - -moz-border-radius:24px; - border-radius:24px; - } - .teacher-name { - font-size:16px; - display:inline-block; - height:48px; - vertical-align:middle; - } - .jamclass-policies { - text-align:center; - margin-top:-20px; - } - .actions { - margin-left:-3px; - margin-bottom:20px; - } - .error-text { - display:block; - } - -} \ No newline at end of file diff --git a/web/app/assets/stylesheets/client/react-components/JamClassStudentScreen.css.scss b/web/app/assets/stylesheets/client/react-components/JamClassStudentScreen.css.scss new file mode 100644 index 000000000..d56e04dcf --- /dev/null +++ b/web/app/assets/stylesheets/client/react-components/JamClassStudentScreen.css.scss @@ -0,0 +1,86 @@ +@import "client/common"; + +#jam-class-student-screen { + + div[data-react-class="JamClassStudentScreen"] { + height:100%; + } + .content-body-scroller { + height:100%; + padding:30px; + @include border_box_sizing; + } + + h2 { + font-size: 20px; + font-weight:700; + margin-bottom: 20px !important; + display:inline-block; + } + .column { + @include border_box_sizing; + width:50%; + } + .column-left { + float:left; + padding-right:20px; + } + .column-right { + float:right; + padding-left:20px; + } + p { + line-height:125% !important; + font-size:14px !important; + margin:0 0 20px 0 !important; + color: $ColorTextTypical; + } + .avatar { + display:inline-block; + padding:1px; + width:36px; + height:36px; + background-color:#ed4818; + margin:10px 20px 0 0; + -webkit-border-radius:18px; + -moz-border-radius:18px; + border-radius:18px; + float:none; + } + .avatar img { + width: 36px; + height: 36px; + -webkit-border-radius:18px; + -moz-border-radius:18px; + border-radius:18px; + } + + .calender-integration-notice { + display:block; + text-align:center; + } + .actions { + display:block; + text-align:center; + } + .jamclass-section { + margin-bottom:40px; + } + .jamtable { + a { + text-decoration: underline !important; + color:#fc0 !important; + } + th { + font-size:14px; + padding:3px 10px; + } + td { + padding:4px 15px; + font-size:14px; + } + tbody { + + } + } +} \ No newline at end of file diff --git a/web/app/assets/stylesheets/client/react-components/LessonPayment.css.scss b/web/app/assets/stylesheets/client/react-components/LessonPayment.css.scss index 9136c89d9..5c13b48e6 100644 --- a/web/app/assets/stylesheets/client/react-components/LessonPayment.css.scss +++ b/web/app/assets/stylesheets/client/react-components/LessonPayment.css.scss @@ -2,4 +2,109 @@ #lesson-payment { + div[data-react-class="LessonPayment"] { + height:100%; + } + .content-body-scroller { + height:100%; + padding:30px; + @include border_box_sizing; + } + + h2 { + font-size: 20px; + font-weight:700; + margin-bottom: 20px !important; + display:inline-block; + } + .no-charge { + float:right; + } + .column { + @include border_box_sizing; + width:50%; + } + .column-left { + float:left; + padding-right:20px; + } + .column-right { + float:right; + padding-left:20px; + } + label { + display:inline-block; + } + select { + display:inline-block; + } + + input { + display:inline-block; + width: calc(100% - 150px); + @include border_box_sizing; + } + textarea { + width:100%; + @include border_box_sizing; + height:125px; + } + .field { + position:relative; + display:block; + margin-top:15px; + margin-bottom:25px; + + label { + width:150px; + } + } + p { + line-height:125% !important; + font-size:14px !important; + margin:0 0 20px 0 !important; + } + .avatar { + display:inline-block; + padding:1px; + width:48px; + height:48px; + background-color:#ed4818; + margin:10px 20px 0 0; + -webkit-border-radius:24px; + -moz-border-radius:24px; + border-radius:24px; + float:none; + } + .avatar img { + width: 48px; + height: 48px; + -webkit-border-radius:24px; + -moz-border-radius:24px; + border-radius:24px; + } + .teacher-name { + font-size:16px; + display:inline-block; + height:48px; + vertical-align:middle; + } + .jamclass-policies { + display:block; + text-align:center; + } + .actions { + margin-left:-3px; + margin-bottom:20px; + } + .error-text { + display:block; + } + + .actions { + float:left; + clear:both; + } + + } \ No newline at end of file diff --git a/web/app/controllers/api_controller.rb b/web/app/controllers/api_controller.rb index e202c509e..94ed0a4a4 100644 --- a/web/app/controllers/api_controller.rb +++ b/web/app/controllers/api_controller.rb @@ -23,6 +23,10 @@ class ApiController < ApplicationController @exception = exception render "errors/conflict_error", :status => 409 end + rescue_from 'Stripe::StripeError' do |exception| + @exception = exception + render "errors/stripe_error", :status => 422 + end rescue_from 'ActiveRecord::RecordNotFound' do |exception| log.debug(exception) render :json => { :errors => { :resource => ["record not found"] } }, :status => 404 diff --git a/web/app/controllers/api_lesson_bookings_controller.rb b/web/app/controllers/api_lesson_bookings_controller.rb index 55d107162..60d683380 100644 --- a/web/app/controllers/api_lesson_bookings_controller.rb +++ b/web/app/controllers/api_lesson_bookings_controller.rb @@ -3,6 +3,15 @@ class ApiLessonBookingsController < ApiController before_filter :api_signed_in_user respond_to :json + def index + data = LessonBooking.index(current_user) + + @lessons = data[:query] + + @next = data[:next_page] + render "api_lesson_bookings/index", :layout => nil + end + def create if params[:lesson_type] == LessonBooking::LESSON_TYPE_FREE @@ -28,6 +37,7 @@ class ApiLessonBookingsController < ApiController specified_slot.preferred_day = day specified_slot.hour = slot[:hour] specified_slot.minute = slot[:minute] + specified_slot.timezone = slot[:timezone] slots << specified_slot end @lesson_booking = LessonBooking.book_free(current_user, teacher, slots, params[:description]) @@ -50,6 +60,6 @@ class ApiLessonBookingsController < ApiController def unprocessed @show_teacher = true - @lesson_booking = LessonBooking.unprocessed(current_user) + @lesson_booking = LessonBooking.unprocessed(current_user).first end end diff --git a/web/app/controllers/api_lesson_sessions_controller.rb b/web/app/controllers/api_lesson_sessions_controller.rb new file mode 100644 index 000000000..0001d9757 --- /dev/null +++ b/web/app/controllers/api_lesson_sessions_controller.rb @@ -0,0 +1,14 @@ +class ApiLessonSessionsController < ApiController + + before_filter :api_signed_in_user + respond_to :json + + def index + data = LessonSession.index(current_user, params) + + @lesson_sessions = data[:query] + + @next = data[:next_page] + render "api_lesson_sessions/index", :layout => nil + end +end diff --git a/web/app/controllers/api_stripe_controller.rb b/web/app/controllers/api_stripe_controller.rb new file mode 100644 index 000000000..efd3c339f --- /dev/null +++ b/web/app/controllers/api_stripe_controller.rb @@ -0,0 +1,11 @@ +class ApiStripeController < ApiController + + before_filter :api_signed_in_user + respond_to :json + + def store + data = user.payment_update(params) + @lesson = data[:lesson] + @test_drive = data[:test_drive] + end +end diff --git a/web/app/helpers/client_helper.rb b/web/app/helpers/client_helper.rb index 151d2394d..01a73152e 100644 --- a/web/app/helpers/client_helper.rb +++ b/web/app/helpers/client_helper.rb @@ -81,5 +81,6 @@ module ClientHelper gon.use_cached_session_scores = Rails.application.config.use_cached_session_scores gon.allow_both_find_algos = Rails.application.config.allow_both_find_algos + gon.stripe_publishable_key = Rails.application.config.stripe_publishable_key end end diff --git a/web/app/views/api_jamblasters/get_tokens.rabl b/web/app/views/api_jamblasters/get_tokens.rabl index 6fdfa70ef..c30dd828b 100644 --- a/web/app/views/api_jamblasters/get_tokens.rabl +++ b/web/app/views/api_jamblasters/get_tokens.rabl @@ -1,4 +1,4 @@ object @jamblasters -attributes :id, :serial_no, :client_id, :vtoken \ No newline at end of file +attributes :id, :serial_no, :client_id, :vtoken, :key \ No newline at end of file diff --git a/web/app/views/api_lesson_bookings/show.rabl b/web/app/views/api_lesson_bookings/show.rabl index e2e17e76b..368d7b88b 100644 --- a/web/app/views/api_lesson_bookings/show.rabl +++ b/web/app/views/api_lesson_bookings/show.rabl @@ -10,6 +10,6 @@ child(:user => :user) { attributes :id, :has_stored_credit_card? } -child (:teacher => :teacher) { |teacher| +child(:teacher => :teacher) do |teacher| partial "api_users/show", object: teacher -} \ No newline at end of file +end \ No newline at end of file diff --git a/web/app/views/api_lesson_sessions/index.rabl b/web/app/views/api_lesson_sessions/index.rabl new file mode 100644 index 000000000..76ebfcd45 --- /dev/null +++ b/web/app/views/api_lesson_sessions/index.rabl @@ -0,0 +1,11 @@ +node :next do |page| + @next +end + +node :entries do |page| + partial "api_lesson_sessions/show", object: @lesson_sessions +end + +node :total_entries do |page| + @lesson_sessions.total_entries +end diff --git a/web/app/views/api_lesson_sessions/show.rabl b/web/app/views/api_lesson_sessions/show.rabl new file mode 100644 index 000000000..2fe2c97c5 --- /dev/null +++ b/web/app/views/api_lesson_sessions/show.rabl @@ -0,0 +1,31 @@ +object @lesson_session + +attributes :id, :lesson_type, :duration, :price, :teacher_complete, :student_complete, :status, :student_canceled, :teacher_canceled, :student_canceled_at, :teacher_canceled_at, :student_canceled_reason, :teacher_canceled_reason, :status + +child(:music_session => :music_session) { + attributes :id, :music_session_id, :name, :description, :musician_access, :approval_required, :fan_access, :fan_chat, + :band_id, :user_id, :genre_id, :created_at, :like_count, :comment_count, :play_count, :scheduled_duration, + :language, :recurring_mode, :language_description, :scheduled_start_date, :access_description, :timezone, :timezone_id, :timezone_description, + :musician_access_description, :fan_access_description, :session_removed_at, :legal_policy, :open_rsvps, :is_unstructured_rsvp? + + + node :scheduled_start_date do |session| + scheduled_start_date(session) + end + + node :scheduled_start do |history| + history.scheduled_start_time.strftime("%a %e %B %Y %H:%M:%S") if history.scheduled_start + end + + node :pretty_scheduled_start_with_timezone do |session| + pretty_scheduled_start(session, true) + end + + node :pretty_scheduled_start_short do|session| + pretty_scheduled_start(session, false) + end +} + +child(:teacher => :teacher) do |teacher| + partial "api_users/show", object: teacher +end \ No newline at end of file diff --git a/web/app/views/api_stripe/store.rabl b/web/app/views/api_stripe/store.rabl new file mode 100644 index 000000000..e83d57c81 --- /dev/null +++ b/web/app/views/api_stripe/store.rabl @@ -0,0 +1,14 @@ +object @lesson + +node :lesson do |lesson| + attribute :id +end + +if @test_drive + node :test_drive do |lesson| + + end +end + + + diff --git a/web/app/views/api_users/show.rabl b/web/app/views/api_users/show.rabl index e36546085..28d10dd10 100644 --- a/web/app/views/api_users/show.rabl +++ b/web/app/views/api_users/show.rabl @@ -31,7 +31,7 @@ end # give back more info if the user being fetched is yourself if current_user && @user == current_user - attributes :email, :original_fpfile, :cropped_fpfile, :crop_selection, :session_settings, :show_whats_next, :show_whats_next_count, :subscribe_email, :auth_twitter, :new_notifications, :sales_count, :reuse_card, :purchased_jamtracks_count, :first_downloaded_client_at, :created_at, :first_opened_jamtrack_web_player, :gifted_jamtracks, :has_redeemable_jamtrack + attributes :email, :original_fpfile, :cropped_fpfile, :crop_selection, :session_settings, :show_whats_next, :show_whats_next_count, :subscribe_email, :auth_twitter, :new_notifications, :sales_count, :reuse_card, :purchased_jamtracks_count, :first_downloaded_client_at, :created_at, :first_opened_jamtrack_web_player, :gifted_jamtracks, :has_redeemable_jamtrack, :remaining node :geoiplocation do |user| geoiplocation = current_user.geoiplocation @@ -68,7 +68,7 @@ if current_user && @user == current_user if @show_student node :has_unprocessed_lesson do |user| - !!LessonBooking.unprocessed(user) + !!LessonBooking.unprocessed(user).first end end diff --git a/web/app/views/clients/index.html.erb b/web/app/views/clients/index.html.erb index 491e8f8e6..0d1fb6ecc 100644 --- a/web/app/views/clients/index.html.erb +++ b/web/app/views/clients/index.html.erb @@ -47,7 +47,7 @@ <%= render "clients/teachers/search/search_results" %> <%= render "clients/jamclass/book_lesson_free" %> <%= render "clients/jamclass/lesson_payment" %> -<%= render "clients/jamclass/free_lesson_payment" %> +<%= render "clients/jamclass/jamclass_student" %> <%= render "users/feed_music_session_ajax" %> <%= render "users/feed_recording_ajax" %> <%= render "jamtrack_search" %> diff --git a/web/app/views/clients/jamclass/_free_lesson_payment.html.slim b/web/app/views/clients/jamclass/_free_lesson_payment.html.slim deleted file mode 100644 index 33294c50d..000000000 --- a/web/app/views/clients/jamclass/_free_lesson_payment.html.slim +++ /dev/null @@ -1,10 +0,0 @@ -#free-lesson-payment.screen.secondary layout="screen" layout-id="jamclass/free-lesson-payment" - .content-head - .content-icon - = image_tag "content/icon_account.png", :size => "27x20" - h1 - | jamclass - = render "screen_navigation" - .content-body - = react_component 'FreeLessonPayment', {} - diff --git a/web/app/views/clients/jamclass/_jamclass_student.html.slim b/web/app/views/clients/jamclass/_jamclass_student.html.slim new file mode 100644 index 000000000..3607f633c --- /dev/null +++ b/web/app/views/clients/jamclass/_jamclass_student.html.slim @@ -0,0 +1,10 @@ +#jam-class-student-screen.screen.secondary layout="screen" layout-id="jamclass" + .content-head + .content-icon + = image_tag "content/icon_jamtracks.png", :size => "24x24" + h1 + | jamclass + = render "screen_navigation" + .content-body + = react_component 'JamClassStudentScreen', {} + diff --git a/web/app/views/clients/jamclass/_lesson_payment.html.slim b/web/app/views/clients/jamclass/_lesson_payment.html.slim index 0eee834e3..6cfa5917d 100644 --- a/web/app/views/clients/jamclass/_lesson_payment.html.slim +++ b/web/app/views/clients/jamclass/_lesson_payment.html.slim @@ -1,4 +1,4 @@ -#lesson-payment.screen.secondary layout="screen" layout-id="jamclass/payment" layout-arg="id" +#lesson-payment.screen.secondary layout="screen" layout-id="jamclass/lesson-payment" .content-head .content-icon = image_tag "content/icon_account.png", :size => "27x20" diff --git a/web/app/views/errors/stripe_error.rabl b/web/app/views/errors/stripe_error.rabl new file mode 100644 index 000000000..53b717210 --- /dev/null +++ b/web/app/views/errors/stripe_error.rabl @@ -0,0 +1,13 @@ +object @exception + +node do |exception| + errors = {} + errors["message"] = [exception.to_s] + { + errors: errors + } +end + +node "type" do + "StripeError" +end \ No newline at end of file diff --git a/web/app/views/layouts/client.html.erb b/web/app/views/layouts/client.html.erb index 1908a054d..b77ca9351 100644 --- a/web/app/views/layouts/client.html.erb +++ b/web/app/views/layouts/client.html.erb @@ -24,6 +24,7 @@ <%= yield %> <%= render "shared/ga" %> <%= render "shared/recurly" %> + <%= render "shared/stripe" %> <%= render "shared/google_nocaptcha" %> <%= render "shared/olark" %> diff --git a/web/app/views/shared/_stripe.html.slim b/web/app/views/shared/_stripe.html.slim new file mode 100644 index 000000000..b8a9f650f --- /dev/null +++ b/web/app/views/shared/_stripe.html.slim @@ -0,0 +1,6 @@ +javascript: + window.stripeReadyHandler = function() { + Stripe.setPublishableKey(gon.stripe_publishable_key); + } + +script src="https://js.stripe.com/v2/" onload="window.stripeReadyHandler()" async \ No newline at end of file diff --git a/web/config/application.rb b/web/config/application.rb index 2b8df7a47..dc621455e 100644 --- a/web/config/application.rb +++ b/web/config/application.rb @@ -164,6 +164,9 @@ if defined?(Bundler) # Use Public Keys to identify your site when using Recurly.js. See https://docs.recurly.com/js/#include to learn more. config.recurly_public_api_key = 'sjc-SZlO11shkeA1WMGuISLGg5' + config.stripe_secret_key = 'sk_test_cPVRbtr9xbMiqffV8jwibwLA' + config.stripe_publishable_key = 'pk_test_9vO8ZnxBpb9Udb0paruV3qLv' + if Rails.env == 'production' config.desk_url = 'https://jamkazam.desk.com' config.multipass_callback_url = "http://jamkazam.desk.com/customer/authentication/multipass/callback" @@ -418,5 +421,11 @@ if defined?(Bundler) config.ban_jamtrack_downloaders = true config.chat_opened_by_default = true config.chat_blast = true - end + + config.stripe = { + :publishable_key => 'pk_test_9vO8ZnxBpb9Udb0paruV3qLv', + :secret_key => 'sk_test_cPVRbtr9xbMiqffV8jwibwLA' + } + + end end diff --git a/web/config/initializers/stripe.rb b/web/config/initializers/stripe.rb new file mode 100644 index 000000000..4e32a33c1 --- /dev/null +++ b/web/config/initializers/stripe.rb @@ -0,0 +1 @@ +Stripe.api_key = Rails.configuration.stripe[:secret_key] \ No newline at end of file diff --git a/web/config/initializers/zip_codes.rb b/web/config/initializers/zip_codes.rb new file mode 100644 index 000000000..7165e825b --- /dev/null +++ b/web/config/initializers/zip_codes.rb @@ -0,0 +1 @@ +ZipCodes.load if Rails.env.production? \ No newline at end of file diff --git a/web/config/routes.rb b/web/config/routes.rb index 824cd937c..75fe75ce2 100644 --- a/web/config/routes.rb +++ b/web/config/routes.rb @@ -684,7 +684,10 @@ SampleApp::Application.routes.draw do match '/jamblasters/pairing/store' => 'api_jamblasters#store_token', :via => :post match '/jamblasters/pairing/pair' => 'api_jamblasters#pair', :via => :post + match '/lesson_sessions' => 'api_lesson_sessions#index', :via => :get match '/lesson_bookings' => 'api_lesson_bookings#create', :via => :post match '/lesson_booking/unprocessed' => 'api_lesson_bookings#unprocessed', :via => :get + + match '/stripe' => 'api_stripe#store', :via => :post end end diff --git a/web/vendor/assets/javascripts/jquery.inputmask.js b/web/vendor/assets/javascripts/jquery.inputmask.js new file mode 100644 index 000000000..873b6c4b1 --- /dev/null +++ b/web/vendor/assets/javascripts/jquery.inputmask.js @@ -0,0 +1,2653 @@ +/*! + * jquery.inputmask.bundle.js + * http://github.com/RobinHerbots/jquery.inputmask + * Copyright (c) 2010 - 2016 Robin Herbots + * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) + * Version: 3.2.7 + */ +!function($) { + function Inputmask(alias, options) { + return this instanceof Inputmask ? ($.isPlainObject(alias) ? options = alias : (options = options || {}, + options.alias = alias), this.el = void 0, this.opts = $.extend(!0, {}, this.defaults, options), + this.noMasksCache = options && void 0 !== options.definitions, this.userOptions = options || {}, + this.events = {}, void resolveAlias(this.opts.alias, options, this.opts)) : new Inputmask(alias, options); + } + function isInputEventSupported(eventName) { + var el = document.createElement("input"), evName = "on" + eventName, isSupported = evName in el; + return isSupported || (el.setAttribute(evName, "return;"), isSupported = "function" == typeof el[evName]), + el = null, isSupported; + } + function isElementTypeSupported(input, opts) { + var elementType = input.getAttribute("type"), isSupported = "INPUT" === input.tagName && -1 !== $.inArray(elementType, opts.supportsInputType) || input.isContentEditable || "TEXTAREA" === input.tagName; + if (!isSupported) { + var el = document.createElement("input"); + el.setAttribute("type", elementType), isSupported = "text" === el.type, el = null; + } + return isSupported; + } + function resolveAlias(aliasStr, options, opts) { + var aliasDefinition = opts.aliases[aliasStr]; + return aliasDefinition ? (aliasDefinition.alias && resolveAlias(aliasDefinition.alias, void 0, opts), + $.extend(!0, opts, aliasDefinition), $.extend(!0, opts, options), !0) : (null === opts.mask && (opts.mask = aliasStr), + !1); + } + function importAttributeOptions(npt, opts, userOptions) { + function importOption(option, optionData) { + optionData = void 0 !== optionData ? optionData : npt.getAttribute("data-inputmask-" + option), + null !== optionData && ("string" == typeof optionData && (0 === option.indexOf("on") ? optionData = window[optionData] : "false" === optionData ? optionData = !1 : "true" === optionData && (optionData = !0)), + userOptions[option] = optionData); + } + var option, dataoptions, optionData, p, attrOptions = npt.getAttribute("data-inputmask"); + if (attrOptions && "" !== attrOptions && (attrOptions = attrOptions.replace(new RegExp("'", "g"), '"'), + dataoptions = JSON.parse("{" + attrOptions + "}")), dataoptions) { + optionData = void 0; + for (p in dataoptions) if ("alias" === p.toLowerCase()) { + optionData = dataoptions[p]; + break; + } + } + importOption("alias", optionData), userOptions.alias && resolveAlias(userOptions.alias, userOptions, opts); + for (option in opts) { + if (dataoptions) { + optionData = void 0; + for (p in dataoptions) if (p.toLowerCase() === option.toLowerCase()) { + optionData = dataoptions[p]; + break; + } + } + importOption(option, optionData); + } + return $.extend(!0, opts, userOptions), opts; + } + function generateMaskSet(opts, nocache) { + function analyseMask(mask) { + function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) { + this.matches = [], this.isGroup = isGroup || !1, this.isOptional = isOptional || !1, + this.isQuantifier = isQuantifier || !1, this.isAlternator = isAlternator || !1, + this.quantifier = { + min: 1, + max: 1 + }; + } + function insertTestDefinition(mtoken, element, position) { + var maskdef = opts.definitions[element]; + position = void 0 !== position ? position : mtoken.matches.length; + var prevMatch = mtoken.matches[position - 1]; + if (maskdef && !escaped) { + maskdef.placeholder = $.isFunction(maskdef.placeholder) ? maskdef.placeholder(opts) : maskdef.placeholder; + for (var prevalidators = maskdef.prevalidator, prevalidatorsL = prevalidators ? prevalidators.length : 0, i = 1; i < maskdef.cardinality; i++) { + var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator.validator, cardinality = prevalidator.cardinality; + mtoken.matches.splice(position++, 0, { + fn: validator ? "string" == typeof validator ? new RegExp(validator) : new function() { + this.test = validator; + }() : new RegExp("."), + cardinality: cardinality ? cardinality : 1, + optionality: mtoken.isOptional, + newBlockMarker: void 0 === prevMatch || prevMatch.def !== (maskdef.definitionSymbol || element), + casing: maskdef.casing, + def: maskdef.definitionSymbol || element, + placeholder: maskdef.placeholder, + mask: element + }), prevMatch = mtoken.matches[position - 1]; + } + mtoken.matches.splice(position++, 0, { + fn: maskdef.validator ? "string" == typeof maskdef.validator ? new RegExp(maskdef.validator) : new function() { + this.test = maskdef.validator; + }() : new RegExp("."), + cardinality: maskdef.cardinality, + optionality: mtoken.isOptional, + newBlockMarker: void 0 === prevMatch || prevMatch.def !== (maskdef.definitionSymbol || element), + casing: maskdef.casing, + def: maskdef.definitionSymbol || element, + placeholder: maskdef.placeholder, + mask: element + }); + } else mtoken.matches.splice(position++, 0, { + fn: null, + cardinality: 0, + optionality: mtoken.isOptional, + newBlockMarker: void 0 === prevMatch || prevMatch.def !== element, + casing: null, + def: opts.staticDefinitionSymbol || element, + placeholder: void 0 !== opts.staticDefinitionSymbol ? element : void 0, + mask: element + }), escaped = !1; + } + function verifyGroupMarker(lastMatch, isOpenGroup) { + lastMatch.isGroup && (lastMatch.isGroup = !1, insertTestDefinition(lastMatch, opts.groupmarker.start, 0), + isOpenGroup !== !0 && insertTestDefinition(lastMatch, opts.groupmarker.end)); + } + function maskCurrentToken(m, currentToken, lastMatch, extraCondition) { + currentToken.matches.length > 0 && (void 0 === extraCondition || extraCondition) && (lastMatch = currentToken.matches[currentToken.matches.length - 1], + verifyGroupMarker(lastMatch)), insertTestDefinition(currentToken, m); + } + function defaultCase() { + if (openenings.length > 0) { + if (currentOpeningToken = openenings[openenings.length - 1], maskCurrentToken(m, currentOpeningToken, lastMatch, !currentOpeningToken.isAlternator), + currentOpeningToken.isAlternator) { + alternator = openenings.pop(); + for (var mndx = 0; mndx < alternator.matches.length; mndx++) alternator.matches[mndx].isGroup = !1; + openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], + currentOpeningToken.matches.push(alternator)) : currentToken.matches.push(alternator); + } + } else maskCurrentToken(m, currentToken, lastMatch); + } + function reverseTokens(maskToken) { + function reverseStatic(st) { + return st === opts.optionalmarker.start ? st = opts.optionalmarker.end : st === opts.optionalmarker.end ? st = opts.optionalmarker.start : st === opts.groupmarker.start ? st = opts.groupmarker.end : st === opts.groupmarker.end && (st = opts.groupmarker.start), + st; + } + maskToken.matches = maskToken.matches.reverse(); + for (var match in maskToken.matches) { + var intMatch = parseInt(match); + if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { + var qt = maskToken.matches[match]; + maskToken.matches.splice(match, 1), maskToken.matches.splice(intMatch + 1, 0, qt); + } + void 0 !== maskToken.matches[match].matches ? maskToken.matches[match] = reverseTokens(maskToken.matches[match]) : maskToken.matches[match] = reverseStatic(maskToken.matches[match]); + } + return maskToken; + } + for (var match, m, openingToken, currentOpeningToken, alternator, lastMatch, groupToken, tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g, escaped = !1, currentToken = new MaskToken(), openenings = [], maskTokens = []; match = tokenizer.exec(mask); ) if (m = match[0], + escaped) defaultCase(); else switch (m.charAt(0)) { + case opts.escapeChar: + escaped = !0; + break; + + case opts.optionalmarker.end: + case opts.groupmarker.end: + if (openingToken = openenings.pop(), void 0 !== openingToken) if (openenings.length > 0) { + if (currentOpeningToken = openenings[openenings.length - 1], currentOpeningToken.matches.push(openingToken), + currentOpeningToken.isAlternator) { + alternator = openenings.pop(); + for (var mndx = 0; mndx < alternator.matches.length; mndx++) alternator.matches[mndx].isGroup = !1; + openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], + currentOpeningToken.matches.push(alternator)) : currentToken.matches.push(alternator); + } + } else currentToken.matches.push(openingToken); else defaultCase(); + break; + + case opts.optionalmarker.start: + openenings.push(new MaskToken(!1, !0)); + break; + + case opts.groupmarker.start: + openenings.push(new MaskToken(!0)); + break; + + case opts.quantifiermarker.start: + var quantifier = new MaskToken(!1, !1, !0); + m = m.replace(/[{}]/g, ""); + var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = 1 === mq.length ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]); + if (("*" === mq1 || "+" === mq1) && (mq0 = "*" === mq1 ? 0 : 1), quantifier.quantifier = { + min: mq0, + max: mq1 + }, openenings.length > 0) { + var matches = openenings[openenings.length - 1].matches; + match = matches.pop(), match.isGroup || (groupToken = new MaskToken(!0), groupToken.matches.push(match), + match = groupToken), matches.push(match), matches.push(quantifier); + } else match = currentToken.matches.pop(), match.isGroup || (groupToken = new MaskToken(!0), + groupToken.matches.push(match), match = groupToken), currentToken.matches.push(match), + currentToken.matches.push(quantifier); + break; + + case opts.alternatormarker: + openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], + lastMatch = currentOpeningToken.matches.pop()) : lastMatch = currentToken.matches.pop(), + lastMatch.isAlternator ? openenings.push(lastMatch) : (alternator = new MaskToken(!1, !1, !1, !0), + alternator.matches.push(lastMatch), openenings.push(alternator)); + break; + + default: + defaultCase(); + } + for (;openenings.length > 0; ) openingToken = openenings.pop(), verifyGroupMarker(openingToken, !0), + currentToken.matches.push(openingToken); + return currentToken.matches.length > 0 && (lastMatch = currentToken.matches[currentToken.matches.length - 1], + verifyGroupMarker(lastMatch), maskTokens.push(currentToken)), opts.numericInput && reverseTokens(maskTokens[0]), + maskTokens; + } + function generateMask(mask, metadata) { + if (null === mask || "" === mask) return void 0; + if (1 === mask.length && opts.greedy === !1 && 0 !== opts.repeat && (opts.placeholder = ""), + opts.repeat > 0 || "*" === opts.repeat || "+" === opts.repeat) { + var repeatStart = "*" === opts.repeat ? 0 : "+" === opts.repeat ? 1 : opts.repeat; + mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end; + } + var masksetDefinition; + return void 0 === Inputmask.prototype.masksCache[mask] || nocache === !0 ? (masksetDefinition = { + mask: mask, + maskToken: analyseMask(mask), + validPositions: {}, + _buffer: void 0, + buffer: void 0, + tests: {}, + metadata: metadata + }, nocache !== !0 && (Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask] = masksetDefinition, + masksetDefinition = $.extend(!0, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]))) : masksetDefinition = $.extend(!0, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]), + masksetDefinition; + } + function preProcessMask(mask) { + return mask = mask.toString(); + } + var ms; + if ($.isFunction(opts.mask) && (opts.mask = opts.mask(opts)), $.isArray(opts.mask)) { + if (opts.mask.length > 1) { + opts.keepStatic = null === opts.keepStatic ? !0 : opts.keepStatic; + var altMask = "("; + return $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function(ndx, msk) { + altMask.length > 1 && (altMask += ")|("), altMask += preProcessMask(void 0 === msk.mask || $.isFunction(msk.mask) ? msk : msk.mask); + }), altMask += ")", generateMask(altMask, opts.mask); + } + opts.mask = opts.mask.pop(); + } + return opts.mask && (ms = void 0 === opts.mask.mask || $.isFunction(opts.mask.mask) ? generateMask(preProcessMask(opts.mask), opts.mask) : generateMask(preProcessMask(opts.mask.mask), opts.mask)), + ms; + } + function maskScope(actionObj, maskset, opts) { + function getMaskTemplate(baseOnInput, minimalPos, includeInput) { + minimalPos = minimalPos || 0; + var ndxIntlzr, test, testPos, maskTemplate = [], pos = 0, lvp = getLastValidPosition(); + do { + if (baseOnInput === !0 && getMaskSet().validPositions[pos]) { + var validPos = getMaskSet().validPositions[pos]; + test = validPos.match, ndxIntlzr = validPos.locator.slice(), maskTemplate.push(includeInput === !0 ? validPos.input : getPlaceholder(pos, test)); + } else testPos = getTestTemplate(pos, ndxIntlzr, pos - 1), test = testPos.match, + ndxIntlzr = testPos.locator.slice(), (opts.jitMasking === !1 || lvp > pos || isFinite(opts.jitMasking) && opts.jitMasking > pos) && maskTemplate.push(getPlaceholder(pos, test)); + pos++; + } while ((void 0 === maxLength || maxLength > pos - 1) && null !== test.fn || null === test.fn && "" !== test.def || minimalPos >= pos); + return "" === maskTemplate[maskTemplate.length - 1] && maskTemplate.pop(), maskTemplate; + } + function getMaskSet() { + return maskset; + } + function resetMaskSet(soft) { + var maskset = getMaskSet(); + maskset.buffer = void 0, soft !== !0 && (maskset.tests = {}, maskset._buffer = void 0, + maskset.validPositions = {}, maskset.p = 0); + } + function getLastValidPosition(closestTo, strict) { + var before = -1, after = -1, valids = getMaskSet().validPositions; + void 0 === closestTo && (closestTo = -1); + for (var posNdx in valids) { + var psNdx = parseInt(posNdx); + valids[psNdx] && (strict || null !== valids[psNdx].match.fn) && (closestTo >= psNdx && (before = psNdx), + psNdx >= closestTo && (after = psNdx)); + } + return -1 !== before && closestTo - before > 1 || closestTo > after ? before : after; + } + function setValidPosition(pos, validTest, fromSetValid) { + if (opts.insertMode && void 0 !== getMaskSet().validPositions[pos] && void 0 === fromSetValid) { + var i, positionsClone = $.extend(!0, {}, getMaskSet().validPositions), lvp = getLastValidPosition(); + for (i = pos; lvp >= i; i++) delete getMaskSet().validPositions[i]; + getMaskSet().validPositions[pos] = validTest; + var j, valid = !0, vps = getMaskSet().validPositions; + for (i = j = pos; lvp >= i; i++) { + var t = positionsClone[i]; + if (void 0 !== t) for (var posMatch = j, prevPosMatch = -1; posMatch < getMaskLength() && (null == t.match.fn && vps[i] && (vps[i].match.optionalQuantifier === !0 || vps[i].match.optionality === !0) || null != t.match.fn); ) { + if (null === t.match.fn || !opts.keepStatic && vps[i] && (void 0 !== vps[i + 1] && getTests(i + 1, vps[i].locator.slice(), i).length > 1 || void 0 !== vps[i].alternation) ? posMatch++ : posMatch = seekNext(j), + positionCanMatchDefinition(posMatch, t.match.def)) { + var result = isValid(posMatch, t.input, !0, !0); + valid = result !== !1, j = result.caret || result.insert ? getLastValidPosition() : posMatch; + break; + } + if (valid = null == t.match.fn, prevPosMatch === posMatch) break; + prevPosMatch = posMatch; + } + if (!valid) break; + } + if (!valid) return getMaskSet().validPositions = $.extend(!0, {}, positionsClone), + resetMaskSet(!0), !1; + } else getMaskSet().validPositions[pos] = validTest; + return resetMaskSet(!0), !0; + } + function stripValidPositions(start, end, nocheck, strict) { + var i, startPos = start; + for (getMaskSet().p = start, i = startPos; end > i; i++) void 0 !== getMaskSet().validPositions[i] && (nocheck === !0 || opts.canClearPosition(getMaskSet(), i, getLastValidPosition(), strict, opts) !== !1) && delete getMaskSet().validPositions[i]; + for (i = startPos + 1; i <= getLastValidPosition(); ) { + for (;void 0 !== getMaskSet().validPositions[startPos]; ) startPos++; + var s = getMaskSet().validPositions[startPos]; + if (startPos > i && (i = startPos + 1), void 0 === getMaskSet().validPositions[i] && isMask(i) || void 0 !== s) i++; else { + var t = getTestTemplate(i); + positionCanMatchDefinition(startPos, t.match.def) ? isValid(startPos, t.input || getPlaceholder(i), !0) !== !1 && (delete getMaskSet().validPositions[i], + i++) : isMask(i) || (i++, startPos--), startPos++; + } + } + var lvp = getLastValidPosition(), ml = getMaskLength(); + for (strict !== !0 && nocheck !== !0 && void 0 !== getMaskSet().validPositions[lvp] && getMaskSet().validPositions[lvp].input === opts.radixPoint && delete getMaskSet().validPositions[lvp], + i = lvp + 1; ml >= i; i++) getMaskSet().validPositions[i] && delete getMaskSet().validPositions[i]; + resetMaskSet(!0); + } + function getTestTemplate(pos, ndxIntlzr, tstPs) { + var testPos = getMaskSet().validPositions[pos]; + if (void 0 === testPos) for (var testPositions = getTests(pos, ndxIntlzr, tstPs), lvp = getLastValidPosition(), lvTest = getMaskSet().validPositions[lvp] || getTests(0)[0], lvTestAltArr = void 0 !== lvTest.alternation ? lvTest.locator[lvTest.alternation].toString().split(",") : [], ndx = 0; ndx < testPositions.length && (testPos = testPositions[ndx], + !(testPos.match && (opts.greedy && testPos.match.optionalQuantifier !== !0 || (testPos.match.optionality === !1 || testPos.match.newBlockMarker === !1) && testPos.match.optionalQuantifier !== !0) && (void 0 === lvTest.alternation || lvTest.alternation !== testPos.alternation || void 0 !== testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr)))); ndx++) ; + return testPos; + } + function getTest(pos) { + return getMaskSet().validPositions[pos] ? getMaskSet().validPositions[pos].match : getTests(pos)[0].match; + } + function positionCanMatchDefinition(pos, def) { + for (var valid = !1, tests = getTests(pos), tndx = 0; tndx < tests.length; tndx++) if (tests[tndx].match && tests[tndx].match.def === def) { + valid = !0; + break; + } + return valid; + } + function selectBestMatch(pos, alternateNdx) { + var bestMatch, indexPos; + return (getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) && $.each(getMaskSet().tests[pos] || [ getMaskSet().validPositions[pos] ], function(ndx, lmnt) { + var ndxPos = lmnt.alternation ? lmnt.locator[lmnt.alternation].toString().indexOf(alternateNdx) : -1; + (void 0 === indexPos || indexPos > ndxPos) && -1 !== ndxPos && (bestMatch = lmnt, + indexPos = ndxPos); + }), bestMatch; + } + function getTests(pos, ndxIntlzr, tstPs) { + function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { + function handleMatch(match, loopNdx, quantifierRecurse) { + function isFirstMatch(latestMatch, tokenGroup) { + var firstMatch = 0 === $.inArray(latestMatch, tokenGroup.matches); + return firstMatch || $.each(tokenGroup.matches, function(ndx, match) { + return match.isQuantifier === !0 && (firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1])) ? !1 : void 0; + }), firstMatch; + } + function resolveNdxInitializer(pos, alternateNdx) { + var bestMatch = selectBestMatch(pos, alternateNdx); + return bestMatch ? bestMatch.locator.slice(bestMatch.alternation + 1) : []; + } + if (testPos > 1e4) throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet().mask; + if (testPos === pos && void 0 === match.matches) return matches.push({ + match: match, + locator: loopNdx.reverse(), + cd: cacheDependency + }), !0; + if (void 0 !== match.matches) { + if (match.isGroup && quantifierRecurse !== match) { + if (match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx)) return !0; + } else if (match.isOptional) { + var optionalToken = match; + if (match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse)) { + if (latestMatch = matches[matches.length - 1].match, !isFirstMatch(latestMatch, optionalToken)) return !0; + insertStop = !0, testPos = pos; + } + } else if (match.isAlternator) { + var maltMatches, alternateToken = match, malternateMatches = [], currentMatches = matches.slice(), loopNdxCnt = loopNdx.length, altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1; + if (-1 === altIndex || "string" == typeof altIndex) { + var amndx, currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr = []; + if ("string" == typeof altIndex) altIndexArr = altIndex.split(","); else for (amndx = 0; amndx < alternateToken.matches.length; amndx++) altIndexArr.push(amndx); + for (var ndx = 0; ndx < altIndexArr.length; ndx++) { + if (amndx = parseInt(altIndexArr[ndx]), matches = [], ndxInitializer = resolveNdxInitializer(testPos, amndx), + match = handleMatch(alternateToken.matches[amndx] || maskToken.matches[amndx], [ amndx ].concat(loopNdx), quantifierRecurse) || match, + match !== !0 && void 0 !== match && altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length) { + var ntndx = $.inArray(match, maskToken.matches) + 1; + maskToken.matches.length > ntndx && (match = handleMatch(maskToken.matches[ntndx], [ ntndx ].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse), + match && (altIndexArr.push(ntndx.toString()), $.each(matches, function(ndx, lmnt) { + lmnt.alternation = loopNdx.length - 1; + }))); + } + maltMatches = matches.slice(), testPos = currentPos, matches = []; + for (var i = 0; i < ndxInitializerClone.length; i++) ndxInitializer[i] = ndxInitializerClone[i]; + for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) { + var altMatch = maltMatches[ndx1]; + altMatch.alternation = altMatch.alternation || loopNdxCnt; + for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) { + var altMatch2 = malternateMatches[ndx2]; + if (altMatch.match.def === altMatch2.match.def && ("string" != typeof altIndex || -1 !== $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr))) { + altMatch.match.mask === altMatch2.match.mask && (maltMatches.splice(ndx1, 1), ndx1--), + -1 === altMatch2.locator[altMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) && (altMatch2.locator[altMatch.alternation] = altMatch2.locator[altMatch.alternation] + "," + altMatch.locator[altMatch.alternation], + altMatch2.alternation = altMatch.alternation); + break; + } + } + } + malternateMatches = malternateMatches.concat(maltMatches); + } + "string" == typeof altIndex && (malternateMatches = $.map(malternateMatches, function(lmnt, ndx) { + if (isFinite(ndx)) { + var mamatch, alternation = lmnt.alternation, altLocArr = lmnt.locator[alternation].toString().split(","); + lmnt.locator[alternation] = void 0, lmnt.alternation = void 0; + for (var alndx = 0; alndx < altLocArr.length; alndx++) mamatch = -1 !== $.inArray(altLocArr[alndx], altIndexArr), + mamatch && (void 0 !== lmnt.locator[alternation] ? (lmnt.locator[alternation] += ",", + lmnt.locator[alternation] += altLocArr[alndx]) : lmnt.locator[alternation] = parseInt(altLocArr[alndx]), + lmnt.alternation = alternation); + if (void 0 !== lmnt.locator[alternation]) return lmnt; + } + })), matches = currentMatches.concat(malternateMatches), testPos = pos, insertStop = matches.length > 0; + } else match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [ altIndex ].concat(loopNdx), quantifierRecurse); + if (match) return !0; + } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) for (var qt = match, qndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max) && pos >= testPos; qndx++) { + var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1]; + if (match = handleMatch(tokenGroup, [ qndx ].concat(loopNdx), tokenGroup)) { + if (latestMatch = matches[matches.length - 1].match, latestMatch.optionalQuantifier = qndx > qt.quantifier.min - 1, + isFirstMatch(latestMatch, tokenGroup)) { + if (qndx > qt.quantifier.min - 1) { + insertStop = !0, testPos = pos; + break; + } + return !0; + } + return !0; + } + } else if (match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse)) return !0; + } else testPos++; + } + for (var tndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; tndx < maskToken.matches.length; tndx++) if (maskToken.matches[tndx].isQuantifier !== !0) { + var match = handleMatch(maskToken.matches[tndx], [ tndx ].concat(loopNdx), quantifierRecurse); + if (match && testPos === pos) return match; + if (testPos > pos) break; + } + } + function mergeLocators(tests) { + var test = tests[0] || tests; + return test.locator.slice(); + } + var latestMatch, maskTokens = getMaskSet().maskToken, testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [ 0 ], matches = [], insertStop = !1, cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : ""; + if (pos > -1) { + if (void 0 === ndxIntlzr) { + for (var test, previousPos = pos - 1; void 0 === (test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) && previousPos > -1; ) previousPos--; + void 0 !== test && previousPos > -1 && (ndxInitializer = mergeLocators(test), cacheDependency = ndxInitializer.join(""), + test = test[0] || test, testPos = previousPos); + } + if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) return getMaskSet().tests[pos]; + for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) { + var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [ mtndx ]); + if (match && testPos === pos || testPos > pos) break; + } + } + return (0 === matches.length || insertStop) && matches.push({ + match: { + fn: null, + cardinality: 0, + optionality: !0, + casing: null, + def: "" + }, + locator: [] + }), getMaskSet().tests[pos] = $.extend(!0, [], matches), getMaskSet().tests[pos]; + } + function getBufferTemplate() { + return void 0 === getMaskSet()._buffer && (getMaskSet()._buffer = getMaskTemplate(!1, 1)), + getMaskSet()._buffer; + } + function getBuffer(noCache) { + if (void 0 === getMaskSet().buffer || noCache === !0) { + if (noCache === !0) for (var testNdx in getMaskSet().tests) void 0 === getMaskSet().validPositions[testNdx] && delete getMaskSet().tests[testNdx]; + getMaskSet().buffer = getMaskTemplate(!0, getLastValidPosition(), !0); + } + return getMaskSet().buffer; + } + function refreshFromBuffer(start, end, buffer) { + var i; + if (buffer = buffer, start === !0) resetMaskSet(), start = 0, end = buffer.length; else for (i = start; end > i; i++) delete getMaskSet().validPositions[i], + delete getMaskSet().tests[i]; + for (i = start; end > i; i++) resetMaskSet(!0), buffer[i] !== opts.skipOptionalPartCharacter && isValid(i, buffer[i], !0, !0); + } + function casing(elem, test) { + switch (test.casing) { + case "upper": + elem = elem.toUpperCase(); + break; + + case "lower": + elem = elem.toLowerCase(); + } + return elem; + } + function checkAlternationMatch(altArr1, altArr2) { + for (var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1), isMatch = !1, alndx = 0; alndx < altArr1.length; alndx++) if (-1 !== $.inArray(altArr1[alndx], altArrC)) { + isMatch = !0; + break; + } + return isMatch; + } + function isValid(pos, c, strict, fromSetValid) { + function _isValid(position, c, strict, fromSetValid) { + var rslt = !1; + return $.each(getTests(position), function(ndx, tst) { + for (var test = tst.match, loopend = c ? 1 : 0, chrs = "", i = test.cardinality; i > loopend; i--) chrs += getBufferElement(position - (i - 1)); + if (c && (chrs += c), getBuffer(!0), rslt = null != test.fn ? test.fn.test(chrs, getMaskSet(), position, strict, opts) : c !== test.def && c !== opts.skipOptionalPartCharacter || "" === test.def ? !1 : { + c: test.placeholder || test.def, + pos: position + }, rslt !== !1) { + var elem = void 0 !== rslt.c ? rslt.c : c; + elem = elem === opts.skipOptionalPartCharacter && null === test.fn ? test.placeholder || test.def : elem; + var validatedPos = position, possibleModifiedBuffer = getBuffer(); + if (void 0 !== rslt.remove && ($.isArray(rslt.remove) || (rslt.remove = [ rslt.remove ]), + $.each(rslt.remove.sort(function(a, b) { + return b - a; + }), function(ndx, lmnt) { + stripValidPositions(lmnt, lmnt + 1, !0); + })), void 0 !== rslt.insert && ($.isArray(rslt.insert) || (rslt.insert = [ rslt.insert ]), + $.each(rslt.insert.sort(function(a, b) { + return a - b; + }), function(ndx, lmnt) { + isValid(lmnt.pos, lmnt.c, !1, fromSetValid); + })), rslt.refreshFromBuffer) { + var refresh = rslt.refreshFromBuffer; + if (strict = !0, refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end, possibleModifiedBuffer), + void 0 === rslt.pos && void 0 === rslt.c) return rslt.pos = getLastValidPosition(), + !1; + if (validatedPos = void 0 !== rslt.pos ? rslt.pos : position, validatedPos !== position) return rslt = $.extend(rslt, isValid(validatedPos, elem, !0, fromSetValid)), + !1; + } else if (rslt !== !0 && void 0 !== rslt.pos && rslt.pos !== position && (validatedPos = rslt.pos, + refreshFromBuffer(position, validatedPos, getBuffer().slice()), validatedPos !== position)) return rslt = $.extend(rslt, isValid(validatedPos, elem, !0)), + !1; + return rslt !== !0 && void 0 === rslt.pos && void 0 === rslt.c ? !1 : (ndx > 0 && resetMaskSet(!0), + setValidPosition(validatedPos, $.extend({}, tst, { + input: casing(elem, test) + }), fromSetValid) || (rslt = !1), !1); + } + }), rslt; + } + function alternate(pos, c, strict, fromSetValid) { + for (var lastAlt, alternation, isValidRslt, altPos, i, validPos, validPsClone = $.extend(!0, {}, getMaskSet().validPositions), testsClone = $.extend(!0, {}, getMaskSet().tests), lAlt = getLastValidPosition(); lAlt >= 0 && (altPos = getMaskSet().validPositions[lAlt], + !altPos || void 0 === altPos.alternation || (lastAlt = lAlt, alternation = getMaskSet().validPositions[lastAlt].alternation, + getTestTemplate(lastAlt).locator[altPos.alternation] === altPos.locator[altPos.alternation])); lAlt--) ; + if (void 0 !== alternation) { + lastAlt = parseInt(lastAlt); + for (var decisionPos in getMaskSet().validPositions) if (decisionPos = parseInt(decisionPos), + altPos = getMaskSet().validPositions[decisionPos], decisionPos >= lastAlt && void 0 !== altPos.alternation) { + var altNdxs; + 0 === lastAlt ? (altNdxs = [], $.each(getMaskSet().tests[lastAlt], function(ndx, test) { + void 0 !== test.locator[alternation] && (altNdxs = altNdxs.concat(test.locator[alternation].toString().split(","))); + })) : altNdxs = getMaskSet().validPositions[lastAlt].locator[alternation].toString().split(","); + var decisionTaker = void 0 !== altPos.locator[alternation] ? altPos.locator[alternation] : altNdxs[0]; + decisionTaker.length > 0 && (decisionTaker = decisionTaker.split(",")[0]); + for (var mndx = 0; mndx < altNdxs.length; mndx++) { + var validInputs = [], staticInputsBeforePos = 0, staticInputsBeforePosAlternate = 0; + if (decisionTaker < altNdxs[mndx]) { + for (var possibilityPos, possibilities, dp = decisionPos; dp >= 0; dp--) if (possibilityPos = getMaskSet().validPositions[dp], + void 0 !== possibilityPos) { + var bestMatch = selectBestMatch(dp, altNdxs[mndx]); + getMaskSet().validPositions[dp].match.def !== bestMatch.match.def && (validInputs.push(getMaskSet().validPositions[dp].input), + getMaskSet().validPositions[dp] = bestMatch, getMaskSet().validPositions[dp].input = getPlaceholder(dp), + null === getMaskSet().validPositions[dp].match.fn && staticInputsBeforePosAlternate++, + possibilityPos = bestMatch), possibilities = possibilityPos.locator[alternation], + possibilityPos.locator[alternation] = parseInt(altNdxs[mndx]); + break; + } + if (decisionTaker !== possibilityPos.locator[alternation]) { + for (i = decisionPos + 1; i < getLastValidPosition(void 0, !0) + 1; i++) validPos = getMaskSet().validPositions[i], + validPos && null != validPos.match.fn ? validInputs.push(validPos.input) : pos > i && staticInputsBeforePos++, + delete getMaskSet().validPositions[i], delete getMaskSet().tests[i]; + for (resetMaskSet(!0), opts.keepStatic = !opts.keepStatic, isValidRslt = !0; validInputs.length > 0; ) { + var input = validInputs.shift(); + if (input !== opts.skipOptionalPartCharacter && !(isValidRslt = isValid(getLastValidPosition(void 0, !0) + 1, input, !1, fromSetValid))) break; + } + if (possibilityPos.alternation = alternation, possibilityPos.locator[alternation] = possibilities, + isValidRslt) { + var targetLvp = getLastValidPosition(pos) + 1; + for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) validPos = getMaskSet().validPositions[i], + (void 0 === validPos || null == validPos.match.fn) && pos > i && staticInputsBeforePosAlternate++; + pos += staticInputsBeforePosAlternate - staticInputsBeforePos, isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid); + } + if (opts.keepStatic = !opts.keepStatic, isValidRslt) return isValidRslt; + resetMaskSet(), getMaskSet().validPositions = $.extend(!0, {}, validPsClone), getMaskSet().tests = $.extend(!0, {}, testsClone); + } + } + } + break; + } + } + return !1; + } + function trackbackAlternations(originalPos, newPos) { + for (var vp = getMaskSet().validPositions[newPos], targetLocator = vp.locator, tll = targetLocator.length, ps = originalPos; newPos > ps; ps++) if (void 0 === getMaskSet().validPositions[ps] && !isMask(ps, !0)) { + var tests = getTests(ps), bestMatch = tests[0], equality = -1; + $.each(tests, function(ndx, tst) { + for (var i = 0; tll > i && (void 0 !== tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(","), targetLocator[i].toString().split(","))); i++) i > equality && (equality = i, + bestMatch = tst); + }), setValidPosition(ps, $.extend({}, bestMatch, { + input: bestMatch.match.placeholder || bestMatch.match.def + }), !0); + } + } + strict = strict === !0; + for (var buffer = getBuffer(), pndx = pos - 1; pndx > -1 && !getMaskSet().validPositions[pndx]; pndx--) ; + for (pndx++; pos > pndx; pndx++) void 0 === getMaskSet().validPositions[pndx] && ((!isMask(pndx) || buffer[pndx] !== getPlaceholder(pndx)) && getTests(pndx).length > 1 || buffer[pndx] === opts.radixPoint || "0" === buffer[pndx] && $.inArray(opts.radixPoint, buffer) < pndx) && _isValid(pndx, buffer[pndx], !0, fromSetValid); + var maskPos = pos, result = !1, positionsClone = $.extend(!0, {}, getMaskSet().validPositions); + if (maskPos < getMaskLength() && (result = _isValid(maskPos, c, strict, fromSetValid), + (!strict || fromSetValid === !0) && result === !1)) { + var currentPosValid = getMaskSet().validPositions[maskPos]; + if (!currentPosValid || null !== currentPosValid.match.fn || currentPosValid.match.def !== c && c !== opts.skipOptionalPartCharacter) { + if ((opts.insertMode || void 0 === getMaskSet().validPositions[seekNext(maskPos)]) && !isMask(maskPos, !0)) { + var staticChar = getTestTemplate(maskPos).match, staticChar = staticChar.placeholder || staticChar.def; + _isValid(maskPos, staticChar, strict, fromSetValid); + for (var nPos = maskPos + 1, snPos = seekNext(maskPos); snPos >= nPos; nPos++) if (result = _isValid(nPos, c, strict, fromSetValid), + result !== !1) { + trackbackAlternations(maskPos, nPos), maskPos = nPos; + break; + } + } + } else result = { + caret: seekNext(maskPos) + }; + } + if (result === !1 && opts.keepStatic && (result = alternate(pos, c, strict, fromSetValid)), + result === !0 && (result = { + pos: maskPos + }), $.isFunction(opts.postValidation) && result !== !1 && !strict && fromSetValid !== !0) { + var postValidResult = opts.postValidation(getBuffer(!0), result, opts); + if (postValidResult) { + if (postValidResult.refreshFromBuffer) { + var refresh = postValidResult.refreshFromBuffer; + refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end, postValidResult.buffer), + resetMaskSet(!0), result = postValidResult; + } + } else resetMaskSet(!0), getMaskSet().validPositions = $.extend(!0, {}, positionsClone), + result = !1; + } + return result; + } + function isMask(pos, strict) { + var test; + if (strict ? (test = getTestTemplate(pos).match, "" == test.def && (test = getTest(pos))) : test = getTest(pos), + null != test.fn) return test.fn; + if (strict !== !0 && pos > -1 && !opts.keepStatic && void 0 === getMaskSet().validPositions[pos]) { + var tests = getTests(pos); + return tests.length > 2; + } + return !1; + } + function getMaskLength() { + var maskLength; + maxLength = void 0 !== el ? el.maxLength : void 0, -1 === maxLength && (maxLength = void 0); + var pos, lvp = getLastValidPosition(), testPos = getMaskSet().validPositions[lvp], ndxIntlzr = void 0 !== testPos ? testPos.locator.slice() : void 0; + for (pos = lvp + 1; void 0 === testPos || null !== testPos.match.fn || null === testPos.match.fn && "" !== testPos.match.def; pos++) testPos = getTestTemplate(pos, ndxIntlzr, pos - 1), + ndxIntlzr = testPos.locator.slice(); + var lastTest = getTest(pos - 1); + return maskLength = "" !== lastTest.def ? pos : pos - 1, void 0 === maxLength || maxLength > maskLength ? maskLength : maxLength; + } + function seekNext(pos, newBlock) { + var maskL = getMaskLength(); + if (pos >= maskL) return maskL; + for (var position = pos; ++position < maskL && (newBlock === !0 && (getTest(position).newBlockMarker !== !0 || !isMask(position)) || newBlock !== !0 && !isMask(position) && (opts.nojumps !== !0 || opts.nojumpsThreshold > position)); ) ; + return position; + } + function seekPrevious(pos, newBlock) { + var position = pos; + if (0 >= position) return 0; + for (;--position > 0 && (newBlock === !0 && getTest(position).newBlockMarker !== !0 || newBlock !== !0 && !isMask(position)); ) ; + return position; + } + function getBufferElement(position) { + return void 0 === getMaskSet().validPositions[position] ? getPlaceholder(position) : getMaskSet().validPositions[position].input; + } + function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) { + if (event && $.isFunction(opts.onBeforeWrite)) { + var result = opts.onBeforeWrite(event, buffer, caretPos, opts); + if (result) { + if (result.refreshFromBuffer) { + var refresh = result.refreshFromBuffer; + refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end, result.buffer || buffer), + buffer = getBuffer(!0); + } + void 0 !== caretPos && (caretPos = void 0 !== result.caret ? result.caret : caretPos); + } + } + input.inputmask._valueSet(buffer.join("")), void 0 === caretPos || void 0 !== event && "blur" === event.type || caret(input, caretPos), + triggerInputEvent === !0 && (skipInputEvent = !0, $(input).trigger("input")); + } + function getPlaceholder(pos, test) { + if (test = test || getTest(pos), void 0 !== test.placeholder) return test.placeholder; + if (null === test.fn) { + if (pos > -1 && !opts.keepStatic && void 0 === getMaskSet().validPositions[pos]) { + var prevTest, tests = getTests(pos), staticAlternations = 0; + if (tests.length > 2) for (var i = 0; i < tests.length; i++) if (tests[i].match.optionality !== !0 && tests[i].match.optionalQuantifier !== !0 && (null === tests[i].match.fn || void 0 === prevTest || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, !0, opts) !== !1) && (staticAlternations++, + null === tests[i].match.fn && (prevTest = tests[i]), staticAlternations > 1)) return opts.placeholder.charAt(pos % opts.placeholder.length); + } + return test.def; + } + return opts.placeholder.charAt(pos % opts.placeholder.length); + } + function checkVal(input, writeOut, strict, nptvl) { + function isTemplateMatch() { + var isMatch = !1, charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join("").indexOf(charCodes); + if (-1 !== charCodeNdx && !isMask(initialNdx)) { + isMatch = !0; + for (var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx), i = 0; i < bufferTemplateArr.length; i++) if (" " !== bufferTemplateArr[i]) { + isMatch = !1; + break; + } + } + return isMatch; + } + var inputValue = nptvl.slice(), charCodes = "", initialNdx = 0; + if (resetMaskSet(), getMaskSet().p = seekNext(-1), !strict) if (opts.autoUnmask !== !0) { + var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""), matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g")); + matches && matches.length > 0 && (inputValue.splice(0, matches.length * staticInput.length), + initialNdx = seekNext(initialNdx)); + } else initialNdx = seekNext(initialNdx); + $.each(inputValue, function(ndx, charCode) { + if (void 0 !== charCode) { + var keypress = new $.Event("keypress"); + keypress.which = charCode.charCodeAt(0), charCodes += charCode; + var lvp = getLastValidPosition(void 0, !0), lvTest = getMaskSet().validPositions[lvp], nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : void 0, lvp); + if (!isTemplateMatch() || strict || opts.autoUnmask) { + var pos = strict ? ndx : null == nextTest.match.fn && nextTest.match.optionality && lvp + 1 < getMaskSet().p ? lvp + 1 : getMaskSet().p; + keypressEvent.call(input, keypress, !0, !1, strict, pos), initialNdx = pos + 1, + charCodes = ""; + } else keypressEvent.call(input, keypress, !0, !1, !0, lvp + 1); + } + }), writeOut && writeBuffer(input, getBuffer(), document.activeElement === input ? seekNext(getLastValidPosition(0)) : void 0, new $.Event("checkval")); + } + function unmaskedvalue(input) { + if (input && void 0 === input.inputmask) return input.value; + var umValue = [], vps = getMaskSet().validPositions; + for (var pndx in vps) vps[pndx].match && null != vps[pndx].match.fn && umValue.push(vps[pndx].input); + var unmaskedValue = 0 === umValue.length ? null : (isRTL ? umValue.reverse() : umValue).join(""); + if (null !== unmaskedValue) { + var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join(""); + $.isFunction(opts.onUnMask) && (unmaskedValue = opts.onUnMask(bufferValue, unmaskedValue, opts) || unmaskedValue); + } + return unmaskedValue; + } + function caret(input, begin, end, notranslate) { + function translatePosition(pos) { + if (notranslate !== !0 && isRTL && "number" == typeof pos && (!opts.greedy || "" !== opts.placeholder)) { + var bffrLght = getBuffer().join("").length; + pos = bffrLght - pos; + } + return pos; + } + var range; + if ("number" != typeof begin) return input.setSelectionRange ? (begin = input.selectionStart, + end = input.selectionEnd) : window.getSelection ? (range = window.getSelection().getRangeAt(0), + (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) && (begin = range.startOffset, + end = range.endOffset)) : document.selection && document.selection.createRange && (range = document.selection.createRange(), + begin = 0 - range.duplicate().moveStart("character", -1e5), end = begin + range.text.length), + { + begin: translatePosition(begin), + end: translatePosition(end) + }; + begin = translatePosition(begin), end = translatePosition(end), end = "number" == typeof end ? end : begin; + var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end; + if (input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0, mobile || opts.insertMode !== !1 || begin !== end || end++, + input.setSelectionRange) input.selectionStart = begin, input.selectionEnd = end; else if (window.getSelection) { + if (range = document.createRange(), void 0 === input.firstChild || null === input.firstChild) { + var textNode = document.createTextNode(""); + input.appendChild(textNode); + } + range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length), + range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length), + range.collapse(!0); + var sel = window.getSelection(); + sel.removeAllRanges(), sel.addRange(range); + } else input.createTextRange && (range = input.createTextRange(), range.collapse(!0), + range.moveEnd("character", end), range.moveStart("character", begin), range.select()); + } + function determineLastRequiredPosition(returnDefinition) { + var pos, testPos, buffer = getBuffer(), bl = buffer.length, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet().validPositions[lvp], ndxIntlzr = void 0 !== lvTest ? lvTest.locator.slice() : void 0; + for (pos = lvp + 1; pos < buffer.length; pos++) testPos = getTestTemplate(pos, ndxIntlzr, pos - 1), + ndxIntlzr = testPos.locator.slice(), positions[pos] = $.extend(!0, {}, testPos); + var lvTestAlt = lvTest && void 0 !== lvTest.alternation ? lvTest.locator[lvTest.alternation] : void 0; + for (pos = bl - 1; pos > lvp && (testPos = positions[pos], (testPos.match.optionality || testPos.match.optionalQuantifier || lvTestAlt && (lvTestAlt !== positions[pos].locator[lvTest.alternation] && null != testPos.match.fn || null === testPos.match.fn && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && "" !== getTests(pos)[0].def)) && buffer[pos] === getPlaceholder(pos, testPos.match)); pos--) bl--; + return returnDefinition ? { + l: bl, + def: positions[bl] ? positions[bl].match : void 0 + } : bl; + } + function clearOptionalTail(buffer) { + for (var rl = determineLastRequiredPosition(), lmib = buffer.length - 1; lmib > rl && !isMask(lmib); lmib--) ; + return buffer.splice(rl, lmib + 1 - rl), buffer; + } + function isComplete(buffer) { + if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts); + if ("*" === opts.repeat) return void 0; + var complete = !1, lrp = determineLastRequiredPosition(!0), aml = seekPrevious(lrp.l); + if (void 0 === lrp.def || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) { + complete = !0; + for (var i = 0; aml >= i; i++) { + var test = getTestTemplate(i).match; + if (null !== test.fn && void 0 === getMaskSet().validPositions[i] && test.optionality !== !0 && test.optionalQuantifier !== !0 || null === test.fn && buffer[i] !== getPlaceholder(i, test)) { + complete = !1; + break; + } + } + } + return complete; + } + function isSelection(begin, end) { + return isRTL ? begin - end > 1 || begin - end === 1 && opts.insertMode : end - begin > 1 || end - begin === 1 && opts.insertMode; + } + function patchValueProperty(npt) { + function patchValhook(type) { + if ($.valHooks && (void 0 === $.valHooks[type] || $.valHooks[type].inputmaskpatch !== !0)) { + var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) { + return elem.value; + }, valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) { + return elem.value = value, elem; + }; + $.valHooks[type] = { + get: function(elem) { + if (elem.inputmask) { + if (elem.inputmask.opts.autoUnmask) return elem.inputmask.unmaskedvalue(); + var result = valhookGet(elem), maskset = elem.inputmask.maskset, bufferTemplate = maskset._buffer; + return bufferTemplate = bufferTemplate ? bufferTemplate.join("") : "", result !== bufferTemplate ? result : ""; + } + return valhookGet(elem); + }, + set: function(elem, value) { + var result, $elem = $(elem); + return result = valhookSet(elem, value), elem.inputmask && $elem.trigger("setvalue"), + result; + }, + inputmaskpatch: !0 + }; + } + } + function getter() { + return this.inputmask ? this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : valueGet.call(this) !== getBufferTemplate().join("") ? document.activeElement === this && opts.clearMaskOnLostFocus ? (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") : valueGet.call(this) : "" : valueGet.call(this); + } + function setter(value) { + valueSet.call(this, value), this.inputmask && $(this).trigger("setvalue"); + } + function installNativeValueSetFallback(npt) { + EventRuler.on(npt, "mouseenter", function(event) { + var $input = $(this), input = this, value = input.inputmask._valueGet(); + value !== getBuffer().join("") && getLastValidPosition() > 0 && $input.trigger("setvalue"); + }); + } + var valueGet, valueSet; + npt.inputmask.__valueGet || (Object.getOwnPropertyDescriptor && void 0 === npt.value ? (valueGet = function() { + return this.textContent; + }, valueSet = function(value) { + this.textContent = value; + }, Object.defineProperty(npt, "value", { + get: getter, + set: setter + })) : document.__lookupGetter__ && npt.__lookupGetter__("value") ? (valueGet = npt.__lookupGetter__("value"), + valueSet = npt.__lookupSetter__("value"), npt.__defineGetter__("value", getter), + npt.__defineSetter__("value", setter)) : (valueGet = function() { + return npt.value; + }, valueSet = function(value) { + npt.value = value; + }, patchValhook(npt.type), installNativeValueSetFallback(npt)), npt.inputmask.__valueGet = valueGet, + npt.inputmask._valueGet = function(overruleRTL) { + return isRTL && overruleRTL !== !0 ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el); + }, npt.inputmask.__valueSet = valueSet, npt.inputmask._valueSet = function(value, overruleRTL) { + valueSet.call(this.el, null === value || void 0 === value ? "" : overruleRTL !== !0 && isRTL ? value.split("").reverse().join("") : value); + }); + } + function handleRemove(input, k, pos, strict) { + function generalize() { + if (opts.keepStatic) { + resetMaskSet(!0); + var lastAlt, validInputs = [], positionsClone = $.extend(!0, {}, getMaskSet().validPositions); + for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) { + var validPos = getMaskSet().validPositions[lastAlt]; + if (validPos && (null != validPos.match.fn && validInputs.push(validPos.input), + delete getMaskSet().validPositions[lastAlt], void 0 !== validPos.alternation && validPos.locator[validPos.alternation] === getTestTemplate(lastAlt).locator[validPos.alternation])) break; + } + if (lastAlt > -1) for (;validInputs.length > 0; ) { + getMaskSet().p = seekNext(getLastValidPosition()); + var keypress = new $.Event("keypress"); + keypress.which = validInputs.pop().charCodeAt(0), keypressEvent.call(input, keypress, !0, !1, !1, getMaskSet().p); + } else getMaskSet().validPositions = $.extend(!0, {}, positionsClone); + } + } + if ((opts.numericInput || isRTL) && (k === Inputmask.keyCode.BACKSPACE ? k = Inputmask.keyCode.DELETE : k === Inputmask.keyCode.DELETE && (k = Inputmask.keyCode.BACKSPACE), + isRTL)) { + var pend = pos.end; + pos.end = pos.begin, pos.begin = pend; + } + k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === !1) ? (pos.begin = seekPrevious(pos.begin), + void 0 === getMaskSet().validPositions[pos.begin] || getMaskSet().validPositions[pos.begin].input !== opts.groupSeparator && getMaskSet().validPositions[pos.begin].input !== opts.radixPoint || pos.begin--) : k === Inputmask.keyCode.DELETE && pos.begin === pos.end && (pos.end = isMask(pos.end) ? pos.end + 1 : seekNext(pos.end) + 1, + void 0 === getMaskSet().validPositions[pos.begin] || getMaskSet().validPositions[pos.begin].input !== opts.groupSeparator && getMaskSet().validPositions[pos.begin].input !== opts.radixPoint || pos.end++), + stripValidPositions(pos.begin, pos.end, !1, strict), strict !== !0 && generalize(); + var lvp = getLastValidPosition(pos.begin); + lvp < pos.begin ? (-1 === lvp && resetMaskSet(), getMaskSet().p = seekNext(lvp)) : strict !== !0 && (getMaskSet().p = pos.begin); + } + function keydownEvent(e) { + var input = this, $input = $(input), k = e.keyCode, pos = caret(input); + if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || iphone && 127 === k || e.ctrlKey && 88 === k && !isInputEventSupported("cut")) e.preventDefault(), + 88 === k && (undoValue = getBuffer().join("")), handleRemove(input, k, pos), writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join("")), + input.inputmask._valueGet() === getBufferTemplate().join("") ? $input.trigger("cleared") : isComplete(getBuffer()) === !0 && $input.trigger("complete"), + opts.showTooltip && (input.title = opts.tooltip || getMaskSet().mask); else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { + e.preventDefault(); + var caretPos = seekNext(getLastValidPosition()); + opts.insertMode || caretPos !== getMaskLength() || e.shiftKey || caretPos--, caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, !0); + } else k === Inputmask.keyCode.HOME && !e.shiftKey || k === Inputmask.keyCode.PAGE_UP ? (e.preventDefault(), + caret(input, 0, e.shiftKey ? pos.begin : 0, !0)) : (opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE || 90 === k && e.ctrlKey) && e.altKey !== !0 ? (checkVal(input, !0, !1, undoValue.split("")), + $input.trigger("click")) : k !== Inputmask.keyCode.INSERT || e.shiftKey || e.ctrlKey ? opts.tabThrough === !0 && k === Inputmask.keyCode.TAB ? (e.shiftKey === !0 ? (null === getTest(pos.begin).fn && (pos.begin = seekNext(pos.begin)), + pos.end = seekPrevious(pos.begin, !0), pos.begin = seekPrevious(pos.end, !0)) : (pos.begin = seekNext(pos.begin, !0), + pos.end = seekNext(pos.begin, !0), pos.end < getMaskLength() && pos.end--), pos.begin < getMaskLength() && (e.preventDefault(), + caret(input, pos.begin, pos.end))) : opts.insertMode !== !1 || e.shiftKey || (k === Inputmask.keyCode.RIGHT ? setTimeout(function() { + var caretPos = caret(input); + caret(input, caretPos.begin); + }, 0) : k === Inputmask.keyCode.LEFT && setTimeout(function() { + var caretPos = caret(input); + caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1); + }, 0)) : (opts.insertMode = !opts.insertMode, caret(input, opts.insertMode || pos.begin !== getMaskLength() ? pos.begin : pos.begin - 1)); + opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts), ignorable = -1 !== $.inArray(k, opts.ignorables); + } + function keypressEvent(e, checkval, writeOut, strict, ndx) { + var input = this, $input = $(input), k = e.which || e.charCode || e.keyCode; + if (!(checkval === !0 || e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable)) return k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("") && (undoValue = getBuffer().join(""), + setTimeout(function() { + $input.trigger("change"); + }, 0)), !0; + if (k) { + 46 === k && e.shiftKey === !1 && "," === opts.radixPoint && (k = 44); + var forwardPosition, pos = checkval ? { + begin: ndx, + end: ndx + } : caret(input), c = String.fromCharCode(k), isSlctn = isSelection(pos.begin, pos.end); + isSlctn && (getMaskSet().undoPositions = $.extend(!0, {}, getMaskSet().validPositions), + handleRemove(input, Inputmask.keyCode.DELETE, pos, !0), pos.begin = getMaskSet().p, + opts.insertMode || (opts.insertMode = !opts.insertMode, setValidPosition(pos.begin, strict), + opts.insertMode = !opts.insertMode), isSlctn = !opts.multi), getMaskSet().writeOutBuffer = !0; + var p = isRTL && !isSlctn ? pos.end : pos.begin, valResult = isValid(p, c, strict); + if (valResult !== !1) { + if (valResult !== !0 && (p = void 0 !== valResult.pos ? valResult.pos : p, c = void 0 !== valResult.c ? valResult.c : c), + resetMaskSet(!0), void 0 !== valResult.caret) forwardPosition = valResult.caret; else { + var vps = getMaskSet().validPositions; + forwardPosition = !opts.keepStatic && (void 0 !== vps[p + 1] && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || void 0 !== vps[p].alternation) ? p + 1 : seekNext(p); + } + getMaskSet().p = forwardPosition; + } + if (writeOut !== !1) { + var self = this; + if (setTimeout(function() { + opts.onKeyValidation.call(self, k, valResult, opts); + }, 0), getMaskSet().writeOutBuffer && valResult !== !1) { + var buffer = getBuffer(); + writeBuffer(input, buffer, opts.numericInput && void 0 === valResult.caret ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== !0), + checkval !== !0 && setTimeout(function() { + isComplete(buffer) === !0 && $input.trigger("complete"); + }, 0); + } else isSlctn && (getMaskSet().buffer = void 0, getMaskSet().validPositions = getMaskSet().undoPositions); + } else isSlctn && (getMaskSet().buffer = void 0, getMaskSet().validPositions = getMaskSet().undoPositions); + if (opts.showTooltip && (input.title = opts.tooltip || getMaskSet().mask), checkval && $.isFunction(opts.onBeforeWrite)) { + var result = opts.onBeforeWrite(e, getBuffer(), forwardPosition, opts); + if (result && result.refreshFromBuffer) { + var refresh = result.refreshFromBuffer; + refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end, result.buffer), + resetMaskSet(!0), result.caret && (getMaskSet().p = result.caret); + } + } + if (e.preventDefault(), checkval) return valResult; + } + } + function pasteEvent(e) { + var input = this, ev = e.originalEvent || e, $input = $(input), inputValue = input.inputmask._valueGet(!0), caretPos = caret(input), valueBeforeCaret = inputValue.substr(0, caretPos.begin), valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length); + valueBeforeCaret === getBufferTemplate().slice(0, caretPos.begin).join("") && (valueBeforeCaret = ""), + valueAfterCaret === getBufferTemplate().slice(caretPos.end).join("") && (valueAfterCaret = ""), + window.clipboardData && window.clipboardData.getData ? inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret : ev.clipboardData && ev.clipboardData.getData && (inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret); + var pasteValue = inputValue; + if ($.isFunction(opts.onBeforePaste)) { + if (pasteValue = opts.onBeforePaste(inputValue, opts), pasteValue === !1) return e.preventDefault(), + !1; + pasteValue || (pasteValue = inputValue); + } + return checkVal(input, !1, !1, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split("")), + writeBuffer(input, getBuffer(), void 0, e, !0), $input.trigger("click"), isComplete(getBuffer()) === !0 && $input.trigger("complete"), + !1; + } + function inputFallBackEvent(e) { + var input = this, inputValue = input.inputmask._valueGet(); + if (getBuffer().join("") !== inputValue) { + var caretPos = caret(input); + if (inputValue = inputValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), ""), + iemobile) { + var inputChar = inputValue.replace(getBuffer().join(""), ""); + if (1 === inputChar.length) { + var keypress = new $.Event("keypress"); + return keypress.which = inputChar.charCodeAt(0), keypressEvent.call(input, keypress, !0, !0, !1, getMaskSet().validPositions[caretPos.begin - 1] ? caretPos.begin : caretPos.begin - 1), + !1; + } + } + if (caretPos.begin > inputValue.length && (caret(input, inputValue.length), caretPos = caret(input)), + getBuffer().length - inputValue.length !== 1 || inputValue.charAt(caretPos.begin) === getBuffer()[caretPos.begin] || inputValue.charAt(caretPos.begin + 1) === getBuffer()[caretPos.begin] || isMask(caretPos.begin)) { + for (var lvp = getLastValidPosition() + 1, bufferTemplate = getBuffer().slice(lvp).join(""); null === inputValue.match(Inputmask.escapeRegex(bufferTemplate) + "$"); ) bufferTemplate = bufferTemplate.slice(1); + inputValue = inputValue.replace(bufferTemplate, ""), inputValue = inputValue.split(""), + checkVal(input, !0, !1, inputValue), isComplete(getBuffer()) === !0 && $(input).trigger("complete"); + } else e.keyCode = Inputmask.keyCode.BACKSPACE, keydownEvent.call(input, e); + e.preventDefault(); + } + } + function compositionStartEvent(e) { + var ev = e.originalEvent || e; + undoValue = getBuffer().join(""), "" === compositionData || 0 !== ev.data.indexOf(compositionData); + } + function compositionUpdateEvent(e) { + var input = this, ev = e.originalEvent || e, inputBuffer = getBuffer().join(""); + 0 === ev.data.indexOf(compositionData) && (resetMaskSet(), getMaskSet().p = seekNext(-1)); + for (var newData = ev.data, i = 0; i < newData.length; i++) { + var keypress = new $.Event("keypress"); + keypress.which = newData.charCodeAt(i), skipKeyPressEvent = !1, ignorable = !1, + keypressEvent.call(input, keypress, !0, !1, !1, getMaskSet().p); + } + inputBuffer !== getBuffer().join("") && setTimeout(function() { + var forwardPosition = getMaskSet().p; + writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition); + }, 0), compositionData = ev.data; + } + function compositionEndEvent(e) {} + function setValueEvent(e) { + var input = this, value = input.inputmask._valueGet(); + checkVal(input, !0, !1, ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(value, opts) || value : value).split("")), + undoValue = getBuffer().join(""), (opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("") && input.inputmask._valueSet(""); + } + function focusEvent(e) { + var input = this, nptValue = input.inputmask._valueGet(); + opts.showMaskOnFocus && (!opts.showMaskOnHover || opts.showMaskOnHover && "" === nptValue) ? input.inputmask._valueGet() !== getBuffer().join("") && writeBuffer(input, getBuffer(), seekNext(getLastValidPosition())) : mouseEnter === !1 && caret(input, seekNext(getLastValidPosition())), + opts.positionCaretOnTab === !0 && setTimeout(function() { + caret(input, seekNext(getLastValidPosition())); + }, 0), undoValue = getBuffer().join(""); + } + function mouseleaveEvent(e) { + var input = this; + if (mouseEnter = !1, opts.clearMaskOnLostFocus && document.activeElement !== input) { + var buffer = getBuffer().slice(), nptValue = input.inputmask._valueGet(); + nptValue !== input.getAttribute("placeholder") && "" !== nptValue && (-1 === getLastValidPosition() && nptValue === getBufferTemplate().join("") ? buffer = [] : clearOptionalTail(buffer), + writeBuffer(input, buffer)); + } + } + function clickEvent(e) { + function doRadixFocus(clickPos) { + if (opts.radixFocus && "" !== opts.radixPoint) { + var vps = getMaskSet().validPositions; + if (void 0 === vps[clickPos] || vps[clickPos].input === getPlaceholder(clickPos)) { + if (clickPos < seekNext(-1)) return !0; + var radixPos = $.inArray(opts.radixPoint, getBuffer()); + if (-1 !== radixPos) { + for (var vp in vps) if (vp > radixPos && vps[vp].input !== getPlaceholder(vp)) return !1; + return !0; + } + } + } + return !1; + } + var input = this; + if (document.activeElement === input) { + var selectedCaret = caret(input); + if (selectedCaret.begin === selectedCaret.end) if (doRadixFocus(selectedCaret.begin)) caret(input, opts.numericInput ? seekNext($.inArray(opts.radixPoint, getBuffer())) : $.inArray(opts.radixPoint, getBuffer())); else { + var clickPosition = selectedCaret.begin, lvclickPosition = getLastValidPosition(clickPosition), lastPosition = seekNext(lvclickPosition); + lastPosition > clickPosition ? caret(input, isMask(clickPosition) || isMask(clickPosition - 1) ? clickPosition : seekNext(clickPosition)) : ((getBuffer()[lastPosition] !== getPlaceholder(lastPosition) || !isMask(lastPosition, !0) && getTest(lastPosition).def === getPlaceholder(lastPosition)) && (lastPosition = seekNext(lastPosition)), + caret(input, lastPosition)); + } + } + } + function dblclickEvent(e) { + var input = this; + setTimeout(function() { + caret(input, 0, seekNext(getLastValidPosition())); + }, 0); + } + function cutEvent(e) { + var input = this, $input = $(input), pos = caret(input), ev = e.originalEvent || e, clipboardData = window.clipboardData || ev.clipboardData, clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end); + clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join("")), + document.execCommand && document.execCommand("copy"), handleRemove(input, Inputmask.keyCode.DELETE, pos), + writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join("")), + input.inputmask._valueGet() === getBufferTemplate().join("") && $input.trigger("cleared"), + opts.showTooltip && (input.title = opts.tooltip || getMaskSet().mask); + } + function blurEvent(e) { + var $input = $(this), input = this; + if (input.inputmask) { + var nptValue = input.inputmask._valueGet(), buffer = getBuffer().slice(); + undoValue !== buffer.join("") && setTimeout(function() { + $input.trigger("change"), undoValue = buffer.join(""); + }, 0), "" !== nptValue && (opts.clearMaskOnLostFocus && (-1 === getLastValidPosition() && nptValue === getBufferTemplate().join("") ? buffer = [] : clearOptionalTail(buffer)), + isComplete(buffer) === !1 && (setTimeout(function() { + $input.trigger("incomplete"); + }, 0), opts.clearIncomplete && (resetMaskSet(), buffer = opts.clearMaskOnLostFocus ? [] : getBufferTemplate().slice())), + writeBuffer(input, buffer, void 0, e)); + } + } + function mouseenterEvent(e) { + var input = this; + mouseEnter = !0, document.activeElement !== input && opts.showMaskOnHover && input.inputmask._valueGet() !== getBuffer().join("") && writeBuffer(input, getBuffer()); + } + function submitEvent(e) { + undoValue !== getBuffer().join("") && $el.trigger("change"), opts.clearMaskOnLostFocus && -1 === getLastValidPosition() && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("") && el.inputmask._valueSet(""), + opts.removeMaskOnSubmit && (el.inputmask._valueSet(el.inputmask.unmaskedvalue(), !0), + setTimeout(function() { + writeBuffer(el, getBuffer()); + }, 0)); + } + function resetEvent(e) { + setTimeout(function() { + $el.trigger("setvalue"); + }, 0); + } + function mask(elem) { + if (el = elem, $el = $(el), opts.showTooltip && (el.title = opts.tooltip || getMaskSet().mask), + ("rtl" === el.dir || opts.rightAlign) && (el.style.textAlign = "right"), ("rtl" === el.dir || opts.numericInput) && (el.dir = "ltr", + el.removeAttribute("dir"), el.inputmask.isRTL = !0, isRTL = !0), EventRuler.off(el), + patchValueProperty(el), isElementTypeSupported(el, opts) && (EventRuler.on(el, "submit", submitEvent), + EventRuler.on(el, "reset", resetEvent), EventRuler.on(el, "mouseenter", mouseenterEvent), + EventRuler.on(el, "blur", blurEvent), EventRuler.on(el, "focus", focusEvent), EventRuler.on(el, "mouseleave", mouseleaveEvent), + EventRuler.on(el, "click", clickEvent), EventRuler.on(el, "dblclick", dblclickEvent), + EventRuler.on(el, "paste", pasteEvent), EventRuler.on(el, "dragdrop", pasteEvent), + EventRuler.on(el, "drop", pasteEvent), EventRuler.on(el, "cut", cutEvent), EventRuler.on(el, "complete", opts.oncomplete), + EventRuler.on(el, "incomplete", opts.onincomplete), EventRuler.on(el, "cleared", opts.oncleared), + EventRuler.on(el, "keydown", keydownEvent), EventRuler.on(el, "keypress", keypressEvent), + EventRuler.on(el, "input", inputFallBackEvent), mobile || (EventRuler.on(el, "compositionstart", compositionStartEvent), + EventRuler.on(el, "compositionupdate", compositionUpdateEvent), EventRuler.on(el, "compositionend", compositionEndEvent))), + EventRuler.on(el, "setvalue", setValueEvent), "" !== el.inputmask._valueGet() || opts.clearMaskOnLostFocus === !1) { + var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(el.inputmask._valueGet(), opts) || el.inputmask._valueGet() : el.inputmask._valueGet(); + checkVal(el, !0, !1, initialValue.split("")); + var buffer = getBuffer().slice(); + undoValue = buffer.join(""), isComplete(buffer) === !1 && opts.clearIncomplete && resetMaskSet(), + opts.clearMaskOnLostFocus && (buffer.join("") === getBufferTemplate().join("") ? buffer = [] : clearOptionalTail(buffer)), + writeBuffer(el, buffer), document.activeElement === el && caret(el, seekNext(getLastValidPosition())); + } + } + var undoValue, compositionData, el, $el, maxLength, valueBuffer, isRTL = !1, skipKeyPressEvent = !1, skipInputEvent = !1, ignorable = !1, mouseEnter = !0, inComposition = !1, EventRuler = { + on: function(input, eventName, eventHandler) { + var ev = function(e) { + if (void 0 === this.inputmask && "FORM" !== this.nodeName) { + var imOpts = $.data(this, "_inputmask_opts"); + imOpts ? new Inputmask(imOpts).mask(this) : EventRuler.off(this); + } else { + if ("setvalue" === e.type || !(this.disabled || this.readOnly && !("keydown" === e.type && e.ctrlKey && 67 === e.keyCode || opts.tabThrough === !1 && e.keyCode === Inputmask.keyCode.TAB))) { + switch (e.type) { + case "input": + if (skipInputEvent === !0 || inComposition === !0) return skipInputEvent = inComposition, + e.preventDefault(); + break; + + case "keydown": + skipKeyPressEvent = !1, skipInputEvent = !1, inComposition = !1; + break; + + case "keypress": + if (skipKeyPressEvent === !0) return e.preventDefault(); + skipKeyPressEvent = !0; + break; + + case "compositionstart": + inComposition = !0; + break; + + case "compositionupdate": + skipInputEvent = !0; + break; + + case "compositionend": + inComposition = !1; + break; + + case "cut": + skipInputEvent = !0; + break; + + case "click": + if (iemobile) { + var that = this; + return setTimeout(function() { + eventHandler.apply(that, arguments); + }, 0), !1; + } + } + return eventHandler.apply(this, arguments); + } + e.preventDefault(); + } + }; + input.inputmask.events[eventName] = input.inputmask.events[eventName] || [], input.inputmask.events[eventName].push(ev), + -1 !== $.inArray(eventName, [ "submit", "reset" ]) ? null != input.form && $(input.form).on(eventName, ev) : $(input).on(eventName, ev); + }, + off: function(input, event) { + if (input.inputmask && input.inputmask.events) { + var events; + event ? (events = [], events[event] = input.inputmask.events[event]) : events = input.inputmask.events, + $.each(events, function(eventName, evArr) { + for (;evArr.length > 0; ) { + var ev = evArr.pop(); + -1 !== $.inArray(eventName, [ "submit", "reset" ]) ? null != input.form && $(input.form).off(eventName, ev) : $(input).off(eventName, ev); + } + delete input.inputmask.events[eventName]; + }); + } + } + }; + if (void 0 !== actionObj) switch (actionObj.action) { + case "isComplete": + return el = actionObj.el, isComplete(getBuffer()); + + case "unmaskedvalue": + return el = actionObj.el, void 0 !== el && void 0 !== el.inputmask ? (maskset = el.inputmask.maskset, + opts = el.inputmask.opts, isRTL = el.inputmask.isRTL) : (valueBuffer = actionObj.value, + opts.numericInput && (isRTL = !0), valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(valueBuffer, opts) || valueBuffer : valueBuffer).split(""), + checkVal(void 0, !1, !1, isRTL ? valueBuffer.reverse() : valueBuffer), $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite(void 0, getBuffer(), 0, opts)), + unmaskedvalue(el); + + case "mask": + el = actionObj.el, maskset = el.inputmask.maskset, opts = el.inputmask.opts, isRTL = el.inputmask.isRTL, + undoValue = getBuffer().join(""), mask(el); + break; + + case "format": + return opts.numericInput && (isRTL = !0), valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(actionObj.value, opts) || actionObj.value : actionObj.value).split(""), + checkVal(void 0, !1, !1, isRTL ? valueBuffer.reverse() : valueBuffer), $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite(void 0, getBuffer(), 0, opts), + actionObj.metadata ? { + value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""), + metadata: maskScope({ + action: "getmetadata" + }, maskset, opts) + } : isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""); + + case "isValid": + opts.numericInput && (isRTL = !0), actionObj.value ? (valueBuffer = actionObj.value.split(""), + checkVal(void 0, !1, !0, isRTL ? valueBuffer.reverse() : valueBuffer)) : actionObj.value = getBuffer().join(""); + for (var buffer = getBuffer(), rl = determineLastRequiredPosition(), lmib = buffer.length - 1; lmib > rl && !isMask(lmib); lmib--) ; + return buffer.splice(rl, lmib + 1 - rl), isComplete(buffer) && actionObj.value === getBuffer().join(""); + + case "getemptymask": + return getBufferTemplate(); + + case "remove": + el = actionObj.el, $el = $(el), maskset = el.inputmask.maskset, opts = el.inputmask.opts, + el.inputmask._valueSet(unmaskedvalue(el)), EventRuler.off(el); + var valueProperty; + Object.getOwnPropertyDescriptor && (valueProperty = Object.getOwnPropertyDescriptor(el, "value")), + valueProperty && valueProperty.get ? el.inputmask.__valueGet && Object.defineProperty(el, "value", { + get: el.inputmask.__valueGet, + set: el.inputmask.__valueSet + }) : document.__lookupGetter__ && el.__lookupGetter__("value") && el.inputmask.__valueGet && (el.__defineGetter__("value", el.inputmask.__valueGet), + el.__defineSetter__("value", el.inputmask.__valueSet)), el.inputmask = void 0; + break; + + case "getmetadata": + if ($.isArray(maskset.metadata)) { + for (var alternation, lvp = getLastValidPosition(), firstAlt = lvp; firstAlt >= 0; firstAlt--) if (getMaskSet().validPositions[firstAlt] && void 0 !== getMaskSet().validPositions[firstAlt].alternation) { + alternation = getMaskSet().validPositions[firstAlt].alternation; + break; + } + return void 0 !== alternation ? maskset.metadata[getMaskSet().validPositions[lvp].locator[alternation]] : maskset.metadata[0]; + } + return maskset.metadata; + } + } + Inputmask.prototype = { + defaults: { + placeholder: "_", + optionalmarker: { + start: "[", + end: "]" + }, + quantifiermarker: { + start: "{", + end: "}" + }, + groupmarker: { + start: "(", + end: ")" + }, + alternatormarker: "|", + escapeChar: "\\", + mask: null, + oncomplete: $.noop, + onincomplete: $.noop, + oncleared: $.noop, + repeat: 0, + greedy: !0, + autoUnmask: !1, + removeMaskOnSubmit: !1, + clearMaskOnLostFocus: !0, + insertMode: !0, + clearIncomplete: !1, + aliases: {}, + alias: null, + onKeyDown: $.noop, + onBeforeMask: null, + onBeforePaste: function(pastedValue, opts) { + return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(pastedValue, opts) : pastedValue; + }, + onBeforeWrite: null, + onUnMask: null, + showMaskOnFocus: !0, + showMaskOnHover: !0, + onKeyValidation: $.noop, + skipOptionalPartCharacter: " ", + showTooltip: !1, + tooltip: void 0, + numericInput: !1, + rightAlign: !1, + undoOnEscape: !0, + radixPoint: "", + groupSeparator: "", + radixFocus: !1, + nojumps: !1, + nojumpsThreshold: 0, + keepStatic: null, + positionCaretOnTab: !1, + tabThrough: !1, + supportsInputType: [ "text", "tel", "password" ], + definitions: { + "9": { + validator: "[0-9]", + cardinality: 1, + definitionSymbol: "*" + }, + a: { + validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", + cardinality: 1, + definitionSymbol: "*" + }, + "*": { + validator: "[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", + cardinality: 1 + } + }, + ignorables: [ 8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123 ], + isComplete: null, + canClearPosition: $.noop, + postValidation: null, + staticDefinitionSymbol: void 0, + jitMasking: !1 + }, + masksCache: {}, + mask: function(elems) { + var that = this; + return "string" == typeof elems && (elems = document.getElementById(elems) || document.querySelectorAll(elems)), + elems = elems.nodeName ? [ elems ] : elems, $.each(elems, function(ndx, el) { + var scopedOpts = $.extend(!0, {}, that.opts); + importAttributeOptions(el, scopedOpts, $.extend(!0, {}, that.userOptions)); + var maskset = generateMaskSet(scopedOpts, that.noMasksCache); + void 0 !== maskset && (void 0 !== el.inputmask && el.inputmask.remove(), el.inputmask = new Inputmask(), + el.inputmask.opts = scopedOpts, el.inputmask.noMasksCache = that.noMasksCache, el.inputmask.userOptions = $.extend(!0, {}, that.userOptions), + el.inputmask.el = el, el.inputmask.maskset = maskset, el.inputmask.isRTL = !1, $.data(el, "_inputmask_opts", scopedOpts), + maskScope({ + action: "mask", + el: el + })); + }), elems && elems[0] ? elems[0].inputmask || this : this; + }, + option: function(options) { + return "string" == typeof options ? this.opts[options] : "object" == typeof options ? ($.extend(this.opts, options), + $.extend(this.userOptions, options), this.el && (void 0 !== options.mask || void 0 !== options.alias ? this.mask(this.el) : ($.data(this.el, "_inputmask_opts", this.opts), + maskScope({ + action: "mask", + el: this.el + }))), this) : void 0; + }, + unmaskedvalue: function(value) { + return maskScope({ + action: "unmaskedvalue", + el: this.el, + value: value + }, this.el && this.el.inputmask ? this.el.inputmask.maskset : generateMaskSet(this.opts, this.noMasksCache), this.opts); + }, + remove: function() { + return this.el ? (maskScope({ + action: "remove", + el: this.el + }), this.el.inputmask = void 0, this.el) : void 0; + }, + getemptymask: function() { + return maskScope({ + action: "getemptymask" + }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); + }, + hasMaskedValue: function() { + return !this.opts.autoUnmask; + }, + isComplete: function() { + return maskScope({ + action: "isComplete", + el: this.el + }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); + }, + getmetadata: function() { + return maskScope({ + action: "getmetadata" + }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); + }, + isValid: function(value) { + return maskScope({ + action: "isValid", + value: value + }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); + }, + format: function(value, metadata) { + return maskScope({ + action: "format", + value: value, + metadata: metadata + }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); + } + }, Inputmask.extendDefaults = function(options) { + $.extend(!0, Inputmask.prototype.defaults, options); + }, Inputmask.extendDefinitions = function(definition) { + $.extend(!0, Inputmask.prototype.defaults.definitions, definition); + }, Inputmask.extendAliases = function(alias) { + $.extend(!0, Inputmask.prototype.defaults.aliases, alias); + }, Inputmask.format = function(value, options, metadata) { + return Inputmask(options).format(value, metadata); + }, Inputmask.unmask = function(value, options) { + return Inputmask(options).unmaskedvalue(value); + }, Inputmask.isValid = function(value, options) { + return Inputmask(options).isValid(value); + }, Inputmask.remove = function(elems) { + $.each(elems, function(ndx, el) { + el.inputmask && el.inputmask.remove(); + }); + }, Inputmask.escapeRegex = function(str) { + var specials = [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^" ]; + return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1"); + }, Inputmask.keyCode = { + ALT: 18, + BACKSPACE: 8, + CAPS_LOCK: 20, + COMMA: 188, + COMMAND: 91, + COMMAND_LEFT: 91, + COMMAND_RIGHT: 93, + CONTROL: 17, + DELETE: 46, + DOWN: 40, + END: 35, + ENTER: 13, + ESCAPE: 27, + HOME: 36, + INSERT: 45, + LEFT: 37, + MENU: 93, + NUMPAD_ADD: 107, + NUMPAD_DECIMAL: 110, + NUMPAD_DIVIDE: 111, + NUMPAD_ENTER: 108, + NUMPAD_MULTIPLY: 106, + NUMPAD_SUBTRACT: 109, + PAGE_DOWN: 34, + PAGE_UP: 33, + PERIOD: 190, + RIGHT: 39, + SHIFT: 16, + SPACE: 32, + TAB: 9, + UP: 38, + WINDOWS: 91 + }; + var ua = navigator.userAgent, mobile = /mobile/i.test(ua), iemobile = /iemobile/i.test(ua), iphone = /iphone/i.test(ua) && !iemobile; + /android.*safari.*/i.test(ua) && !iemobile; + return window.Inputmask = Inputmask, Inputmask; +}(jQuery), function($, Inputmask) { + return void 0 === $.fn.inputmask && ($.fn.inputmask = function(fn, options) { + var nptmask, input = this[0]; + if (options = options || {}, "string" == typeof fn) switch (fn) { + case "unmaskedvalue": + return input && input.inputmask ? input.inputmask.unmaskedvalue() : $(input).val(); + + case "remove": + return this.each(function() { + this.inputmask && this.inputmask.remove(); + }); + + case "getemptymask": + return input && input.inputmask ? input.inputmask.getemptymask() : ""; + + case "hasMaskedValue": + return input && input.inputmask ? input.inputmask.hasMaskedValue() : !1; + + case "isComplete": + return input && input.inputmask ? input.inputmask.isComplete() : !0; + + case "getmetadata": + return input && input.inputmask ? input.inputmask.getmetadata() : void 0; + + case "setvalue": + $(input).val(options), input && void 0 !== input.inputmask && $(input).triggerHandler("setvalue"); + break; + + case "option": + if ("string" != typeof options) return this.each(function() { + return void 0 !== this.inputmask ? this.inputmask.option(options) : void 0; + }); + if (input && void 0 !== input.inputmask) return input.inputmask.option(options); + break; + + default: + return options.alias = fn, nptmask = new Inputmask(options), this.each(function() { + nptmask.mask(this); + }); + } else { + if ("object" == typeof fn) return nptmask = new Inputmask(fn), void 0 === fn.mask && void 0 === fn.alias ? this.each(function() { + return void 0 !== this.inputmask ? this.inputmask.option(fn) : void nptmask.mask(this); + }) : this.each(function() { + nptmask.mask(this); + }); + if (void 0 === fn) return this.each(function() { + nptmask = new Inputmask(options), nptmask.mask(this); + }); + } + }), $.fn.inputmask; +}(jQuery, Inputmask), function($, Inputmask) { + return Inputmask.extendDefinitions({ + h: { + validator: "[01][0-9]|2[0-3]", + cardinality: 2, + prevalidator: [ { + validator: "[0-2]", + cardinality: 1 + } ] + }, + s: { + validator: "[0-5][0-9]", + cardinality: 2, + prevalidator: [ { + validator: "[0-5]", + cardinality: 1 + } ] + }, + d: { + validator: "0[1-9]|[12][0-9]|3[01]", + cardinality: 2, + prevalidator: [ { + validator: "[0-3]", + cardinality: 1 + } ] + }, + m: { + validator: "0[1-9]|1[012]", + cardinality: 2, + prevalidator: [ { + validator: "[01]", + cardinality: 1 + } ] + }, + y: { + validator: "(19|20)\\d{2}", + cardinality: 4, + prevalidator: [ { + validator: "[12]", + cardinality: 1 + }, { + validator: "(19|20)", + cardinality: 2 + }, { + validator: "(19|20)\\d", + cardinality: 3 + } ] + } + }), Inputmask.extendAliases({ + "dd/mm/yyyy": { + mask: "1/2/y", + placeholder: "dd/mm/yyyy", + regex: { + val1pre: new RegExp("[0-3]"), + val1: new RegExp("0[1-9]|[12][0-9]|3[01]"), + val2pre: function(separator) { + var escapedSeparator = Inputmask.escapeRegex.call(this, separator); + return new RegExp("((0[1-9]|[12][0-9]|3[01])" + escapedSeparator + "[01])"); + }, + val2: function(separator) { + var escapedSeparator = Inputmask.escapeRegex.call(this, separator); + return new RegExp("((0[1-9]|[12][0-9])" + escapedSeparator + "(0[1-9]|1[012]))|(30" + escapedSeparator + "(0[13-9]|1[012]))|(31" + escapedSeparator + "(0[13578]|1[02]))"); + } + }, + leapday: "29/02/", + separator: "/", + yearrange: { + minyear: 1900, + maxyear: 2099 + }, + isInYearRange: function(chrs, minyear, maxyear) { + if (isNaN(chrs)) return !1; + var enteredyear = parseInt(chrs.concat(minyear.toString().slice(chrs.length))), enteredyear2 = parseInt(chrs.concat(maxyear.toString().slice(chrs.length))); + return (isNaN(enteredyear) ? !1 : enteredyear >= minyear && maxyear >= enteredyear) || (isNaN(enteredyear2) ? !1 : enteredyear2 >= minyear && maxyear >= enteredyear2); + }, + determinebaseyear: function(minyear, maxyear, hint) { + var currentyear = new Date().getFullYear(); + if (minyear > currentyear) return minyear; + if (currentyear > maxyear) { + for (var maxYearPrefix = maxyear.toString().slice(0, 2), maxYearPostfix = maxyear.toString().slice(2, 4); maxYearPrefix + hint > maxyear; ) maxYearPrefix--; + var maxxYear = maxYearPrefix + maxYearPostfix; + return minyear > maxxYear ? minyear : maxxYear; + } + return currentyear; + }, + onKeyDown: function(e, buffer, caretPos, opts) { + var $input = $(this); + if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { + var today = new Date(); + $input.val(today.getDate().toString() + (today.getMonth() + 1).toString() + today.getFullYear().toString()), + $input.trigger("setvalue"); + } + }, + getFrontValue: function(mask, buffer, opts) { + for (var start = 0, length = 0, i = 0; i < mask.length && "2" !== mask.charAt(i); i++) { + var definition = opts.definitions[mask.charAt(i)]; + definition ? (start += length, length = definition.cardinality) : length++; + } + return buffer.join("").substr(start, length); + }, + definitions: { + "1": { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.regex.val1.test(chrs); + return strict || isValid || chrs.charAt(1) !== opts.separator && -1 === "-./".indexOf(chrs.charAt(1)) || !(isValid = opts.regex.val1.test("0" + chrs.charAt(0))) ? isValid : (maskset.buffer[pos - 1] = "0", + { + refreshFromBuffer: { + start: pos - 1, + end: pos + }, + pos: pos, + c: chrs.charAt(0) + }); + }, + cardinality: 2, + prevalidator: [ { + validator: function(chrs, maskset, pos, strict, opts) { + var pchrs = chrs; + isNaN(maskset.buffer[pos + 1]) || (pchrs += maskset.buffer[pos + 1]); + var isValid = 1 === pchrs.length ? opts.regex.val1pre.test(pchrs) : opts.regex.val1.test(pchrs); + if (!strict && !isValid) { + if (isValid = opts.regex.val1.test(chrs + "0")) return maskset.buffer[pos] = chrs, + maskset.buffer[++pos] = "0", { + pos: pos, + c: "0" + }; + if (isValid = opts.regex.val1.test("0" + chrs)) return maskset.buffer[pos] = "0", + pos++, { + pos: pos + }; + } + return isValid; + }, + cardinality: 1 + } ] + }, + "2": { + validator: function(chrs, maskset, pos, strict, opts) { + var frontValue = opts.getFrontValue(maskset.mask, maskset.buffer, opts); + -1 !== frontValue.indexOf(opts.placeholder[0]) && (frontValue = "01" + opts.separator); + var isValid = opts.regex.val2(opts.separator).test(frontValue + chrs); + if (!strict && !isValid && (chrs.charAt(1) === opts.separator || -1 !== "-./".indexOf(chrs.charAt(1))) && (isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs.charAt(0)))) return maskset.buffer[pos - 1] = "0", + { + refreshFromBuffer: { + start: pos - 1, + end: pos + }, + pos: pos, + c: chrs.charAt(0) + }; + if (opts.mask.indexOf("2") === opts.mask.length - 1 && isValid) { + var dayMonthValue = maskset.buffer.join("").substr(4, 4) + chrs; + if (dayMonthValue !== opts.leapday) return !0; + var year = parseInt(maskset.buffer.join("").substr(0, 4), 10); + return year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; + } + return isValid; + }, + cardinality: 2, + prevalidator: [ { + validator: function(chrs, maskset, pos, strict, opts) { + isNaN(maskset.buffer[pos + 1]) || (chrs += maskset.buffer[pos + 1]); + var frontValue = opts.getFrontValue(maskset.mask, maskset.buffer, opts); + -1 !== frontValue.indexOf(opts.placeholder[0]) && (frontValue = "01" + opts.separator); + var isValid = 1 === chrs.length ? opts.regex.val2pre(opts.separator).test(frontValue + chrs) : opts.regex.val2(opts.separator).test(frontValue + chrs); + return strict || isValid || !(isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", + pos++, { + pos: pos + }); + }, + cardinality: 1 + } ] + }, + y: { + validator: function(chrs, maskset, pos, strict, opts) { + if (opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) { + var dayMonthValue = maskset.buffer.join("").substr(0, 6); + if (dayMonthValue !== opts.leapday) return !0; + var year = parseInt(chrs, 10); + return year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; + } + return !1; + }, + cardinality: 4, + prevalidator: [ { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); + if (!strict && !isValid) { + var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 1); + if (isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(0), + { + pos: pos + }; + if (yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 2), + isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(0), + maskset.buffer[pos++] = yearPrefix.charAt(1), { + pos: pos + }; + } + return isValid; + }, + cardinality: 1 + }, { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); + if (!strict && !isValid) { + var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2); + if (isValid = opts.isInYearRange(chrs[0] + yearPrefix[1] + chrs[1], opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(1), + { + pos: pos + }; + if (yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2), + opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) { + var dayMonthValue = maskset.buffer.join("").substr(0, 6); + if (dayMonthValue !== opts.leapday) isValid = !0; else { + var year = parseInt(chrs, 10); + isValid = year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; + } + } else isValid = !1; + if (isValid) return maskset.buffer[pos - 1] = yearPrefix.charAt(0), maskset.buffer[pos++] = yearPrefix.charAt(1), + maskset.buffer[pos++] = chrs.charAt(0), { + refreshFromBuffer: { + start: pos - 3, + end: pos + }, + pos: pos + }; + } + return isValid; + }, + cardinality: 2 + }, { + validator: function(chrs, maskset, pos, strict, opts) { + return opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); + }, + cardinality: 3 + } ] + } + }, + insertMode: !1, + autoUnmask: !1 + }, + "mm/dd/yyyy": { + placeholder: "mm/dd/yyyy", + alias: "dd/mm/yyyy", + regex: { + val2pre: function(separator) { + var escapedSeparator = Inputmask.escapeRegex.call(this, separator); + return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); + }, + val2: function(separator) { + var escapedSeparator = Inputmask.escapeRegex.call(this, separator); + return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); + }, + val1pre: new RegExp("[01]"), + val1: new RegExp("0[1-9]|1[012]") + }, + leapday: "02/29/", + onKeyDown: function(e, buffer, caretPos, opts) { + var $input = $(this); + if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { + var today = new Date(); + $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString()), + $input.trigger("setvalue"); + } + } + }, + "yyyy/mm/dd": { + mask: "y/1/2", + placeholder: "yyyy/mm/dd", + alias: "mm/dd/yyyy", + leapday: "/02/29", + onKeyDown: function(e, buffer, caretPos, opts) { + var $input = $(this); + if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { + var today = new Date(); + $input.val(today.getFullYear().toString() + (today.getMonth() + 1).toString() + today.getDate().toString()), + $input.trigger("setvalue"); + } + } + }, + "dd.mm.yyyy": { + mask: "1.2.y", + placeholder: "dd.mm.yyyy", + leapday: "29.02.", + separator: ".", + alias: "dd/mm/yyyy" + }, + "dd-mm-yyyy": { + mask: "1-2-y", + placeholder: "dd-mm-yyyy", + leapday: "29-02-", + separator: "-", + alias: "dd/mm/yyyy" + }, + "mm.dd.yyyy": { + mask: "1.2.y", + placeholder: "mm.dd.yyyy", + leapday: "02.29.", + separator: ".", + alias: "mm/dd/yyyy" + }, + "mm-dd-yyyy": { + mask: "1-2-y", + placeholder: "mm-dd-yyyy", + leapday: "02-29-", + separator: "-", + alias: "mm/dd/yyyy" + }, + "yyyy.mm.dd": { + mask: "y.1.2", + placeholder: "yyyy.mm.dd", + leapday: ".02.29", + separator: ".", + alias: "yyyy/mm/dd" + }, + "yyyy-mm-dd": { + mask: "y-1-2", + placeholder: "yyyy-mm-dd", + leapday: "-02-29", + separator: "-", + alias: "yyyy/mm/dd" + }, + datetime: { + mask: "1/2/y h:s", + placeholder: "dd/mm/yyyy hh:mm", + alias: "dd/mm/yyyy", + regex: { + hrspre: new RegExp("[012]"), + hrs24: new RegExp("2[0-4]|1[3-9]"), + hrs: new RegExp("[01][0-9]|2[0-4]"), + ampm: new RegExp("^[a|p|A|P][m|M]"), + mspre: new RegExp("[0-5]"), + ms: new RegExp("[0-5][0-9]") + }, + timeseparator: ":", + hourFormat: "24", + definitions: { + h: { + validator: function(chrs, maskset, pos, strict, opts) { + if ("24" === opts.hourFormat && 24 === parseInt(chrs, 10)) return maskset.buffer[pos - 1] = "0", + maskset.buffer[pos] = "0", { + refreshFromBuffer: { + start: pos - 1, + end: pos + }, + c: "0" + }; + var isValid = opts.regex.hrs.test(chrs); + if (!strict && !isValid && (chrs.charAt(1) === opts.timeseparator || -1 !== "-.:".indexOf(chrs.charAt(1))) && (isValid = opts.regex.hrs.test("0" + chrs.charAt(0)))) return maskset.buffer[pos - 1] = "0", + maskset.buffer[pos] = chrs.charAt(0), pos++, { + refreshFromBuffer: { + start: pos - 2, + end: pos + }, + pos: pos, + c: opts.timeseparator + }; + if (isValid && "24" !== opts.hourFormat && opts.regex.hrs24.test(chrs)) { + var tmp = parseInt(chrs, 10); + return 24 === tmp ? (maskset.buffer[pos + 5] = "a", maskset.buffer[pos + 6] = "m") : (maskset.buffer[pos + 5] = "p", + maskset.buffer[pos + 6] = "m"), tmp -= 12, 10 > tmp ? (maskset.buffer[pos] = tmp.toString(), + maskset.buffer[pos - 1] = "0") : (maskset.buffer[pos] = tmp.toString().charAt(1), + maskset.buffer[pos - 1] = tmp.toString().charAt(0)), { + refreshFromBuffer: { + start: pos - 1, + end: pos + 6 + }, + c: maskset.buffer[pos] + }; + } + return isValid; + }, + cardinality: 2, + prevalidator: [ { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.regex.hrspre.test(chrs); + return strict || isValid || !(isValid = opts.regex.hrs.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", + pos++, { + pos: pos + }); + }, + cardinality: 1 + } ] + }, + s: { + validator: "[0-5][0-9]", + cardinality: 2, + prevalidator: [ { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.regex.mspre.test(chrs); + return strict || isValid || !(isValid = opts.regex.ms.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", + pos++, { + pos: pos + }); + }, + cardinality: 1 + } ] + }, + t: { + validator: function(chrs, maskset, pos, strict, opts) { + return opts.regex.ampm.test(chrs + "m"); + }, + casing: "lower", + cardinality: 1 + } + }, + insertMode: !1, + autoUnmask: !1 + }, + datetime12: { + mask: "1/2/y h:s t\\m", + placeholder: "dd/mm/yyyy hh:mm xm", + alias: "datetime", + hourFormat: "12" + }, + "mm/dd/yyyy hh:mm xm": { + mask: "1/2/y h:s t\\m", + placeholder: "mm/dd/yyyy hh:mm xm", + alias: "datetime12", + regex: { + val2pre: function(separator) { + var escapedSeparator = Inputmask.escapeRegex.call(this, separator); + return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); + }, + val2: function(separator) { + var escapedSeparator = Inputmask.escapeRegex.call(this, separator); + return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); + }, + val1pre: new RegExp("[01]"), + val1: new RegExp("0[1-9]|1[012]") + }, + leapday: "02/29/", + onKeyDown: function(e, buffer, caretPos, opts) { + var $input = $(this); + if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { + var today = new Date(); + $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString()), + $input.trigger("setvalue"); + } + } + }, + "hh:mm t": { + mask: "h:s t\\m", + placeholder: "hh:mm xm", + alias: "datetime", + hourFormat: "12" + }, + "h:s t": { + mask: "h:s t\\m", + placeholder: "hh:mm xm", + alias: "datetime", + hourFormat: "12" + }, + "hh:mm:ss": { + mask: "h:s:s", + placeholder: "hh:mm:ss", + alias: "datetime", + autoUnmask: !1 + }, + "hh:mm": { + mask: "h:s", + placeholder: "hh:mm", + alias: "datetime", + autoUnmask: !1 + }, + date: { + alias: "dd/mm/yyyy" + }, + "mm/yyyy": { + mask: "1/y", + placeholder: "mm/yyyy", + leapday: "donotuse", + separator: "/", + alias: "mm/dd/yyyy" + }, + shamsi: { + regex: { + val2pre: function(separator) { + var escapedSeparator = Inputmask.escapeRegex.call(this, separator); + return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "[0-3])"); + }, + val2: function(separator) { + var escapedSeparator = Inputmask.escapeRegex.call(this, separator); + return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[1-9]|1[012])" + escapedSeparator + "30)|((0[1-6])" + escapedSeparator + "31)"); + }, + val1pre: new RegExp("[01]"), + val1: new RegExp("0[1-9]|1[012]") + }, + yearrange: { + minyear: 1300, + maxyear: 1499 + }, + mask: "y/1/2", + leapday: "/12/30", + placeholder: "yyyy/mm/dd", + alias: "mm/dd/yyyy", + clearIncomplete: !0 + } + }), Inputmask; +}(jQuery, Inputmask), function($, Inputmask) { + return Inputmask.extendDefinitions({ + A: { + validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", + cardinality: 1, + casing: "upper" + }, + "&": { + validator: "[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", + cardinality: 1, + casing: "upper" + }, + "#": { + validator: "[0-9A-Fa-f]", + cardinality: 1, + casing: "upper" + } + }), Inputmask.extendAliases({ + url: { + definitions: { + i: { + validator: ".", + cardinality: 1 + } + }, + mask: "(\\http://)|(\\http\\s://)|(ftp://)|(ftp\\s://)i{+}", + insertMode: !1, + autoUnmask: !1 + }, + ip: { + mask: "i[i[i]].i[i[i]].i[i[i]].i[i[i]]", + definitions: { + i: { + validator: function(chrs, maskset, pos, strict, opts) { + return pos - 1 > -1 && "." !== maskset.buffer[pos - 1] ? (chrs = maskset.buffer[pos - 1] + chrs, + chrs = pos - 2 > -1 && "." !== maskset.buffer[pos - 2] ? maskset.buffer[pos - 2] + chrs : "0" + chrs) : chrs = "00" + chrs, + new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(chrs); + }, + cardinality: 1 + } + }, + onUnMask: function(maskedValue, unmaskedValue, opts) { + return maskedValue; + } + }, + email: { + mask: "*{1,64}[.*{1,64}][.*{1,64}][.*{1,64}]@*{1,64}[.*{2,64}][.*{2,6}][.*{1,2}]", + greedy: !1, + onBeforePaste: function(pastedValue, opts) { + return pastedValue = pastedValue.toLowerCase(), pastedValue.replace("mailto:", ""); + }, + definitions: { + "*": { + validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~-]", + cardinality: 1, + casing: "lower" + } + }, + onUnMask: function(maskedValue, unmaskedValue, opts) { + return maskedValue; + } + }, + mac: { + mask: "##:##:##:##:##:##" + } + }), Inputmask; +}(jQuery, Inputmask), function($, Inputmask) { + return Inputmask.extendAliases({ + numeric: { + mask: function(opts) { + function autoEscape(txt) { + for (var escapedTxt = "", i = 0; i < txt.length; i++) escapedTxt += opts.definitions[txt.charAt(i)] ? "\\" + txt.charAt(i) : txt.charAt(i); + return escapedTxt; + } + if (0 !== opts.repeat && isNaN(opts.integerDigits) && (opts.integerDigits = opts.repeat), + opts.repeat = 0, opts.groupSeparator === opts.radixPoint && ("." === opts.radixPoint ? opts.groupSeparator = "," : "," === opts.radixPoint ? opts.groupSeparator = "." : opts.groupSeparator = ""), + " " === opts.groupSeparator && (opts.skipOptionalPartCharacter = void 0), opts.autoGroup = opts.autoGroup && "" !== opts.groupSeparator, + opts.autoGroup && ("string" == typeof opts.groupSize && isFinite(opts.groupSize) && (opts.groupSize = parseInt(opts.groupSize)), + isFinite(opts.integerDigits))) { + var seps = Math.floor(opts.integerDigits / opts.groupSize), mod = opts.integerDigits % opts.groupSize; + opts.integerDigits = parseInt(opts.integerDigits) + (0 === mod ? seps - 1 : seps), + opts.integerDigits < 1 && (opts.integerDigits = "*"); + } + opts.placeholder.length > 1 && (opts.placeholder = opts.placeholder.charAt(0)), + opts.radixFocus = opts.radixFocus && "" !== opts.placeholder && opts.integerOptional === !0, + opts.definitions[";"] = opts.definitions["~"], opts.definitions[";"].definitionSymbol = "~", + 1 == opts.numericInput && (opts.radixFocus = !1, opts.digitsOptional = !1, isNaN(opts.digits) && (opts.digits = 2), + opts.decimalProtect = !1); + var mask = autoEscape(opts.prefix); + return mask += "[+]", mask += opts.integerOptional === !0 ? "~{1," + opts.integerDigits + "}" : "~{" + opts.integerDigits + "}", + void 0 !== opts.digits && (isNaN(opts.digits) || parseInt(opts.digits) > 0) && (mask += opts.digitsOptional ? "[" + (opts.decimalProtect ? ":" : opts.radixPoint) + ";{1," + opts.digits + "}]" : (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}"), + "" !== opts.negationSymbol.back && (mask += "[-]"), mask += autoEscape(opts.suffix), + opts.greedy = !1, mask; + }, + placeholder: "", + greedy: !1, + digits: "*", + digitsOptional: !0, + radixPoint: ".", + radixFocus: !0, + groupSize: 3, + groupSeparator: "", + autoGroup: !1, + allowPlus: !0, + allowMinus: !0, + negationSymbol: { + front: "-", + back: "" + }, + integerDigits: "+", + integerOptional: !0, + prefix: "", + suffix: "", + rightAlign: !0, + decimalProtect: !0, + min: null, + max: null, + step: 1, + insertMode: !0, + autoUnmask: !1, + unmaskAsNumber: !1, + postFormat: function(buffer, pos, reformatOnly, opts) { + opts.numericInput === !0 && (buffer = buffer.reverse(), isFinite(pos) && (pos = buffer.join("").length - pos - 1)); + var i, l, suffixStripped = !1; + buffer.length >= opts.suffix.length && buffer.join("").indexOf(opts.suffix) === buffer.length - opts.suffix.length && (buffer.length = buffer.length - opts.suffix.length, + suffixStripped = !0), pos = pos >= buffer.length ? buffer.length - 1 : pos < opts.prefix.length ? opts.prefix.length : pos; + var needsRefresh = !1, charAtPos = buffer[pos]; + if ("" === opts.groupSeparator || opts.numericInput !== !0 && -1 !== $.inArray(opts.radixPoint, buffer) && pos > $.inArray(opts.radixPoint, buffer) || new RegExp("[" + Inputmask.escapeRegex(opts.negationSymbol.front) + "+]").test(charAtPos)) { + if (suffixStripped) for (i = 0, l = opts.suffix.length; l > i; i++) buffer.push(opts.suffix.charAt(i)); + return { + pos: pos + }; + } + var cbuf = buffer.slice(); + charAtPos === opts.groupSeparator && (cbuf.splice(pos--, 1), charAtPos = cbuf[pos]), + reformatOnly ? charAtPos !== opts.radixPoint && (cbuf[pos] = "?") : cbuf.splice(pos, 0, "?"); + var bufVal = cbuf.join(""), bufValOrigin = bufVal; + if (bufVal.length > 0 && opts.autoGroup || reformatOnly && -1 !== bufVal.indexOf(opts.groupSeparator)) { + var escapedGroupSeparator = Inputmask.escapeRegex(opts.groupSeparator); + needsRefresh = 0 === bufVal.indexOf(opts.groupSeparator), bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), ""); + var radixSplit = bufVal.split(opts.radixPoint); + if (bufVal = "" === opts.radixPoint ? bufVal : radixSplit[0], bufVal !== opts.prefix + "?0" && bufVal.length >= opts.groupSize + opts.prefix.length) for (var reg = new RegExp("([-+]?[\\d?]+)([\\d?]{" + opts.groupSize + "})"); reg.test(bufVal); ) bufVal = bufVal.replace(reg, "$1" + opts.groupSeparator + "$2"), + bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator); + "" !== opts.radixPoint && radixSplit.length > 1 && (bufVal += opts.radixPoint + radixSplit[1]); + } + for (needsRefresh = bufValOrigin !== bufVal, buffer.length = bufVal.length, i = 0, + l = bufVal.length; l > i; i++) buffer[i] = bufVal.charAt(i); + var newPos = $.inArray("?", buffer); + if (-1 === newPos && charAtPos === opts.radixPoint && (newPos = $.inArray(opts.radixPoint, buffer)), + reformatOnly ? buffer[newPos] = charAtPos : buffer.splice(newPos, 1), !needsRefresh && suffixStripped) for (i = 0, + l = opts.suffix.length; l > i; i++) buffer.push(opts.suffix.charAt(i)); + return newPos = opts.numericInput && isFinite(pos) ? buffer.join("").length - newPos - 1 : newPos, + opts.numericInput && (buffer = buffer.reverse(), $.inArray(opts.radixPoint, buffer) < newPos && buffer.join("").length - opts.suffix.length !== newPos && (newPos -= 1)), + { + pos: newPos, + refreshFromBuffer: needsRefresh, + buffer: buffer + }; + }, + onBeforeWrite: function(e, buffer, caretPos, opts) { + if (e && ("blur" === e.type || "checkval" === e.type)) { + var maskedValue = buffer.join(""), processValue = maskedValue.replace(opts.prefix, ""); + if (processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""), + "," === opts.radixPoint && (processValue = processValue.replace(Inputmask.escapeRegex(opts.radixPoint), ".")), + isFinite(processValue) && isFinite(opts.min) && parseFloat(processValue) < parseFloat(opts.min)) return $.extend(!0, { + refreshFromBuffer: !0, + buffer: (opts.prefix + opts.min).split("") + }, opts.postFormat((opts.prefix + opts.min).split(""), 0, !0, opts)); + if (opts.numericInput !== !0) { + var tmpBufSplit = "" !== opts.radixPoint ? buffer.join("").split(opts.radixPoint) : [ buffer.join("") ], matchRslt = tmpBufSplit[0].match(opts.regex.integerPart(opts)), matchRsltDigits = 2 === tmpBufSplit.length ? tmpBufSplit[1].match(opts.regex.integerNPart(opts)) : void 0; + if (matchRslt) { + matchRslt[0] !== opts.negationSymbol.front + "0" && matchRslt[0] !== opts.negationSymbol.front && "+" !== matchRslt[0] || void 0 !== matchRsltDigits && !matchRsltDigits[0].match(/^0+$/) || buffer.splice(matchRslt.index, 1); + var radixPosition = $.inArray(opts.radixPoint, buffer); + if (-1 !== radixPosition) { + if (isFinite(opts.digits) && !opts.digitsOptional) { + for (var i = 1; i <= opts.digits; i++) (void 0 === buffer[radixPosition + i] || buffer[radixPosition + i] === opts.placeholder.charAt(0)) && (buffer[radixPosition + i] = "0"); + return { + refreshFromBuffer: maskedValue !== buffer.join(""), + buffer: buffer + }; + } + if (radixPosition === buffer.length - opts.suffix.length - 1) return buffer.splice(radixPosition, 1), + { + refreshFromBuffer: !0, + buffer: buffer + }; + } + } + } + } + if (opts.autoGroup) { + var rslt = opts.postFormat(buffer, opts.numericInput ? caretPos : caretPos - 1, !0, opts); + return rslt.caret = caretPos <= opts.prefix.length ? rslt.pos : rslt.pos + 1, rslt; + } + }, + regex: { + integerPart: function(opts) { + return new RegExp("[" + Inputmask.escapeRegex(opts.negationSymbol.front) + "+]?\\d+"); + }, + integerNPart: function(opts) { + return new RegExp("[\\d" + Inputmask.escapeRegex(opts.groupSeparator) + "]+"); + } + }, + signHandler: function(chrs, maskset, pos, strict, opts) { + if (!strict && opts.allowMinus && "-" === chrs || opts.allowPlus && "+" === chrs) { + var matchRslt = maskset.buffer.join("").match(opts.regex.integerPart(opts)); + if (matchRslt && matchRslt[0].length > 0) return maskset.buffer[matchRslt.index] === ("-" === chrs ? "+" : opts.negationSymbol.front) ? "-" === chrs ? "" !== opts.negationSymbol.back ? { + pos: matchRslt.index, + c: opts.negationSymbol.front, + remove: matchRslt.index, + caret: pos, + insert: { + pos: maskset.buffer.length - opts.suffix.length - 1, + c: opts.negationSymbol.back + } + } : { + pos: matchRslt.index, + c: opts.negationSymbol.front, + remove: matchRslt.index, + caret: pos + } : "" !== opts.negationSymbol.back ? { + pos: matchRslt.index, + c: "+", + remove: [ matchRslt.index, maskset.buffer.length - opts.suffix.length - 1 ], + caret: pos + } : { + pos: matchRslt.index, + c: "+", + remove: matchRslt.index, + caret: pos + } : maskset.buffer[matchRslt.index] === ("-" === chrs ? opts.negationSymbol.front : "+") ? "-" === chrs && "" !== opts.negationSymbol.back ? { + remove: [ matchRslt.index, maskset.buffer.length - opts.suffix.length - 1 ], + caret: pos - 1 + } : { + remove: matchRslt.index, + caret: pos - 1 + } : "-" === chrs ? "" !== opts.negationSymbol.back ? { + pos: matchRslt.index, + c: opts.negationSymbol.front, + caret: pos + 1, + insert: { + pos: maskset.buffer.length - opts.suffix.length, + c: opts.negationSymbol.back + } + } : { + pos: matchRslt.index, + c: opts.negationSymbol.front, + caret: pos + 1 + } : { + pos: matchRslt.index, + c: chrs, + caret: pos + 1 + }; + } + return !1; + }, + radixHandler: function(chrs, maskset, pos, strict, opts) { + if (!strict && (-1 !== $.inArray(chrs, [ ",", "." ]) && (chrs = opts.radixPoint), + chrs === opts.radixPoint && void 0 !== opts.digits && (isNaN(opts.digits) || parseInt(opts.digits) > 0))) { + var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join("").match(opts.regex.integerPart(opts)); + if (-1 !== radixPos && maskset.validPositions[radixPos]) return maskset.validPositions[radixPos - 1] ? { + caret: radixPos + 1 + } : { + pos: integerValue.index, + c: integerValue[0], + caret: radixPos + 1 + }; + if (!integerValue || "0" === integerValue[0] && integerValue.index + 1 !== pos) return maskset.buffer[integerValue ? integerValue.index : pos] = "0", + { + pos: (integerValue ? integerValue.index : pos) + 1, + c: opts.radixPoint + }; + } + return !1; + }, + leadingZeroHandler: function(chrs, maskset, pos, strict, opts) { + if (opts.numericInput === !0) { + if ("0" === maskset.buffer[maskset.buffer.length - opts.prefix.length - 1]) return { + pos: pos, + remove: maskset.buffer.length - opts.prefix.length - 1 + }; + } else { + var matchRslt = maskset.buffer.join("").match(opts.regex.integerNPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer); + if (matchRslt && !strict && (-1 === radixPosition || radixPosition >= pos)) if (0 === matchRslt[0].indexOf("0")) { + pos < opts.prefix.length && (pos = matchRslt.index); + var _radixPosition = $.inArray(opts.radixPoint, maskset._buffer), digitsMatch = maskset._buffer && maskset.buffer.slice(radixPosition).join("") === maskset._buffer.slice(_radixPosition).join("") || 0 === parseInt(maskset.buffer.slice(radixPosition + 1).join("")), integerMatch = maskset._buffer && maskset.buffer.slice(matchRslt.index, radixPosition).join("") === maskset._buffer.slice(opts.prefix.length, _radixPosition).join("") || "0" === maskset.buffer.slice(matchRslt.index, radixPosition).join(""); + if (-1 === radixPosition || digitsMatch && integerMatch) return maskset.buffer.splice(matchRslt.index, 1), + pos = pos > matchRslt.index ? pos - 1 : matchRslt.index, { + pos: pos, + remove: matchRslt.index + }; + if (matchRslt.index + 1 === pos || "0" === chrs) return maskset.buffer.splice(matchRslt.index, 1), + pos = matchRslt.index, { + pos: pos, + remove: matchRslt.index + }; + } else if ("0" === chrs && pos <= matchRslt.index && matchRslt[0] !== opts.groupSeparator) return !1; + } + return !0; + }, + postValidation: function(buffer, currentResult, opts) { + var isValid = !0, maskedValue = opts.numericInput ? buffer.slice().reverse().join("") : buffer.join(""), processValue = maskedValue.replace(opts.prefix, ""); + return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""), + "," === opts.radixPoint && (processValue = processValue.replace(Inputmask.escapeRegex(opts.radixPoint), ".")), + processValue = processValue.replace(new RegExp("^" + Inputmask.escapeRegex(opts.negationSymbol.front)), "-"), + processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.negationSymbol.back) + "$"), ""), + processValue = processValue === opts.negationSymbol.front ? processValue + "0" : processValue, + isFinite(processValue) && (null !== opts.max && isFinite(opts.max) && (processValue = parseFloat(processValue) > parseFloat(opts.max) ? opts.max : processValue, + isValid = opts.postFormat((opts.prefix + processValue).split(""), 0, !0, opts)), + null !== opts.min && isFinite(opts.min) && (processValue = parseFloat(processValue) < parseFloat(opts.min) ? opts.min : processValue, + isValid = opts.postFormat((opts.prefix + processValue).split(""), 0, !0, opts))), + isValid; + }, + definitions: { + "~": { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.signHandler(chrs, maskset, pos, strict, opts); + if (!isValid && (isValid = opts.radixHandler(chrs, maskset, pos, strict, opts), + !isValid && (isValid = strict ? new RegExp("[0-9" + Inputmask.escapeRegex(opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs), + isValid === !0 && (isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts), + isValid === !0)))) { + var radixPosition = $.inArray(opts.radixPoint, maskset.buffer); + isValid = -1 !== radixPosition && opts.digitsOptional === !1 && opts.numericInput !== !0 && pos > radixPosition && !strict ? { + pos: pos, + remove: pos + } : { + pos: pos + }; + } + return isValid; + }, + cardinality: 1, + prevalidator: null + }, + "+": { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.signHandler(chrs, maskset, pos, strict, opts); + return !isValid && (strict && opts.allowMinus && chrs === opts.negationSymbol.front || opts.allowMinus && "-" === chrs || opts.allowPlus && "+" === chrs) && (isValid = "-" === chrs ? "" !== opts.negationSymbol.back ? { + pos: pos, + c: "-" === chrs ? opts.negationSymbol.front : "+", + caret: pos + 1, + insert: { + pos: maskset.buffer.length, + c: opts.negationSymbol.back + } + } : { + pos: pos, + c: "-" === chrs ? opts.negationSymbol.front : "+", + caret: pos + 1 + } : !0), isValid; + }, + cardinality: 1, + prevalidator: null, + placeholder: "" + }, + "-": { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.signHandler(chrs, maskset, pos, strict, opts); + return !isValid && strict && opts.allowMinus && chrs === opts.negationSymbol.back && (isValid = !0), + isValid; + }, + cardinality: 1, + prevalidator: null, + placeholder: "" + }, + ":": { + validator: function(chrs, maskset, pos, strict, opts) { + var isValid = opts.signHandler(chrs, maskset, pos, strict, opts); + if (!isValid) { + var radix = "[" + Inputmask.escapeRegex(opts.radixPoint) + ",\\.]"; + isValid = new RegExp(radix).test(chrs), isValid && maskset.validPositions[pos] && maskset.validPositions[pos].match.placeholder === opts.radixPoint && (isValid = { + caret: pos + 1 + }); + } + return isValid ? { + c: opts.radixPoint + } : isValid; + }, + cardinality: 1, + prevalidator: null, + placeholder: function(opts) { + return opts.radixPoint; + } + } + }, + onUnMask: function(maskedValue, unmaskedValue, opts) { + var processValue = maskedValue.replace(opts.prefix, ""); + return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""), + opts.unmaskAsNumber ? ("" !== opts.radixPoint && -1 !== processValue.indexOf(opts.radixPoint) && (processValue = processValue.replace(Inputmask.escapeRegex.call(this, opts.radixPoint), ".")), + Number(processValue)) : processValue; + }, + isComplete: function(buffer, opts) { + var maskedValue = buffer.join(""), bufClone = buffer.slice(); + if (opts.postFormat(bufClone, 0, !0, opts), bufClone.join("") !== maskedValue) return !1; + var processValue = maskedValue.replace(opts.prefix, ""); + return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""), + "," === opts.radixPoint && (processValue = processValue.replace(Inputmask.escapeRegex(opts.radixPoint), ".")), + isFinite(processValue); + }, + onBeforeMask: function(initialValue, opts) { + if ("" !== opts.radixPoint && isFinite(initialValue)) initialValue = initialValue.toString().replace(".", opts.radixPoint); else { + var kommaMatches = initialValue.match(/,/g), dotMatches = initialValue.match(/\./g); + dotMatches && kommaMatches ? dotMatches.length > kommaMatches.length ? (initialValue = initialValue.replace(/\./g, ""), + initialValue = initialValue.replace(",", opts.radixPoint)) : kommaMatches.length > dotMatches.length ? (initialValue = initialValue.replace(/,/g, ""), + initialValue = initialValue.replace(".", opts.radixPoint)) : initialValue = initialValue.indexOf(".") < initialValue.indexOf(",") ? initialValue.replace(/\./g, "") : initialValue = initialValue.replace(/,/g, "") : initialValue = initialValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""); + } + if (0 === opts.digits && (-1 !== initialValue.indexOf(".") ? initialValue = initialValue.substring(0, initialValue.indexOf(".")) : -1 !== initialValue.indexOf(",") && (initialValue = initialValue.substring(0, initialValue.indexOf(",")))), + "" !== opts.radixPoint && isFinite(opts.digits) && -1 !== initialValue.indexOf(opts.radixPoint)) { + var valueParts = initialValue.split(opts.radixPoint), decPart = valueParts[1].match(new RegExp("\\d*"))[0]; + if (parseInt(opts.digits) < decPart.toString().length) { + var digitsFactor = Math.pow(10, parseInt(opts.digits)); + initialValue = initialValue.replace(Inputmask.escapeRegex(opts.radixPoint), "."), + initialValue = Math.round(parseFloat(initialValue) * digitsFactor) / digitsFactor, + initialValue = initialValue.toString().replace(".", opts.radixPoint); + } + } + return initialValue.toString(); + }, + canClearPosition: function(maskset, position, lvp, strict, opts) { + var positionInput = maskset.validPositions[position].input, canClear = positionInput !== opts.radixPoint || null !== maskset.validPositions[position].match.fn && opts.decimalProtect === !1 || isFinite(positionInput) || position === lvp || positionInput === opts.groupSeparator || positionInput === opts.negationSymbol.front || positionInput === opts.negationSymbol.back; + if (canClear && isFinite(positionInput)) { + var matchRslt, radixPos = $.inArray(opts.radixPoint, maskset.buffer), radixInjection = !1; + if (void 0 === maskset.validPositions[radixPos] && (maskset.validPositions[radixPos] = { + input: opts.radixPoint + }, radixInjection = !0), !strict && maskset.buffer) { + matchRslt = maskset.buffer.join("").substr(0, position).match(opts.regex.integerNPart(opts)); + var pos = position + 1, isNull = null == matchRslt || 0 === parseInt(matchRslt[0].replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), "")); + if (isNull) for (;maskset.validPositions[pos] && (maskset.validPositions[pos].input === opts.groupSeparator || "0" === maskset.validPositions[pos].input); ) delete maskset.validPositions[pos], + pos++; + } + var buffer = []; + for (var vp in maskset.validPositions) void 0 !== maskset.validPositions[vp].input && buffer.push(maskset.validPositions[vp].input); + if (radixInjection && delete maskset.validPositions[radixPos], radixPos > 0) { + var bufVal = buffer.join(""); + if (matchRslt = bufVal.match(opts.regex.integerNPart(opts))) if (radixPos >= position) if (0 === matchRslt[0].indexOf("0")) canClear = matchRslt.index !== position || "0" === opts.placeholder; else { + var intPart = parseInt(matchRslt[0].replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), "")), radixPart = parseInt(bufVal.split(opts.radixPoint)[1]); + 10 > intPart && maskset.validPositions[position] && ("0" !== opts.placeholder || radixPart > 0) && (maskset.validPositions[position].input = "0", + maskset.p = opts.prefix.length + 1, canClear = !1); + } else 0 === matchRslt[0].indexOf("0") && 3 === bufVal.length && (maskset.validPositions = {}, + canClear = !1); + } + } + return canClear; + }, + onKeyDown: function(e, buffer, caretPos, opts) { + var $input = $(this); + if (e.ctrlKey) switch (e.keyCode) { + case Inputmask.keyCode.UP: + $input.val(parseFloat(this.inputmask.unmaskedvalue()) + parseInt(opts.step)), $input.trigger("setvalue"); + break; + + case Inputmask.keyCode.DOWN: + $input.val(parseFloat(this.inputmask.unmaskedvalue()) - parseInt(opts.step)), $input.trigger("setvalue"); + } + } + }, + currency: { + prefix: "$ ", + groupSeparator: ",", + alias: "numeric", + placeholder: "0", + autoGroup: !0, + digits: 2, + digitsOptional: !1, + clearMaskOnLostFocus: !1 + }, + decimal: { + alias: "numeric" + }, + integer: { + alias: "numeric", + digits: 0, + radixPoint: "" + }, + percentage: { + alias: "numeric", + digits: 2, + radixPoint: ".", + placeholder: "0", + autoGroup: !1, + min: 0, + max: 100, + suffix: " %", + allowPlus: !1, + allowMinus: !1 + } + }), Inputmask; +}(jQuery, Inputmask), function($, Inputmask) { + return Inputmask.extendAliases({ + phone: { + url: "phone-codes/phone-codes.js", + countrycode: "", + phoneCodeCache: {}, + mask: function(opts) { + if (void 0 === opts.phoneCodeCache[opts.url]) { + var maskList = []; + opts.definitions["#"] = opts.definitions[9], $.ajax({ + url: opts.url, + async: !1, + type: "get", + dataType: "json", + success: function(response) { + maskList = response; + }, + error: function(xhr, ajaxOptions, thrownError) { + alert(thrownError + " - " + opts.url); + } + }), opts.phoneCodeCache[opts.url] = maskList.sort(function(a, b) { + return (a.mask || a) < (b.mask || b) ? -1 : 1; + }); + } + return opts.phoneCodeCache[opts.url]; + }, + keepStatic: !1, + nojumps: !0, + nojumpsThreshold: 1, + onBeforeMask: function(value, opts) { + var processedValue = value.replace(/^0{1,2}/, "").replace(/[\s]/g, ""); + return (processedValue.indexOf(opts.countrycode) > 1 || -1 === processedValue.indexOf(opts.countrycode)) && (processedValue = "+" + opts.countrycode + processedValue), + processedValue; + } + }, + phonebe: { + alias: "phone", + url: "phone-codes/phone-be.js", + countrycode: "32", + nojumpsThreshold: 4 + } + }), Inputmask; +}(jQuery, Inputmask), function($, Inputmask) { + return Inputmask.extendAliases({ + Regex: { + mask: "r", + greedy: !1, + repeat: "*", + regex: null, + regexTokens: null, + tokenizer: /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, + quantifierFilter: /[0-9]+[^,]/, + isComplete: function(buffer, opts) { + return new RegExp(opts.regex).test(buffer.join("")); + }, + definitions: { + r: { + validator: function(chrs, maskset, pos, strict, opts) { + function RegexToken(isGroup, isQuantifier) { + this.matches = [], this.isGroup = isGroup || !1, this.isQuantifier = isQuantifier || !1, + this.quantifier = { + min: 1, + max: 1 + }, this.repeaterPart = void 0; + } + function analyseRegex() { + var match, m, currentToken = new RegexToken(), opengroups = []; + for (opts.regexTokens = []; match = opts.tokenizer.exec(opts.regex); ) switch (m = match[0], + m.charAt(0)) { + case "(": + opengroups.push(new RegexToken(!0)); + break; + + case ")": + groupToken = opengroups.pop(), opengroups.length > 0 ? opengroups[opengroups.length - 1].matches.push(groupToken) : currentToken.matches.push(groupToken); + break; + + case "{": + case "+": + case "*": + var quantifierToken = new RegexToken(!1, !0); + m = m.replace(/[{}]/g, ""); + var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = 1 === mq.length ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]); + if (quantifierToken.quantifier = { + min: mq0, + max: mq1 + }, opengroups.length > 0) { + var matches = opengroups[opengroups.length - 1].matches; + match = matches.pop(), match.isGroup || (groupToken = new RegexToken(!0), groupToken.matches.push(match), + match = groupToken), matches.push(match), matches.push(quantifierToken); + } else match = currentToken.matches.pop(), match.isGroup || (groupToken = new RegexToken(!0), + groupToken.matches.push(match), match = groupToken), currentToken.matches.push(match), + currentToken.matches.push(quantifierToken); + break; + + default: + opengroups.length > 0 ? opengroups[opengroups.length - 1].matches.push(m) : currentToken.matches.push(m); + } + currentToken.matches.length > 0 && opts.regexTokens.push(currentToken); + } + function validateRegexToken(token, fromGroup) { + var isvalid = !1; + fromGroup && (regexPart += "(", openGroupCount++); + for (var mndx = 0; mndx < token.matches.length; mndx++) { + var matchToken = token.matches[mndx]; + if (matchToken.isGroup === !0) isvalid = validateRegexToken(matchToken, !0); else if (matchToken.isQuantifier === !0) { + var crrntndx = $.inArray(matchToken, token.matches), matchGroup = token.matches[crrntndx - 1], regexPartBak = regexPart; + if (isNaN(matchToken.quantifier.max)) { + for (;matchToken.repeaterPart && matchToken.repeaterPart !== regexPart && matchToken.repeaterPart.length > regexPart.length && !(isvalid = validateRegexToken(matchGroup, !0)); ) ; + isvalid = isvalid || validateRegexToken(matchGroup, !0), isvalid && (matchToken.repeaterPart = regexPart), + regexPart = regexPartBak + matchToken.quantifier.max; + } else { + for (var i = 0, qm = matchToken.quantifier.max - 1; qm > i && !(isvalid = validateRegexToken(matchGroup, !0)); i++) ; + regexPart = regexPartBak + "{" + matchToken.quantifier.min + "," + matchToken.quantifier.max + "}"; + } + } else if (void 0 !== matchToken.matches) for (var k = 0; k < matchToken.length && !(isvalid = validateRegexToken(matchToken[k], fromGroup)); k++) ; else { + var testExp; + if ("[" == matchToken.charAt(0)) { + testExp = regexPart, testExp += matchToken; + for (var j = 0; openGroupCount > j; j++) testExp += ")"; + var exp = new RegExp("^(" + testExp + ")$"); + isvalid = exp.test(bufferStr); + } else for (var l = 0, tl = matchToken.length; tl > l; l++) if ("\\" !== matchToken.charAt(l)) { + testExp = regexPart, testExp += matchToken.substr(0, l + 1), testExp = testExp.replace(/\|$/, ""); + for (var j = 0; openGroupCount > j; j++) testExp += ")"; + var exp = new RegExp("^(" + testExp + ")$"); + if (isvalid = exp.test(bufferStr)) break; + } + regexPart += matchToken; + } + if (isvalid) break; + } + return fromGroup && (regexPart += ")", openGroupCount--), isvalid; + } + var bufferStr, groupToken, cbuffer = maskset.buffer.slice(), regexPart = "", isValid = !1, openGroupCount = 0; + null === opts.regexTokens && analyseRegex(), cbuffer.splice(pos, 0, chrs), bufferStr = cbuffer.join(""); + for (var i = 0; i < opts.regexTokens.length; i++) { + var regexToken = opts.regexTokens[i]; + if (isValid = validateRegexToken(regexToken, regexToken.isGroup)) break; + } + return isValid; + }, + cardinality: 1 + } + } + } + }), Inputmask; +}(jQuery, Inputmask); \ No newline at end of file diff --git a/web/vendor/assets/javascripts/jquery.payment.js b/web/vendor/assets/javascripts/jquery.payment.js new file mode 100644 index 000000000..fc20731ea --- /dev/null +++ b/web/vendor/assets/javascripts/jquery.payment.js @@ -0,0 +1,651 @@ +// Generated by CoffeeScript 1.7.1 +(function() { + var $, cardFromNumber, cardFromType, cards, defaultFormat, formatBackCardNumber, formatBackExpiry, formatCardNumber, formatExpiry, formatForwardExpiry, formatForwardSlashAndSpace, hasTextSelected, luhnCheck, reFormatCVC, reFormatCardNumber, reFormatExpiry, reFormatNumeric, replaceFullWidthChars, restrictCVC, restrictCardNumber, restrictExpiry, restrictNumeric, safeVal, setCardType, + __slice = [].slice, + __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + + $ = window.jQuery || window.Zepto || window.$; + + $.payment = {}; + + $.payment.fn = {}; + + $.fn.payment = function() { + var args, method; + method = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + return $.payment.fn[method].apply(this, args); + }; + + defaultFormat = /(\d{1,4})/g; + + $.payment.cards = cards = [ + { + type: 'visaelectron', + patterns: [4026, 417500, 4405, 4508, 4844, 4913, 4917], + format: defaultFormat, + length: [16], + cvcLength: [3], + luhn: true + }, { + type: 'maestro', + patterns: [5018, 502, 503, 56, 58, 639, 6220, 67], + format: defaultFormat, + length: [12, 13, 14, 15, 16, 17, 18, 19], + cvcLength: [3], + luhn: true + }, { + type: 'forbrugsforeningen', + patterns: [600], + format: defaultFormat, + length: [16], + cvcLength: [3], + luhn: true + }, { + type: 'dankort', + patterns: [5019], + format: defaultFormat, + length: [16], + cvcLength: [3], + luhn: true + }, { + type: 'visa', + patterns: [4], + format: defaultFormat, + length: [13, 16], + cvcLength: [3], + luhn: true + }, { + type: 'mastercard', + patterns: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27], + format: defaultFormat, + length: [16], + cvcLength: [3], + luhn: true + }, { + type: 'amex', + patterns: [34, 37], + format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/, + length: [15], + cvcLength: [3, 4], + luhn: true + }, { + type: 'dinersclub', + patterns: [30, 36, 38, 39], + format: /(\d{1,4})(\d{1,6})?(\d{1,4})?/, + length: [14], + cvcLength: [3], + luhn: true + }, { + type: 'discover', + patterns: [60, 64, 65, 622], + format: defaultFormat, + length: [16], + cvcLength: [3], + luhn: true + }, { + type: 'unionpay', + patterns: [62, 88], + format: defaultFormat, + length: [16, 17, 18, 19], + cvcLength: [3], + luhn: false + }, { + type: 'jcb', + patterns: [35], + format: defaultFormat, + length: [16], + cvcLength: [3], + luhn: true + } + ]; + + cardFromNumber = function(num) { + var card, p, pattern, _i, _j, _len, _len1, _ref; + num = (num + '').replace(/\D/g, ''); + for (_i = 0, _len = cards.length; _i < _len; _i++) { + card = cards[_i]; + _ref = card.patterns; + for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { + pattern = _ref[_j]; + p = pattern + ''; + if (num.substr(0, p.length) === p) { + return card; + } + } + } + }; + + cardFromType = function(type) { + var card, _i, _len; + for (_i = 0, _len = cards.length; _i < _len; _i++) { + card = cards[_i]; + if (card.type === type) { + return card; + } + } + }; + + luhnCheck = function(num) { + var digit, digits, odd, sum, _i, _len; + odd = true; + sum = 0; + digits = (num + '').split('').reverse(); + for (_i = 0, _len = digits.length; _i < _len; _i++) { + digit = digits[_i]; + digit = parseInt(digit, 10); + if ((odd = !odd)) { + digit *= 2; + } + if (digit > 9) { + digit -= 9; + } + sum += digit; + } + return sum % 10 === 0; + }; + + hasTextSelected = function($target) { + var _ref; + if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== $target.prop('selectionEnd')) { + return true; + } + if ((typeof document !== "undefined" && document !== null ? (_ref = document.selection) != null ? _ref.createRange : void 0 : void 0) != null) { + if (document.selection.createRange().text) { + return true; + } + } + return false; + }; + + safeVal = function(value, $target) { + var cursor, error, last; + try { + cursor = $target.prop('selectionStart'); + } catch (_error) { + error = _error; + cursor = null; + } + last = $target.val(); + $target.val(value); + if (cursor !== null && $target.is(":focus")) { + if (cursor === last.length) { + cursor = value.length; + } + $target.prop('selectionStart', cursor); + return $target.prop('selectionEnd', cursor); + } + }; + + replaceFullWidthChars = function(str) { + var chars, chr, fullWidth, halfWidth, idx, value, _i, _len; + if (str == null) { + str = ''; + } + fullWidth = '\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19'; + halfWidth = '0123456789'; + value = ''; + chars = str.split(''); + for (_i = 0, _len = chars.length; _i < _len; _i++) { + chr = chars[_i]; + idx = fullWidth.indexOf(chr); + if (idx > -1) { + chr = halfWidth[idx]; + } + value += chr; + } + return value; + }; + + reFormatNumeric = function(e) { + var $target; + $target = $(e.currentTarget); + return setTimeout(function() { + var value; + value = $target.val(); + value = replaceFullWidthChars(value); + value = value.replace(/\D/g, ''); + return safeVal(value, $target); + }); + }; + + reFormatCardNumber = function(e) { + var $target; + $target = $(e.currentTarget); + return setTimeout(function() { + var value; + value = $target.val(); + value = replaceFullWidthChars(value); + value = $.payment.formatCardNumber(value); + return safeVal(value, $target); + }); + }; + + formatCardNumber = function(e) { + var $target, card, digit, length, re, upperLength, value; + digit = String.fromCharCode(e.which); + if (!/^\d+$/.test(digit)) { + return; + } + $target = $(e.currentTarget); + value = $target.val(); + card = cardFromNumber(value + digit); + length = (value.replace(/\D/g, '') + digit).length; + upperLength = 16; + if (card) { + upperLength = card.length[card.length.length - 1]; + } + if (length >= upperLength) { + return; + } + if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) { + return; + } + if (card && card.type === 'amex') { + re = /^(\d{4}|\d{4}\s\d{6})$/; + } else { + re = /(?:^|\s)(\d{4})$/; + } + if (re.test(value)) { + e.preventDefault(); + return setTimeout(function() { + return $target.val(value + ' ' + digit); + }); + } else if (re.test(value + digit)) { + e.preventDefault(); + return setTimeout(function() { + return $target.val(value + digit + ' '); + }); + } + }; + + formatBackCardNumber = function(e) { + var $target, value; + $target = $(e.currentTarget); + value = $target.val(); + if (e.which !== 8) { + return; + } + if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) { + return; + } + if (/\d\s$/.test(value)) { + e.preventDefault(); + return setTimeout(function() { + return $target.val(value.replace(/\d\s$/, '')); + }); + } else if (/\s\d?$/.test(value)) { + e.preventDefault(); + return setTimeout(function() { + return $target.val(value.replace(/\d$/, '')); + }); + } + }; + + reFormatExpiry = function(e) { + var $target; + $target = $(e.currentTarget); + return setTimeout(function() { + var value; + value = $target.val(); + value = replaceFullWidthChars(value); + value = $.payment.formatExpiry(value); + return safeVal(value, $target); + }); + }; + + formatExpiry = function(e) { + var $target, digit, val; + digit = String.fromCharCode(e.which); + if (!/^\d+$/.test(digit)) { + return; + } + $target = $(e.currentTarget); + val = $target.val() + digit; + if (/^\d$/.test(val) && (val !== '0' && val !== '1')) { + e.preventDefault(); + return setTimeout(function() { + return $target.val("0" + val + " / "); + }); + } else if (/^\d\d$/.test(val)) { + e.preventDefault(); + return setTimeout(function() { + var m1, m2; + m1 = parseInt(val[0], 10); + m2 = parseInt(val[1], 10); + if (m2 > 2 && m1 !== 0) { + return $target.val("0" + m1 + " / " + m2); + } else { + return $target.val("" + val + " / "); + } + }); + } + }; + + formatForwardExpiry = function(e) { + var $target, digit, val; + digit = String.fromCharCode(e.which); + if (!/^\d+$/.test(digit)) { + return; + } + $target = $(e.currentTarget); + val = $target.val(); + if (/^\d\d$/.test(val)) { + return $target.val("" + val + " / "); + } + }; + + formatForwardSlashAndSpace = function(e) { + var $target, val, which; + which = String.fromCharCode(e.which); + if (!(which === '/' || which === ' ')) { + return; + } + $target = $(e.currentTarget); + val = $target.val(); + if (/^\d$/.test(val) && val !== '0') { + return $target.val("0" + val + " / "); + } + }; + + formatBackExpiry = function(e) { + var $target, value; + $target = $(e.currentTarget); + value = $target.val(); + if (e.which !== 8) { + return; + } + if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) { + return; + } + if (/\d\s\/\s$/.test(value)) { + e.preventDefault(); + return setTimeout(function() { + return $target.val(value.replace(/\d\s\/\s$/, '')); + }); + } + }; + + reFormatCVC = function(e) { + var $target; + $target = $(e.currentTarget); + return setTimeout(function() { + var value; + value = $target.val(); + value = replaceFullWidthChars(value); + value = value.replace(/\D/g, '').slice(0, 4); + return safeVal(value, $target); + }); + }; + + restrictNumeric = function(e) { + var input; + if (e.metaKey || e.ctrlKey) { + return true; + } + if (e.which === 32) { + return false; + } + if (e.which === 0) { + return true; + } + if (e.which < 33) { + return true; + } + input = String.fromCharCode(e.which); + return !!/[\d\s]/.test(input); + }; + + restrictCardNumber = function(e) { + var $target, card, digit, value; + $target = $(e.currentTarget); + digit = String.fromCharCode(e.which); + if (!/^\d+$/.test(digit)) { + return; + } + if (hasTextSelected($target)) { + return; + } + value = ($target.val() + digit).replace(/\D/g, ''); + card = cardFromNumber(value); + if (card) { + return value.length <= card.length[card.length.length - 1]; + } else { + return value.length <= 16; + } + }; + + restrictExpiry = function(e) { + var $target, digit, value; + $target = $(e.currentTarget); + digit = String.fromCharCode(e.which); + if (!/^\d+$/.test(digit)) { + return; + } + if (hasTextSelected($target)) { + return; + } + value = $target.val() + digit; + value = value.replace(/\D/g, ''); + if (value.length > 6) { + return false; + } + }; + + restrictCVC = function(e) { + var $target, digit, val; + $target = $(e.currentTarget); + digit = String.fromCharCode(e.which); + if (!/^\d+$/.test(digit)) { + return; + } + if (hasTextSelected($target)) { + return; + } + val = $target.val() + digit; + return val.length <= 4; + }; + + setCardType = function(e) { + var $target, allTypes, card, cardType, val; + $target = $(e.currentTarget); + val = $target.val(); + cardType = $.payment.cardType(val) || 'unknown'; + if (!$target.hasClass(cardType)) { + allTypes = (function() { + var _i, _len, _results; + _results = []; + for (_i = 0, _len = cards.length; _i < _len; _i++) { + card = cards[_i]; + _results.push(card.type); + } + return _results; + })(); + $target.removeClass('unknown'); + $target.removeClass(allTypes.join(' ')); + $target.addClass(cardType); + $target.toggleClass('identified', cardType !== 'unknown'); + return $target.trigger('payment.cardType', cardType); + } + }; + + $.payment.fn.formatCardCVC = function() { + this.on('keypress', restrictNumeric); + this.on('keypress', restrictCVC); + this.on('paste', reFormatCVC); + this.on('change', reFormatCVC); + this.on('input', reFormatCVC); + return this; + }; + + $.payment.fn.formatCardExpiry = function() { + this.on('keypress', restrictNumeric); + this.on('keypress', restrictExpiry); + this.on('keypress', formatExpiry); + this.on('keypress', formatForwardSlashAndSpace); + this.on('keypress', formatForwardExpiry); + this.on('keydown', formatBackExpiry); + this.on('change', reFormatExpiry); + this.on('input', reFormatExpiry); + return this; + }; + + $.payment.fn.formatCardNumber = function() { + this.on('keypress', restrictNumeric); + this.on('keypress', restrictCardNumber); + this.on('keypress', formatCardNumber); + this.on('keydown', formatBackCardNumber); + this.on('keyup', setCardType); + this.on('paste', reFormatCardNumber); + this.on('change', reFormatCardNumber); + this.on('input', reFormatCardNumber); + this.on('input', setCardType); + return this; + }; + + $.payment.fn.restrictNumeric = function() { + this.on('keypress', restrictNumeric); + this.on('paste', reFormatNumeric); + this.on('change', reFormatNumeric); + this.on('input', reFormatNumeric); + return this; + }; + + $.payment.fn.cardExpiryVal = function() { + return $.payment.cardExpiryVal($(this).val()); + }; + + $.payment.cardExpiryVal = function(value) { + var month, prefix, year, _ref; + _ref = value.split(/[\s\/]+/, 2), month = _ref[0], year = _ref[1]; + if ((year != null ? year.length : void 0) === 2 && /^\d+$/.test(year)) { + prefix = (new Date).getFullYear(); + prefix = prefix.toString().slice(0, 2); + year = prefix + year; + } + month = parseInt(month, 10); + year = parseInt(year, 10); + return { + month: month, + year: year + }; + }; + + $.payment.validateCardNumber = function(num) { + var card, _ref; + num = (num + '').replace(/\s+|-/g, ''); + if (!/^\d+$/.test(num)) { + return false; + } + card = cardFromNumber(num); + if (!card) { + return false; + } + return (_ref = num.length, __indexOf.call(card.length, _ref) >= 0) && (card.luhn === false || luhnCheck(num)); + }; + + $.payment.validateCardExpiry = function(month, year) { + var currentTime, expiry, _ref; + if (typeof month === 'object' && 'month' in month) { + _ref = month, month = _ref.month, year = _ref.year; + } + if (!(month && year)) { + return false; + } + month = $.trim(month); + year = $.trim(year); + if (!/^\d+$/.test(month)) { + return false; + } + if (!/^\d+$/.test(year)) { + return false; + } + if (!((1 <= month && month <= 12))) { + return false; + } + if (year.length === 2) { + if (year < 70) { + year = "20" + year; + } else { + year = "19" + year; + } + } + if (year.length !== 4) { + return false; + } + expiry = new Date(year, month); + currentTime = new Date; + expiry.setMonth(expiry.getMonth() - 1); + expiry.setMonth(expiry.getMonth() + 1, 1); + return expiry > currentTime; + }; + + $.payment.validateCardCVC = function(cvc, type) { + var card, _ref; + cvc = $.trim(cvc); + if (!/^\d+$/.test(cvc)) { + return false; + } + card = cardFromType(type); + if (card != null) { + return _ref = cvc.length, __indexOf.call(card.cvcLength, _ref) >= 0; + } else { + return cvc.length >= 3 && cvc.length <= 4; + } + }; + + $.payment.cardType = function(num) { + var _ref; + if (!num) { + return null; + } + return ((_ref = cardFromNumber(num)) != null ? _ref.type : void 0) || null; + }; + + $.payment.formatCardNumber = function(num) { + var card, groups, upperLength, _ref; + num = num.replace(/\D/g, ''); + card = cardFromNumber(num); + if (!card) { + return num; + } + upperLength = card.length[card.length.length - 1]; + num = num.slice(0, upperLength); + if (card.format.global) { + return (_ref = num.match(card.format)) != null ? _ref.join(' ') : void 0; + } else { + groups = card.format.exec(num); + if (groups == null) { + return; + } + groups.shift(); + groups = $.grep(groups, function(n) { + return n; + }); + return groups.join(' '); + } + }; + + $.payment.formatExpiry = function(expiry) { + var mon, parts, sep, year; + parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/); + if (!parts) { + return ''; + } + mon = parts[1] || ''; + sep = parts[2] || ''; + year = parts[3] || ''; + if (year.length > 0) { + sep = ' / '; + } else if (sep === ' /') { + mon = mon.substring(0, 1); + sep = ''; + } else if (mon.length === 2 || sep.length > 0) { + sep = ' / '; + } else if (mon.length === 1 && (mon !== '0' && mon !== '1')) { + mon = "0" + mon; + sep = ' / '; + } + return mon + sep + year; + }; + +}).call(this); \ No newline at end of file diff --git a/websocket-gateway/lib/jam_websockets/router.rb b/websocket-gateway/lib/jam_websockets/router.rb index 62f5b6b87..00d60a54a 100644 --- a/websocket-gateway/lib/jam_websockets/router.rb +++ b/websocket-gateway/lib/jam_websockets/router.rb @@ -1310,7 +1310,6 @@ module JamWebsockets @message_stats['total_time'] = total_time @message_stats['banned_users'] = @temp_ban.length - Stats.write('gateway.stats', @message_stats) # clear out stats