Seed MnoHub database

When creating a new environment for your marketplace, here is a script you can run to seed your database


seeds.rb
#======================================================================

# Create Applications

#======================================================================

module CreateApps

  def self.create_app(opts)

    # Create or update application
    opts = ActiveSupport::HashWithIndifferentAccess.new(opts)
    app_opts = opts.slice(*App.column_names).symbolize_keys
    app_opts.merge!(account_id: 1)
    app_opts.merge!(base_price_currency: 'AUD', base_price_cents: 2900) if opts[:stack] == 'cube'

    app = App.find_by_nid(opts[:nid])

    if app
      app.update_attributes(app_opts)
    else
      app = App.create!(app_opts)
    end

    # Cube standard configuration
    if opts[:stack] == 'cube'
      app.update_attributes(
        active: true,
        free_trial_duration: 14,
        durations: {"provisioning"=>60, "starting"=>30, "stopping"=>20, "terminating"=>30}
      )
      self.create_app_templates(app, opts)
    else
      # Connector/Cloud standard configuration
      app.update_attributes(active: true, base_price_cents: nil, per_user_licence: false)
      if opts[:stack] == 'cloud'
        # Add sandbox application
        sandbox_name = "Sandbox: #{app.name} #{app.sandbox_apps.count + 1}"
        sandbox_app = app.sandbox_apps.create(name: sandbox_name, account_id: 1, stack: 'cloud')
        # Set default metadata
        app.update_attributes(metadata: {"sso"=>{"enabled"=>true, "idm"=>"https://#{app.nid}.com", "init_path"=>"/maestrano/auth/saml/init/default"}})
        sandbox_app.update_attributes(metadata: {"sso"=>{"enabled"=>true, "idm"=>"https://staging.#{app.nid}.com", "init_path"=>"/maestrano/auth/saml/init/default"}})
      end
    end

    # Attempt to upload logo
    if app && !app.read_attribute(:logo)
      path = ['png','jpg'].map { |ext| "#{Rails.root}/vendor/app-logos/#{app.nid}.#{ext}" }.select { |p| File.exists?(p) }.first
      app.logo = File.open(path) if path
      app.save
    end
    app

  end



  def self.create_app_templates(app, opts)
    templates = {
      mini:   {name: "Mini",
        description: "1-5 simultaneous users", price_cents: 15, monthly_price_cents: 2990, currency: "AUD", pu: 2, free_trial_hourly: true, free_trial_monthly: true},
      medium: {name: "Medium",
        description: "6-10 simultaneous users", price_cents: 45, monthly_price_cents: 8970, currency: "AUD", pu: 6, free_trial_hourly: false, free_trial_monthly: false},
      maxi:   {name: "Maxi",
        description: "11-20 simultaneous users", price_cents: 90, monthly_price_cents: 17940, currency: "AUD", pu: 12, free_trial_hourly: false, free_trial_monthly: false}
    }

    new_app_templates = templates.map do |plan, template|
      AppTemplate.create!(name: template[:name], app_version: app.version,
        description: template[:description], price_cents: template[:price_cents], currency: template[:currency],
                          active: true, app: app, cube_template_human_id: "docker/maestrano/#{opts[:template]}", stack: "cube", pu: template[:pu], monthly_price_cents: template[:monthly_price_cents],
                          monthly_price_currency: template[:currency], free_trial_hourly: template[:free_trial_hourly], free_trial_monthly: template[:free_trial_monthly],
                          sso_enabled: true,
                          soa_eligible: true, ssl_enabled: true, plan: plan.to_s)
    end

    # Disable previous templates
    (app.app_templates - new_app_templates).each{|t| t.update_attributes(active: false)}

  end



  def self.create_organization(name, tenant)

    # organization = Organization.where(name: name, mnoe_tenant_id: tenant.id).first
    # organization = Organization.create(name: name, mnoe_tenant: tenant) unless organization
    organization = Organization.where(name: name).first
    organization = Organization.create(name: name) unless organization
    organization

  end



  def self.create_user(email, first_name, last_name, role, organization, admin=false)

    user = User.find_by_email(email.strip)
    user = User.create!(email: email.strip, password: 'password', password_confirmation: 'password', name: first_name, surname: last_name) unless user
    user.metadata = (user.metadata || {}).merge(has_analytics_beta_access: true)
    user.admin = admin
    # user.mnoe_tenant = organization.mnoe_tenant
    user.confirm!
    OrgaRelation.create(user: user, organization: organization, role: role)
    user

  end




  def self.create_app_instance(me, app, organization, uid=nil)

    uid = "#{app.nid}.app.dev.maestrano.io"
    app_instance = AppInstance.find_by_uid(uid)
    unless app_instance
      app_instance = AppInstance.create!(app: app, name: app.name, status: 'running', stack: 'cube', pu: 2, owner: organization, uid: uid, billing_type: 'hourly',
                                        app_template: app.app_templates_active.first, region: 'ap-southeast-1', sso_enabled: true, soa_enabled: true, soa_eligible: true)
      app_instance.api_key = Digest::SHA2.hexdigest("#{Time.now.to_s}-#{rand(1000)}")
      app_instance.api_secret = SecureRandom.uuid
      app_instance.save!
    end

  end




  def self.create_connector_app(me, app, organization)

    cloud_partner = CloudPartner.find_by_name("#{app.name} Cloud Partner")
    unless cloud_partner
      cloud_partner = CloudPartner.create!(app: app, name: "#{app.name} Cloud Partner", commission: '{name: "Percentage", options: {percentage: 0.15}}',
                                            email: 'test@test.com', address: '21 Jump Street', country: 'Australia')
    end

    app_instance = AppInstance.where(name: app.name, app_id: app.id, owner_id: organization.id).first
    unless app_instance
      app_instance = AppInstance.create!( app: app, name: app.name, status: 'running', stack: 'connector', owner: organization)
      app_instance.save!
    end

  end



  def self.create_cloud_app(me, app, organization)
    cloud_partner = CloudPartner.find_by_name("#{app.name} Cloud Partner")

    unless cloud_partner
      cloud_partner = CloudPartner.create!(app: app, name: "#{app.name} Cloud Partner", commission: '{name: "Percentage", options: {percentage: 0.15}}',
                                            email: 'test@test.com', address: '21 Jump Street', country: 'Australia')
    end

    app_instance = AppInstance.where(name: app.name, app_id: app.id, owner_id: organization.id).first

    unless app_instance
      app_instance = AppInstance.create!( app: app, name: app.name, status: 'running', stack: 'cloud', owner: organization)
      app_instance.save!
    end

  end

end




#======================================================================

# Setup applications

#======================================================================

[

  # Cubes

  { nid: 'vtiger6', name: 'Vtiger', template: 'vtiger6', stack: 'cube', version: '6.3.0', active: true,

    categories: ["Customer Management", "Collaboration"],

    key_benefits: [{:text=>"Stay on top of the relationship with your customers"}, {:text=>"Seamlessly manage your marketing and sales programs"}, {:text=>"Be mobile and integrate your everyday tools with extra plugins"}],

    key_features: [{:text=>"Organize Sales"}, {:text=>"Access Anywhere"}, {:text=>"Easy to use"}, {:text=>"No software"}, {:text=>"Optimize time"}, {:text=>"High productivity"}],

    tiny_description: "Manage your Customers",

    description: "[vTiger](http://www.vtiger.com) provides customer relationship management (CRM) tools to support sales, marketing, and support teams with powerful services to efficiently and effectively collaborate and deliver the ideal customer experience. vTiger is a great CRM application for small to medium sized businesses with comparable features to SugarCRM and Salesforce.com.\n\nIt is an easy to use, dashboard-based CRM with many add-on modules to allow for a full customization of the tool.\n\nIts import wizard feature makes the transition from any existing CRM a breeze and all the information is presented in a hierarchical structure, allowing for rapid and easy access.\n\nThis CRM is used by more than 120,000 companies across the World and has more than 3 million downloads to date. This tool is ideal for Small & Medium businesses on the look for flexibility and efficiency.\n\nAdd the peace of mind of a deployment by Maestrano, and you are all set and guaranteed to have the best tool, always up to date.",

    terms_url: "https://www.vtiger.com/vtiger-public-license/",

    website: 'http://www.vtiger.com',

    appinfo: {"connecReady"=>true, "responsive"=>true, "beta"=>false, "popular"=>true, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'magento', name: 'Magento', template: 'magento', stack: 'cube', version: '1.9.2.1', active: true,

    categories: ["Internet and Online"],

    key_benefits: [{"text"=>"Accelerate the growth of your online store"}, {"text"=>"Provides more than 50 payment gateways"}, {"text"=>"Allows for various discounts and promotions during check-out"}, {"text"=>""}],

    key_features: [{"text"=>"Improve your online store"}, {"text"=>"More than 50 payment gateways"}, {"text"=>"Allows for various discounts and promotions during check-out"}],

    tiny_description: "Get your e-commerce website easily",

    description: "<p><span>Magento is an ecommerce platform which provides online merchants with a flexible shopping cart system, as well as control over the look, content and functionality of their online store. Magento offers powerful marketing, search engine optimization, and catalog-management tools. </span></p><p>Magento’s ability to scale allows shops with only a few products and simple needs to easily expand to tens of thousands of products and complex custom behavior without changing platforms. It offers a variety of plug-ins and themes which can easily enhance a customer’s experience. </p><p>Magento is designed to be utilized as an application by someone who isn’t a developer.&nbsp;You can use Magento to build a branded website for desktops as well as mobile devices.</p>\n",

    terms_url: 'http://www.gnu.org/licenses/gpl-3.0.html',

    website: 'http://magento.com/',

    human_url: "\"\#{url}/administrator\"",

    appinfo: {"connecReady"=>true, "responsive"=>true, "beta"=>false, "popular"=>true, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'prestashop', name: 'PrestaShop', template: 'prestashop', stack: 'cube', version: '1.6.1.2', active: true,

    categories: ["Internet and Online"],

    key_benefits: [{"text"=>"Accelerate the growth of your online store"}, {"text"=>"Provides more than 50 payment gateways"}, {"text"=>"Allows for various discounts and promotions during check-out"}, {"text"=>""}],

    key_features: [{"text"=>"Improve your online store"}, {"text"=>"More than 50 payment gateways"}, {"text"=>"Allows for various discounts and promotions during check-out"}],

    tiny_description: "Create your free online store",

    description: "Create your online store with PrestaShop&amp;#039;s free shopping cart software. Build an ecommerce website for free and start selling online with hundreds of powerful features.",

    website: 'https://www.prestashop.com',

    human_url: "\"\#{url}/admin-dev\"",

    appinfo: {"connecReady"=>true, "responsive"=>true, "beta"=>false, "popular"=>true, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'wordpress', name: 'WordPress', template: 'wordpress', stack: 'cube', version: '4.2.4', active: true,

    categories: ["Content Management"],

    key_benefits: [{:text=>"Rely on a proven tool that already helped develop more than 50 million sites globally", :icon=>"icon-mno-lp-esearch"}, {:text=>"Customize and optimize your website with the plugin library", :icon=>"icon-mno-lp-pen"}, {:text=>"Get on board very quickly with the intuitive interface", :icon=>"icon-mno-lp-codefree"}],

    tiny_description: "Make beautiful websites and blogs",

    description: "WordPress is web software you can use to create your website or blog. WordPress is a state-of-the-art semantic personal publishing platform with a focus on aesthetics, web standards, and usability.Used on million of websites this content management system is an intuitive tool that will allow you to create awesome websites in a very short amount of time. You do not need to have any software development knowledge to use this application. Just let your creative mind take over and use the features of the tool to get amazing and professional results.As part of Maestrano's deployment, your websites are automatically hosted by our servers at no extra cost. No need to worry about paying for hosting or uploading your website, we do it for you.",

    soa_eligible: false,

    website: 'http://wordpress.com',

    human_url: "\"\#{url}/wp-admin\"",

    appinfo: {"connecReady"=>false, "responsive"=>true, "beta"=>false, "popular"=>true, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'orangehrm', name: 'OrangeHRM', template: 'orangehrm', stack: 'cube', version: '3.2.1', active: true,

    categories: ["Human Resources and Employee Management"],

    key_benefits: [{:text=>"Easily manage your employees' information, performance, training and recruitment with one system"}, {:text=>"Make your system evolve with you thanks to the extra modules"}, {:text=>"Simplify your recruitment process"}],

    key_features: [{:text=>"Intuitive dashboard"}, {:text=>"Time & Attendance Management"}, {:text=>"Personal Information Management"}, {:text=>"Recruitment"}, {:text=>"Leave/Time Off management"}, {:text=>"Performance & KPI Management"}],

    tiny_description: "Manage your employees easily",

    description: "OrangeHRM is a precise and convenient HR Management (HRM) system targeted for Small and Medium Enterprises. The functionality includes employee information management, employee absence management, recruitment management, employee performance evaluation, leaves management, reporting lines management and many other HR management tools. Orange HRM also provides Expense tracker, timesheets, leave calendar, notifications and exports to Microsoft Excel (CSV extractor) for reports, leave and recruitment details.\n\nMore than 1 million users worldwide trust this HR application. It is an all-in-one solution to manage your workforce, thanks to the various management modules already included in the tool: employee information, employee absence, recruitment, employee performance evaluation and other HR management tools.\n\nThe application is simple and intuitive and will deliver awesome results which will allow you to have a better understanding of the status of your workforce and help manage better your most critical resource - your people!\n\nAdded to the peace of mind of a deployment by Maestrano, you are all set and guaranteed to have the best tool, always up to date.",

    terms_url: "http://www.gnu.org/licenses/gpl-2.0.html",

    appinfo: {"connecReady"=>true, "responsive"=>false, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'dolibarr', name: 'Dolibarr', template: 'dolibarr', stack: 'cube', version: '3.7.1', active: true,

    categories: ["Operations Management"],

    key_benefits: [{:text=>"Save time by using a system that combines the features of an ERP and a CRM."}, {:text=>"Centralize your resource management"}, {:text=>"Increase productivity by improving collaboration"}],

    key_features: [],

    tiny_description: "Enterprise Resource Management",

    description: "Dolibarr is an easy to use ERP and CRM software for small to mid-sized businesses, foundations or freelancers. This ERP includes all the features you would expect and also Customer Relationship Management (CRM) components, among others inventory, warehouse, order, invoice, shipment, POS, members for foundations, bank accounts...\n\nIts easy to use interface does not require any technical knowledge.\n\nMore and more businesses are turning towards Dolibarr because of its simplicity and efficiency. It is one of the prime ERP systems for European small and medium businesses. Deployed on Maestrano, it will offer you a peace of mind you wouldn't expect from your ERP!",

    terms_url: "http://www.gnu.org/licenses/gpl-2.0.html",

    appinfo: {"connecReady"=>true, "responsive"=>false, "beta"=>false, "popular"=>true, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'timetrex', name: 'TimeTrex', template: 'timetrex', stack: 'cube', version: '8.0.9', active: true,

    categories: ["Accounting and Finance","Human Resources and Employee Management"],

    key_benefits: [{:text=>"Track and monitor employee attendance accurately in real-time from anywhere in the world"}, {:text=>"Increase productivity by accurately identifying labor costs by employee, project, department or task type"}, {:text=>"Engage your employees with an intuitive and easy to use interface"}],

    key_features: [{:text=>"Complete Payroll System"}, {:text=>"Time & Attendance Management"}, {:text=>"Personal Information Management"}, {:text=>"Recruitment"}, {:text=>"Leave/Time Off management"}, {:text=>"Performance & KPI Management"}],

    tiny_description: "Run your payroll easily",

    description: "TimeTrex is a complete web-based payroll and time management suite which offers many great features such as employee scheduling, time and attendance (timeclock, time sheet), job costing, human resource management (HRM), invoicing, expense tracking and payroll all in one application.\n\nWith TimeTrex, you can engage your employees with the system quickly thanks to the intuitive and user-friendly interface. The system automates time sheet reconciliation based on employees' input and you can securely run your payroll from the system.\n\nMore than 400,000 users worldwide trust this payroll application to manage their workforce and run their payroll processes.\n\nAdd the peace of mind of a deployment by Maestrano, and you are all set and guaranteed to have the best tool, always up to date.",

    terms_url: "http://www.timetrex.com/TPL",

    appinfo: {"connecReady"=>true, "responsive"=>false, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'sugarcrm', name: 'SugarCRM', template: 'sugarcrm_dev', stack: 'cube', version: '6.5.21', active: true,

    categories: ["Customer Management"],

    key_benefits: [{:text=>"Empower your sales, marketing and support teams to develop better customer relationships"}, {:text=>"Improve your sales by better understanding your customers with reports and analytics"}, {:text=>"Provide your employees with the latest social media capabilities"}],

    key_features: [{:text=>"Organize Sales"}, {:text=>"Access Anywhere"}, {:text=>"Easy to use"}, {:text=>"No software"}, {:text=>"Optimize time"}, {:text=>"High productivity"}],

    tiny_description: "Manage your customers",

    description: "SugarCRM is Customer Relationship Management very easy to configure and adapt to user's changing needs. SugarCRM is easy to use, intuitive and provides all the features commonly found in the traditional commercial CRMs like sales-force automation, marketing campaigns, customer support, collaboration, Mobile CRM, Social CRM and reporting.\n\nThis CRM is used worldwide by more than 11 million small and medium businesses in all types of industries.\n\nThe application can be easily tailored by adding modules and meet the specific needs of your business. Added to the peace of mind of a deployment by Maestrano, you are all set and guaranteed to have the best tool, always up to date.", 

    terms_url: "http://www.gnu.org/licenses/gpl-2.0.html",

    appinfo: {"connecReady"=>true, "responsive"=>false, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'joomla', name: 'Joomla', template: 'joomla-cms', stack: 'cube', version: '3.4.4', active: true,

    categories: ["Content Management System", "Internet and Online"],

    key_benefits: [{:text=>"Separately edit, change and delete the content and the design of your website", :icon=>""}, {:text=>"Handle very easily large volumes of content", :icon=>""}, {:text=>"Ideal tool to develop a  standard website for a small-to-mid size business.", :icon=>""}],

    key_features: [],

    tiny_description: "Make beautiful websites easily",

    description: "Joomla is a Content Management System (CMS) used for publishing content on the Web and intranets. Its user-friendly interface makes it appealing for non-technical users that will find using it easy and non-disruptive.The application can be customized to best fit your needs by adding modules and components and works with virtually any language as it is built on PHP and uses MySQL as it's database.\nJoomla is also model-view-controller (MVC) web application framework.The application includes features such as page caching, RSS feeds, printable version of pages, news flashes, blogs, polls, search and support for language internationalization.\nMaestrano will host your website and intranet at no extra cost as part of the service provided in our monthly plan. All you need to do is create your content. Joomla and Maestrano will do the rest!",

    terms_url: "http://www.gnu.org/licenses/gpl-2.0.html",

    soa_eligible: false,

    appinfo: {"connecReady"=>false, "responsive"=>true, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'simpleinvoices', name: 'Simple Invoices', template: 'simpleinvoices', stack: 'cube', version: '2011.1', active: true,

    categories: ["Accounting"],

    key_benefits: [{:text=>"Save time with an easy customizable tool to create all the invoices you need", :icon=>"icon-mno-lp-chrono"}, {:text=>"Support your development with about 20 languages available", :icon=>"icon-mno-lp-invoice"}, {:text=>"Be mobile and access your system anywhere through the web based interface", :icon=>"icon-mno-lp-responsive"}],

    tiny_description: "Your invoices, in a flash",

    description: "Simple Invoices is a simple web based invoicing solution for personal/home-office/small business needs. It offers the basic option to enable people to create and manage invoicing.\nThe interface is very well designed and straightforward to use. With this application you will never again bother entering all your invoices manually or spend hours formatting them to get the result your company deserves. Just configure it and generate, send and track your invoices as you need.\nThis application will also help you easily track your finances among hundreds of other great features.\nDeployed on Maestrano, this application will change the way your business considers invoicing!",

    website: 'http://www.simpleinvoices.org',

    appinfo: {"connecReady"=>true, "responsive"=>false, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'drupal', name: 'Drupal', template: 'drupal', stack: 'cube', version: '7.39', active: true,

    categories: ["Content Management"],

    key_benefits: [{:text=>"Easily organize, manage and publish your content.", :icon=>""}, {:text=>"Customize your website with the 1500+ different themes and the 15,000+ modules.", :icon=>""}, {:text=>"Benefit from innovation of a worldwide community.", :icon=>""}],

    tiny_description: "Easily publish content on the web",

    description: "Drupal is a Content Management System (CMS) for publishing content on the Web and intranets. It is also used for knowledge management and business collaboration.  Drupal is also described as a web application framework, as it meets the generally accepted feature requirements for such frameworks.\nThe application includes features such as page caching, RSS feeds, printable version of pages, news flash, user administration. Drupal can support a diverse range of web projects ranging from personal weblogs to large community-driven sites.\nThe Drupal mission is to develop a leading edge open-source content management system that implements the latest thinking and best practices in community publishing, knowledge management, and software design.",

    soa_eligible: false,

    website: 'https://www.drupal.org',

    appinfo: {"connecReady"=>false, "responsive"=>false, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'limesurvey', name: 'eEasySurvey', template: 'limesurvey', stack: 'cube', version: '2.06', active: true,

    categories: ["Online Surveying"],

    key_benefits: [{:text=>"Get on board very easily with its intuitive user interface and its WYSIWYG editor", :icon=>""}, {:text=>"Save time by using the numerous templates available or create your own if you need customization", :icon=>""}, {:text=>"Integrate rich messages in your survey such as images or videos to get better insights", :icon=>""}],

    tiny_description: "Survey and analyze your market",

    description: "eEasySurvey is a survey software to create online surveys. eEasySurvey allows users to quickly create intuitive, powerful, online question-and-answer surveys that can work for tens to thousands of participants without much effort.  The survey software itself is self-guiding for the respondents who are participating.\nThe layout and design of the survey can be modified under a template system. Features open/closed surveys, branching, participant administration, quotas, WYSIWYG HTML editor, email invitations &amp; reminders, assessments, basic statistics and more.\nUsers can use rich text in questions and messages, using a rich text editor, and images and videos can be integrated into the survey. Additionally, templates can be imported and exported through the template editor. Once a survey is finalized, the user can activate it, making it available for respondents to view and answer. Likewise, questions can also be imported and exported through the editor interface. eEasySurvey has no limit on the number of surveys a user can create, nor is there a limit on how many participants can respond. Aside from technical and practical constraints, there is also no limit on the number of questions each survey may have.\nAdded to the peace of mind of a deployment by Maestrano, you are all set and guaranteed to have the best tool, always up to date.",

    website: 'https://www.limesurvey.org',

    human_url: "\"\#{url}/index.php/admin\"",

    appinfo: {"connecReady"=>true, "responsive"=>false, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },




  # Connectors

  { nid: 'xero', name: 'Xero', stack: 'connector', active: true,

    categories: ['Accounting and Finance', 'Human Resources and Employee Management'],

    key_benefits: [{"text"=>"Make accounting a breeze"}, {"text"=>"Manage invoices"}, {"text"=>"Manage sales/expenses"}],

    key_features: [{"text"=>"Intuitive interface"}, {"text"=>"Easy setup"}, {"text"=>"Online accountants available"}],

    tiny_description: "Intuitive Accounting",

    description: "Xero is award winning web-based accounting software for small business owners and their advisors. It is beautifully designed and easy to use. \n\nStay up to date on your business finances and cashflow, generate real time reports, and customize and send invoices using Xero. The accounting application allows you to import bank transactions, making reconciliation a quick and easy task. With Xero you can authorize anyone to access your accounts and collaborate on your finances thanks to the unlimited number of user logins.", testimonials: [{"author"=>"Jeffery Battersby", "company"=>"Macworld", "text"=>"Xero allows you to add as many users as you want without any additional fees."}, {"author"=>"Jonathan Garro", "company"=>"GetApp", "text"=>"Award winning accounting application designed for small businesses and their advisors."}, {"author"=>"Greg Lam", "company"=>"The Sleeter Group", "text"=>"Xero is the best software for automation, both because of its built-in features as well as because of its integrations."}],

    terms_url: "https://www.xero.com/au/about/terms/",

    website: "https://go.xero.com",

    metadata: {"sso"=>{"init_path"=>"/organisationlogin/default.aspx", "idm"=>"https://go.xero.com/"}, "custom_info_required"=>{"country"=>true}},

    appinfo: {"connecReady"=>true, "responsive"=>true, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'quickbooks', name: 'QuickBooks', stack: 'connector', active: true,

    categories: ['Accounting and Finance', 'Human Resources and Employee Management'],

    key_benefits: [{"text"=>"Your accounting sorted in one click"}, {"text"=>"Manage payroll easily for your employees"}, {"text"=>"Benefit from professional advice"}],

    key_features: [{"text"=>"Fast and easy setup"}, {"text"=>"Beautiful dashboard"}, {"text"=>"Mobile ready - anywhere, anytime"}],

    tiny_description: "Accounting and Payroll",

    description: "QuickBooks Online is a powerful accounting system allowing you to manage customers, invoices, expenses and payroll for your employees.\n\nQuickBooks Online has an intuitive interface with a very easy to use dashboard that presents a consolidated view of your finances so you can stay on top of your financial situation.\n\nQuickBooks Online is available from all types of devices allowing you to work on the go and always be ready to manage your business.\n",

    terms_url: "http://quickbooks.intuit.com/commerce/catalog/fragments/quickbooks/common/legal.jsp",

    website: "http://quickbooks.intuit.com",

    metadata: {"app"=>{"host"=>"https://qbo.intuit.com"}, "sso"=>{"init_path"=>"/app/homepage"}, :custom_info_required=>{:country=>true}},

    appinfo: {"connecReady"=>true, "responsive"=>true, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'myob', name: 'MYOB', stack: 'connector', active: true,

    categories: ['Accounting and Finance', 'Human Resources and Employee Management'],

    key_benefits: [{"text"=>"Stay ahead of tax changes"}, {"text"=>"Totally flexible"}, {"text"=>"Painless payroll and timesheets"}],

    key_features: [{"text"=>"Stay ahead of tax changes"}, {"text"=>"Totally flexible"}, {"text"=>"Painless payroll and timesheets"}],

    tiny_description: "Power to manage your business, your way",

    description: "MYOB AccountRight is Australia's favourite accounting software. AccountRight is a flexible way to manage your business from your desktop. MYOB AccountRight is the smarter way to manage your books and accounting requirements.\n\nWith MYOB AccountRight you get your accountant to work with your team on the same file at the same time. You get everything you would expect from your accounting software, including management of GST, BAS calculations, quotes. Your entire sales process can be managed from quoting to issuing receipts! You also track your own purchases and pay expenses so you know exactly what is happening in your business.\n\n----------------------------------------------------------------------------------------------\n\nMYOB Essentials is the cloud application of MYOB. MYOB Essentials focuses on 3 pillars: easy, on-the-go and better value for MYOB clients. It covers the 8 necessities of online accounting:\n1 – A snapshot of your business - The homepage shows the dashboard, which is designed to be simple, clean and captures the business’ financial standings.\n\n2 – Sales including quotes, and invoices - Create quotes, turn them into invoices and stay on top of your GST and BAS obligations easily.\n\n3 – Expenses -  MYOB Essentials lets you keep track of all the things you have to pay such as rent and supplier bills, and tells you when they are due.\n\n4 – Bank feeds - Bank feeds allows you to connect your bank account to MYOB Essentials. Every bank transaction will be synced into MYOB Essentials automatically. The transactions will then be matched to your sales, expense or any rules that you set.\n\n5 – Contacts - Keep track of all your business contacts in one place, especially those that owe you money.\n\n6 – Payroll - If you hire people, maintaining payroll will be a breeze with MYOB Essentials\n\n7 –  Fulfilling GST and BAS obligations - Preparing your BAS is super easy as MYOB Essentials can generate a GST report for you anytime, whether you submit your BAS quarterly or monthly.\n\n8 –  Reports - MYOB Essentials offer 30 reports on your business including GST, BAS, and Profit and Loss.",

    terms_url: "http://myob.com.au/business/customer-service-support/customer-service/myob-terms-and-conditions---page-1257828417451",

    website: "http://myob.com.au",

    metadata: {"sso"=>{"init_path"=>"/LA/public.htm#login", "idm"=>"https://essentials.myob.com.au"}, :custom_info_required=>{:country=>true, :product=>true}},

    appinfo: {"connecReady"=>true, "responsive"=>false, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },

  { nid: 'eventbrite', name: 'Eventbrite', stack: 'connector', active: true,

    categories: ['Operations Management'],

    key_benefits: [{"text"=>"Customize your event page"}, {"text"=>"Let attendees pay online"}, {"text"=>"Manage your guests"}],

    key_features: [],

    tiny_description: "Get everything you need to bring people to your events",

    description: "Eventbrite is an event registration management system, easy to use, attractive and convenient service with great add-ons including social media integration and mobile apps. \n\nAs far as how your registration form looks, you have a fair amount of freedom to customize the colours, logos and graphics. Alternatively, you can embed your form in your own website or blog by grabbing the HTML code. \n\nIf you are organizing an event with a fairly simple registration process then you’ll need to look a long way to find anything better than Eventbrite. The system has nailed it in terms of being modern, simple and functional. It is highly recommended for any type of one-day event (e.g. a gala dinner, one-day workshop, concert or fundraiser).\n\nIt's free for organizers to use Eventbrite as long as you're not charging for tickets! There are no monthly charges, enrollment costs, or setup fees—and Eventbrite gives you access to powerful reporting and promotional tools, mobile sales and box office features, and 24/7 customer support. If you're charging for ticket sales on Eventbrite, your will be charged a fee per ticket (check inside your app for more details), plus a 3% payment processing fee in U.S. dollars. If you sell tickets on-site with Neon or At The Door mobile apps, only the payment processing fee applies.",

    terms_url: "https://www.eventbrite.com.au/tos/",

    website: "https://www.eventbrite.com/r/maestrano",

    metadata: {"sso"=>{"init_path"=>"/", "idm"=>"http://www.eventbrite.com.au/r/maestrano"}},

    appinfo: {"connecReady"=>true, "responsive"=>true, "beta"=>false, "popular"=>false, "new"=>false, "delisted"=>false, "coming_soon"=>false, "coming_soon_eta"=>""}

  },




  # Cloud Applications

  { nid: 'ranqx', name: 'Ranqx', stack: 'cloud', active: true,

    categories: ["Accounting"],

    key_benefits: [{"text"=>"Easy Business Intelligence", "icon"=>""}, {"text"=>"Improve your understanding of your position in your industry", "icon"=>""}, {"text"=>"Learn what your customers really say about you with live customer feedback", "icon"=>""}],

    key_features: [{"text"=>"", "icon"=>""}, {"text"=>"", "icon"=>""}, {"text"=>"", "icon"=>""}],

    tiny_description: "Business intelligence made easy", description: "Whether you sell products or services to consumers or other businesses, ranqx makes Business Intelligence easy with live customer feedback and financial benchmarks. This helps you compare your performance and improve your results.\nAccess powerful business information any time anywhere with ranqx’s online dashboards that show how you perform compared to industry averages. Want to know how you are performing against others in your industry? Load your financials manually, or securely connect to your online accounting software provider such as Xero to see how you anonymously compare to industry averages."

  },

  { nid: 'signmee', name: 'SignMee', stack: 'cloud', active: true,

    categories: ["Operations Management"],

    key_benefits: [{"text"=>"Simplify the sign-off process to close deals faster", "icon"=>""}, {"text"=>"Track and measure with ease - when and whos sent, opened, filled, signed, declined", "icon"=>""}, {"text"=>"Automated collection and collation of customer data without rekeying", "icon"=>""}],

    key_features: [{"text"=>"", "icon"=>""}, {"text"=>"", "icon"=>""}, {"text"=>"", "icon"=>""}],

    tiny_description: "Making it simple to reply and sign online", description: "Forms are needed regularly in business to collect customer data, payments and sign-off.\nIn most businesses today, forms management is email driven involving document attachments, printing, replying, signing then returning (via scanning and email, fax, post...) for processing/rekeying. This largely manual process is disjointed, laborious and costly for the business and contact. \nSignmee eForms engine automates form management, making life easier for everyone.  With Signmee, a business can create and send web-based eForms to customers, who in turn can fill pay and sign online in one transaction.  The signed form is then stored in the contacts Signmee Inbox  and business response library.\n\nThe business is automatically alerted when a form is signed, with real time access to the response data and payments. Everything is traceable and extractable making it easy for businesses  to process response data. \n\nWith Signmee there is nothing to install, and no need to customise. No need to build complicated workflows - this is already done for you via the Signmee engine. Simply add, send and monitor as forms are actioned and stored. \n\nSimplify the sign-off for a faster response."

  },

  { nid: 'spotlight-reporting', name: 'Spotlight Reporting', stack: 'cloud', active: true,

    categories: ["Accounting", "Operations Management"],

    key_benefits: [{"text"=>"Get a clearer picture of your business", "icon"=>""}, {"text"=>"Make more informed decisions based on our amazing reports", "icon"=>""}, {"text"=>"Uncover insights to improve business operations", "icon"=>""}],

    key_features: [{"text"=>"Comprehensive management reports", "icon"=>""}, {"text"=>"Consolidate up to 20 organisations", "icon"=>""}, {"text"=>"Analyze financials and Non-Financial KPIs", "icon"=>""}],

    tiny_description: "Business intelligence at your fingertips.", description: "If you are a business owner needing better insight or an accountant reporting to the Board or management team, our tool gives you a clearer picture of your business. Report your financial performance, position, cash and write up an executive summary to discuss highlights and recommendations. Choose from our templates or customize your own.\n\nSpotlight Reporting also has a range of KPIs and non-financial metrics in-built with the ability to customize KPIs that are most relevant to your organization. Create focus and debate with clever KPIs.\n\nDownload a sample [report](https://s3-ap-southeast-1.amazonaws.com/cdn-prd-maestrano/docs/public/website/Spotlight-Reporting-sample-report-WorldDom.pdf) you can create in minutes with Spotlight Reporting."

  },

  { nid: 'connector-salesforce', name: 'SalesForce', stack: 'cloud', active: true,

    categories: ["Customer Management", "Collaboration"],

    website: "http://www.salesforce.com",

    metadata: {"sso"=>{"init_path"=>"/", "idm"=>"http://localhost:3001"}},

    tiny_description: "Track and organize your business sales"

  },

  { nid: 'demo', name: 'Demo App', stack: 'cloud', active: true,

    categories: ["Operations Management"],

    tiny_description: "Demo Application", description: "Use it for demo purpose."

  },

].each do |app|

  CreateApps.create_app(app)

end




categories = ["Customer Management", "Collaboration", "Most Popular", "Business Intelligence and Analytics",

 "Internet and Online", "Operations Management", "Accounting and Finance", "Human Resources and Employee Management",

 "Education and Training", "Productivity"]




descr = ['Use these tools to truly understand more about your customers, pick up trends, identify opportunities and start making your customer database work for you!',

  "Let your team work smarter and more efficiently with these tools designed to increase collaboration",

  "",

  'Put your data to use, and gain deeper insights to make better decisions for your business',

  "Build and grow your business online with these tools, whether it's making a website, selling online, sending surveys or anything in between!",

  "All the tools you need to manage your entire operations, whether it's email, inventory or even document processing!",

  "Get your numbers in line with the best accounting tools, and don't just stop there - turn those cents into dollars with the right financial tools.",

  "Don't just take care of your people, but grow them with your company with these amazing tools",

  "Whether you're a training or educational institute or just looking for tools to help manage training within your organization - these are the tools to help you!",

  "Increase your productivity with these proven applications to create, stock and share documents, manage approval and get contracts approved."

  ]

  

i=0

categories.each do |c|

  AppCategory.create(name: c, description: descr[i])

  i = i+1

end




#Customer Management

subcategories = ["Customer Relationship Management (CRM)", "Customer Support", "Form and Survey Builder"]

c = AppCategory.find_by_name("Customer Management")

subcategories.each do |sc|

  c.app_subcategories.create(name: sc)

end




#Collaboration

subcategories = ["Project Management", "IT Management", "Document Management System", "Enterprise Social Networking"]

c = AppCategory.find_by_name("Collaboration")

subcategories.each do |sc|

  c.app_subcategories.create(name: sc)

end




#Internet and Online

subcategories = ["CMS / Website Builder", "Form and Survey Builder", "Online Marketing", "eCommerce"]

c = AppCategory.find_by_name("Internet and Online")

subcategories.each do |sc|

  c.app_subcategories.create(name: sc)

end




# Operations Management

subcategories = ["Virtual Office", "Business Process Management (BPM)", "Inventory Management", "ERP", "Event Management"]

c = AppCategory.find_by_name("Operations Management")

subcategories.each do |sc|

  c.app_subcategories.create(name: sc)

end




# Accounting and Finance

subcategories = ["Accounting", "Invoicing", "Payroll", "Reporting", "Expense Management"]

c = AppCategory.find_by_name("Accounting and Finance")

subcategories.each do |sc|

  c.app_subcategories.create(name: sc)

end




# Human Resources and Employee Management

subcategories = ["Human Resources Information System (HRIS)", "Recruitment", "Payroll", "Timesheets and Rostering"] 

c = AppCategory.find_by_name("Human Resources and Employee Management")

subcategories.each do |sc|

  c.app_subcategories.create(name: sc)

end




# Education and Training

subcategories = ["Learning Management System"]

c = AppCategory.find_by_name("Education and Training")

subcategories.each do |sc|

  c.app_subcategories.create(name: sc)

end




#======================================================================

# Create default tenant

#

# Environment variables configuration:

# - default_tenant_name

# - default_tenant_id

# - default_tenant_key

# - default_tenant_scheme

# - default_tenant_host

# - tenant_deny_old_passwords

# - tenant_password_archiving_count

#======================================================================

if ENV['default_tenant_id'] && ENV['default_tenant_key']

  metadata = HashWithIndifferentAccess.new({

    host: "#{ENV['default_tenant_scheme']||'http'}://#{ENV['default_tenant_host'] || 'example.com'}",

    deny_old_passwords: ENV['tenant_deny_old_passwords'] || false,

    password_archiving_count: ENV['tenant_password_archiving_count'] || 0

  })




  t = Mnoe::Tenant.create(

    name: ENV['default_tenant_name'] || "Default Tenant",

    domain: ENV['default_tenant_host'] || "example.com",

    api_key: ENV['default_tenant_id'],

    api_secret: ENV['default_tenant_key'],

    email: "it@maestrano.com",

    address: "Undisclosed",

    country: "AU",

    bank_account: nil,

    commission: { name: "Percentage", options: { percentage: 0.4, currency: 'AUD' } },

    metadata: metadata

  )

end




#======================================================================

# Create Delayed Jobs

#======================================================================

Delayed::Job.enqueue OAuthTokenRenewalJob.new

# TODO: Check which jobs to activate per tenant

# Delayed::Job.enqueue RecurringBillsExecutionJob.new

# current_time = Time.now.utc

# run_at = Time.utc(current_time.year, current_time.month,17)

# Delayed::Job.enqueue PartnerInvoicingJob.new, :run_at => run_at




#======================================================================

# Development environment: create default tenants, organizations and users

#======================================================================

if Rails.env.development?

  username = `git config --get user.name`

  email = `git config --get user.email`




  # Create tenants

  mno = Mnoe::Tenant.find_by_name('Maestrano') || Mnoe::Tenant.create!(name: "Maestrano", domain: 'maestrano.com', country: 'Australia', address: {'street'=>'234234'}, email: email, bank_account: {'name'=>'Account', 'type'=>'AU', 'bsb'=>'23422', 'account' => '345345345'}, commission: {'rate'=>40})



  # Maestrano organizations and users

  my_org = CreateApps.create_organization("#{username} Company", mno)

  my_other_org = CreateApps.create_organization("#{username} Side Business", mno)

  me = CreateApps.create_user(email, username, username, 'Super Admin', my_org, true)

  CreateApps.create_user('member@maestrano.com', 'Member', 'Member', 'Member', my_org, false)

  CreateApps.create_user('poweruser@maestrano.com', 'Power User', 'Power User', 'Power User', my_org, false)

  CreateApps.create_user('admin@maestrano.com', 'Admin', 'Admin', 'Admin', my_org, false)

  OrgaRelation.create(user: me, organization: my_other_org, role: 'Super Admin')




  # App instances

  App.where(stack: 'cube').each do |app|

    CreateApps.create_app_instance me, app, my_org

  end




  App.where(stack: 'connector').each do |app|

    CreateApps.create_connector_app me, app, my_org

  end




  App.where(stack: 'cloud').each do |app|

    CreateApps.create_cloud_app me, app, my_org

  end

end




https://www.vtiger.com/vtiger-public-license/