Synced to master; moved section about troubleshooting Docker in Windows to docker/README.md

This commit is contained in:
Jason Hsu
2020-10-08 14:06:54 -05:00
30 changed files with 863 additions and 593 deletions

View File

@@ -20,6 +20,9 @@ plugins:
enabled: false
DeclarationOrder:
enabled: false
NestingDepth:
enabled: false
duplication:
enabled: true
exclude_patterns:

3
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,3 @@
# Code of Conduct of the Open Food Network
**Welcome!** We are currently working on a Code of Conduct. You are welcome to contribute. We started this work at the Global Gathering 2020 and you find [notes of the initial session](https://community.openfoodnetwork.org/t/global-gathering-2020-day-5-a-code-of-conduct-for-ofn/2071/1) in the community forum. You can edit this file on Github to suggest new content. Alternatively, you can post in our [community forum](https://community.openfoodnetwork.org) or reach us on [Slack](https://openfoodnetwork.org/slack-invite).

View File

@@ -40,7 +40,7 @@ Push your changes to a branch on your fork:
## Submitting a Pull Request
Use the GitHub UI to submit a [new pull request][pr] against upstream/master. To increase the chances that your pull request is swiftly accepted please have a look at our guide to [making a great pull request][great-pr].
Use the GitHub UI to submit a [new pull request][pr] against upstream/master. To increase the chances that your pull request is swiftly accepted please have a look at our guide to [making a great pull request][great-pr].
TL;DR:
* Write tests

65
DOCKER.md Normal file
View File

@@ -0,0 +1,65 @@
### Docker
It is possible to setup the Open Food Network app easily with Docker and Docker Compose.
The objective is to spare configuration time, in order to help people testing the app and contribute to it.
It can also be used as documentation. It is not perfect but it is used in many other projects and many devs are used to it nowadays.
### Install Docker
Please check the documentation here, https://docs.docker.com/install/ to install Docker.
For Docker Compose, information are here: https://docs.docker.com/compose/install/.
Better to have at least 2GB free on your computer in order to download images and create containers for Open Food Network app.
### Use Docker with Open Food Network
Open a terminal with a shell.
Clone the repository. If you're planning on contributing code to the project (which we [LOVE](CONTRIBUTING.md)), it is a good idea to begin by forking this repo using the Fork button in the top-right corner of this screen. You should then be able to use git clone to copy your fork onto your local machine.
```sh
$ git clone https://github.com/YOUR_GITHUB_USERNAME_HERE/openfoodnetwork
```
Otherwise, if you just want to get things running, clone from the OFN main repo:
```sh
$ git clone git@github.com:openfoodfoundation/openfoodnetwork.git
```
Go at the root of the app:
```sh
$ cd openfoodnetwork
```
Download the Docker images and build the containers:
```sh
$ docker-compose build
```
Setup the database and seed it with sample data:
```sh
$ docker-compose run web bundle exec rake db:reset
$ docker-compose run web bundle exec rake db:test:prepare
$ docker-compose run web bundle exec rake ofn:sample_data
```
Finally, run the app with all the required containers:
```sh
$ docker-compose up
```
The default admin user is 'ofn@example.com' with 'ofn123' password.
Check the app in the browser at `http://localhost:3000`.
You will then get the trace of the containers in the terminal. You can stop the containers using Ctrl-C in the terminal.
You can find some useful tips and commands [here](https://github.com/openfoodfoundation/openfoodnetwork/wiki/Docker:-useful-tips-and-commands).
### Troubleshooting
If you are using Windows and having issues related to the ruby-build not finding a definition for the ruby version, you may need to follow these commands [here](https://stackoverflow.com/questions/2517190/how-do-i-force-git-to-use-lf-instead-of-crlf-under-windows/33424884#33424884) to fix your local git config related to line breaks.

View File

@@ -205,7 +205,7 @@ GEM
activerecord (>= 3.2.0, < 5.0)
fog (~> 1.0)
rails (>= 3.2.0, < 5.0)
ddtrace (0.40.0)
ddtrace (0.41.0)
msgpack
debugger-linecache (1.2.0)
delayed_job (4.1.8)
@@ -412,7 +412,7 @@ GEM
get_process_mem (0.2.5)
ffi (~> 1.0)
gmaps4rails (2.1.2)
haml (5.1.2)
haml (5.2.0)
temple (>= 0.8.0)
tilt
hashdiff (1.0.1)
@@ -445,7 +445,7 @@ GEM
actionpack (>= 3.0.0)
activesupport (>= 3.0.0)
kgio (2.11.3)
knapsack (1.18.0)
knapsack (1.19.0)
rake
launchy (2.4.3)
addressable (~> 2.3)

View File

@@ -68,7 +68,7 @@ Darkswarm.controller "ProductsCtrl", ($scope, $sce, $filter, $rootScope, Product
id: $scope.order_cycle.order_cycle_id,
page: page || $scope.page,
per_page: $scope.per_page,
'q[name_or_meta_keywords_or_supplier_name_cont]': $scope.query,
'q[name_or_meta_keywords_or_variants_display_as_or_variants_display_name_or_supplier_name_cont]': $scope.query,
'q[properties_id_or_supplier_properties_id_in_any][]': $scope.activeProperties,
'q[primary_taxon_id_in_any][]': $scope.activeTaxons
}

View File

@@ -1,3 +1,5 @@
@import 'shared/variables/layout';
// -------------------------------------------------------------
// Variables used in all other files
//--------------------------------------------------------------

View File

@@ -8,23 +8,61 @@
box-sizing: border-box;
}
// Helpers
.block-table {
display: table;
width: 100%;
.admin {
&__section-header {
padding: 15px 0;
background-color: very-light($color-3, 4);
border-bottom: 1px solid $color-border;
.table-cell {
display: table-cell;
vertical-align: middle;
padding: 0 10px;
&:first-child {
padding-left: 0;
width: 70%;
.ofn-drop-down {
border: 0;
background-color: $spree-blue;
color: $color-1;
float: none;
margin-left: 3px;
&:hover,
&.expanded {
border: 0;
color: $color-1;
}
}
&:last-child {
padding-right: 0;
width: 30%;
&__content {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
@media all and (min-width: $tablet_breakpoint) {
flex-wrap: nowrap;
}
}
&__title {
width: 100%;
margin-bottom: 10px;
@media all and (min-width: $tablet_breakpoint) {
margin-bottom: 0;
}
}
&__actions {
display: flex;
flex: 1 0 auto;
align-items: center;
list-style: none;
@media all and (min-width: $tablet_breakpoint) {
justify-content: flex-end;
}
> li {
display: flex;
margin-right: 10px;
&:empty {
display: none;
}
&:last-child {
margin-right: 0;
}
}
}
}
}
@@ -66,25 +104,6 @@
margin-top: 15px;
}
#content-header {
padding: 15px 0;
background-color: very-light($color-3, 4);
border-bottom: 1px solid $color-border;
.page-title {
font-size: 20px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.page-actions {
text-align: right;
form {
display: inline-block;
}
}
}
// Footer
//---------------------------------------------------
#footer {

View File

@@ -1,4 +1,5 @@
// Note this mixin file is used in ADMIN and FRONTEND
@import 'shared/variables/layout';
@import "branding";
@@ -258,15 +259,15 @@
@mixin breakpoint($point) {
@if $point == desktop {
@media all and (max-width: 1024px) { @content; }
@media all and (max-width: $desktop_breakpoint) { @content; }
}
@else if $point == tablet {
@media all and (max-width: 768px) { @content; }
@media all and (max-width: $tablet_breakpoint) { @content; }
}
@else if $point == phablet {
@media all and (max-width: 640px) { @content; }
@media all and (max-width: $phablet_breakpoint) { @content; }
}
@else if $point == mobile {
@media all and (max-width: 480px) { @content; }
@media all and (max-width: $mobile_breakpoint) { @content; }
}
}

View File

@@ -34,7 +34,7 @@
>a {
outline: none;
display: block;
color: $grey-500;
color: $black;
font-family: "Oswald", sans-serif;
}
@@ -42,9 +42,9 @@
@include headingFont;
background: transparent;
text-transform: uppercase;
text-transform: capitalize;
line-height: 1;
font-size: 0.875em;
font-size: 1em;
padding: 1em 2em;
border: none;
@@ -58,6 +58,7 @@
@include breakpoint(phablet) {
padding: 0.35em 0 0.65em 0;
font-size: 0.875em;
}
}

View File

@@ -0,0 +1,6 @@
// Breakpoints
$desktop_breakpoint: 1024px;
$tablet_breakpoint: 768px;
$phablet_breakpoint: 640px;
$mobile_breakpoint: 480px;

View File

@@ -75,7 +75,7 @@ module Api
end
def permitted_ransack_params
[:name_or_meta_keywords_or_supplier_name_cont,
[:name_or_meta_keywords_or_variants_display_as_or_variants_display_name_or_supplier_name_cont,
:properties_id_or_supplier_properties_id_in_any,
:primary_taxon_id_in_any]
end

View File

@@ -3,9 +3,6 @@ module Spree
class TaxRatesController < ResourceController
before_action :load_data
update.after :update_after
create.after :create_after
private
def load_data
@@ -14,14 +11,6 @@ module Spree
@calculators = TaxRate.calculators.sort_by(&:name)
end
def update_after
Rails.cache.delete('vat_rates')
end
def create_after
Rails.cache.delete('vat_rates')
end
def permitted_resource_params
params.require(:tax_rate).permit(
:name, :amount, :included_in_price, :zone_id,

View File

@@ -253,7 +253,7 @@ module ProductImport
products.flat_map(&:variants).each do |existing_variant|
unit_scale = existing_variant.product.variant_unit_scale
unscaled_units = entry.unscaled_units || 0
unscaled_units = entry.unscaled_units.to_f || 0
entry.unit_value = unscaled_units * unit_scale unless unit_scale.nil?
if entry_matches_existing_variant?(entry, existing_variant)

View File

@@ -1,5 +1,5 @@
%h1
=t'new_order_cycle'
- content_for :page_title do
=t('new_order_cycle')
- ng_controller = order_cycles_simple_form ? 'AdminSimpleCreateOrderCycleCtrl' : 'AdminCreateOrderCycleCtrl'
= admin_inject_order_cycle_instance

View File

@@ -78,6 +78,7 @@
= f.label :product_description, t(".product_description")
%br/
%text-angular{'id' => 'product_description', 'name' => 'product[description]', 'class' => 'text-angular', "textangular-links-target-blank" => true, 'ta-toolbar' => "[['bold','italics','underline','clear'],['insertLink']]"}
= sanitize(@product.description)
= f.error_message_on :description
.four.columns.omega{ style: "text-align: center" }
%fieldset.no-border-bottom{ id: "image" }

View File

@@ -9,4 +9,4 @@ $("#admin_new_product").parent().hide();
<%# We need to replace the page's title as well. We're navigating to a new page
although through ajax %>
$('#content-header .page-title').html('<%= t('.title') %>');
$('.js-admin-page-title').html('<%= t('.title') %>');

View File

@@ -1,7 +1,7 @@
= admin_inject_currency_config
= render "layouts/i18n_script"
#wrapper{"data-hook" => ""}
#wrapper{ data: { hook: '' } }
- if flash[:error]
.flash.error= flash[:error]
- if notice
@@ -18,30 +18,30 @@
%nav.columns.eleven{"data-hook" => "admin_login_navigation_bar"}
= render :partial => 'spree/layouts/admin/login_nav'
%nav#admin-menu{"data-hook" => ""}
%nav#admin-menu{ data: { hook: '' }}
.container
.sixteen.columns.main-menu-wrapper
%ul.inline-menu.fullwidth-menu{"data-hook" => "admin_tabs"}
= render :partial => 'spree/admin/shared/tabs'
- if content_for?(:sub_menu)
%nav#sub-menu{"data-hook" => ""}
%nav#sub-menu{ data: { hook: ''} }
.container
.sixteen.columns
= yield :sub_menu
- if content_for?(:page_title) || content_for?(:page_actions)
#content-header{"data-hook" => ""}
.js-admin-section-header.admin__section-header{ data: { hook: '' } }
.container
.sixteen.columns
.block-table
.admin__section-header__content
- if content_for?(:page_title)
.table-cell
%h1{:class => "page-title"}= yield :page_title
.admin__section-header__title
%h1.js-admin-page-title= yield :page_title
- if content_for?(:page_actions)
.page-actions.table-cell.toolbar{"data-hook" => "toolbar"}
%ul.inline-menu
= yield :page_actions
%ul.admin__section-header__actions{ data: { hook: 'toolbar' } }
= yield :page_actions
.container
.row

View File

@@ -131,8 +131,8 @@ ar:
subject: "%{enterprise} الآن على %{sitename}"
email_welcome: "أهلا بك"
email_registered: "الآن هو جزء من"
email_userguide_html: "دليل المستخدم مع دعم مفصل لإعداد المنتج أو المحور الخاص بك هنا: %{link}"
userguide: "افتح دليل مستخدم شبكة الغذاء"
email_userguide_html: "دليل المستخدم مع دعم مفصل لإعداد واجهة المنتج أو مركز البيع الخاص بك هنا: %{link}"
userguide: "افتح دليل مستخدم شبكة الغذاء المفتوح الاردن - فلاحة جو"
email_admin_html: "يمكنك إدارة حسابك عن طريق تسجيل الدخول إلى %{link} أو عن طريق النقر على cog في أعلى الجانب الأيمن من الصفحة الرئيسية ، واختيار الإدارة."
admin_panel: "لوحة الادارة"
email_community_html: "لدينا أيضًا منتدى عبر الإنترنت لمناقشات المجتمع المتعلقة ببرامج بشبكة الغذاء المفتوح والتحديات الفريدة لإدارة مؤسسة للأغذية. نحن نشجعك على الانضمام. نحن نتطور باستمرار وسوف تشكل مدخلاتك في هذا المنتدى ما سيحدث بعد ذلك. %{link}"
@@ -851,7 +851,7 @@ ar:
title: شركة جديدة
back_link: العودة إلى قائمة المؤسسات
welcome:
welcome_title: مرحبا بكم في شبكة الغذاء المفتوح!
welcome_title: مرحبا بكم في شبكة الغذاء المفتوح الاردن - فلاحة جو !
welcome_text: لقد نجحت في إنشاء
next_step: الخطوة التالية
choose_starting_point: 'اختر الحزمة الخاصة بك:'
@@ -1181,7 +1181,7 @@ ar:
mobile_menu:
cart: "سلة"
register_call:
selling_on_ofn: "هل أنت مهتم بالحصول على شبكة الغذاء المفتوح؟"
selling_on_ofn: "هل أنت مهتم بالبيع من خلال منصة فلاحة جو؟ "
register: "سجل هنا"
footer:
footer_secure: "آمن وموثوق به."
@@ -2654,7 +2654,7 @@ ar:
users:
order: "طلب"
registration:
welcome_to_ofn: "مرحبا بكم في شبكة الغذاء المفتوح!"
welcome_to_ofn: "مرحبا بكم في شبكة الغذاء المفتوح الاردن - فلاحة جو!"
signup_or_login: "البدء بالتسجيل (أو تسجيل الدخول)"
have_an_account: "هل لديك حساب؟"
action_login: "تسجيل الدخول الآن."

View File

@@ -121,6 +121,7 @@ en_NZ:
not_array_error: "must be an array"
invalid_element_error: "must contain only valid integers"
datetime_picker_ui:
current_text: Now
close_text: Done
time_text: Time
enterprise_mailer:
@@ -600,6 +601,7 @@ en_NZ:
order_date: "Completed at"
max: "Max"
product_unit: "Product: Unit"
weight_volume: "Weight/Volume (g)"
ask: "Ask?"
page_title: "Bulk Order Management"
actions_delete: "Delete Selected"
@@ -636,6 +638,8 @@ en_NZ:
acn_placeholder: eg. 123 456 789
display_invoice_logo: Display logo in invoices
invoice_text: Add customized text at the end of invoices
terms_and_conditions: "Terms and Conditions"
remove_terms_and_conditions: "Remove File"
contact:
name: Name
name_placeholder: eg. Gustav Plum
@@ -1144,12 +1148,17 @@ en_NZ:
destroy_attachment_does_not_exist: "Logo does not exist"
enterprise_promo_image:
destroy_attachment_does_not_exist: "Promo image does not exist"
enterprise_terms_and_conditions:
destroy_attachment_does_not_exist: "Terms and Conditions file does not exist"
orders:
failed_to_update: "Failed to update order"
checkout:
already_ordered:
cart: "cart"
message_html: "You have an order for this order cycle already. Check the %{cart} to see the items you ordered before. You can also cancel items as long as the order cycle is open."
terms_and_conditions:
message_html: "By placing this order you agree to the %{terms_and_conditions_link}."
link_text: "Terms of Service"
failed: "The checkout failed. Please let us know so that we can process your order."
shops:
hubs:
@@ -2295,6 +2304,7 @@ en_NZ:
enterprise_name_error: "has already been taken. If this is your enterprise and you would like to claim ownership, or if you would like to trade with this enterprise please contact the current manager of this profile at %{email}."
enterprise_owner_error: "^%{email} is not permitted to own any more enterprises (limit is %{enterprise_limit})."
enterprise_role_uniqueness_error: "^That role is already present."
enterprise_terms_and_conditions_type_error: "Only PDFs are allowed"
inventory_item_visibility_error: must be true or false
product_importer_file_error: "error: no file uploaded"
product_importer_spreadsheet_error: "could not process file: invalid filetype"
@@ -2573,6 +2583,8 @@ en_NZ:
immediate_logo_removal_warning: "The logo will be removed immediately after you confirm."
removed_promo_image_successfully: "Promo image removed successfully"
immediate_promo_image_removal_warning: "The promo image will be removed immediately after you confirm."
immediate_terms_and_conditions_removal_warning: "The Terms and Conditions file will be removed immediately after you confirm."
removed_terms_and_conditions_successfully: "Terms and Conditions file removed successfully"
insufficient_stock: "Insufficient stock available, only %{on_hand} remaining"
out_of_stock:
reduced_stock_available: Reduced stock available
@@ -2646,6 +2658,11 @@ en_NZ:
signup_or_login: "Start By Signing Up (or logging in)"
have_an_account: "Already have an account?"
action_login: "Log in now."
stripe_elements:
unknown_error_from_stripe: |
There was a problem setting up your card in our payments gateway.
Please refresh the page and try again, if it fails a second time,
please contact us for support.
inflections:
each:
one: "each"

File diff suppressed because it is too large Load Diff

View File

@@ -19,8 +19,8 @@ ru:
primary_taxon: "Категория Продукта"
supplier: "Поставщик"
shipping_category_id: "Категория Доставки"
variant_unit: "Variant Unit"
variant_unit_name: "Variant Unit Name"
variant_unit: "Единица Варианта"
variant_unit_name: "Название Единицы Варианта"
spree/credit_card:
base: "Кредитная Карта"
order_cycle:
@@ -205,7 +205,7 @@ ru:
cancel_order: "Отменить Заказ"
confirm_send_invoice: "Счет на этот заказ будет отправлен клиенту. Вы уверены что хотите продолжить?"
confirm_resend_order_confirmation: "Вы уверены, что хотите повторно отправить письмо с подтверждением заказа?"
must_have_valid_business_number: " %{enterprise_name} должен быть указан Tax ID or W9 перед отправкой счетов."
must_have_valid_business_number: " %{enterprise_name} должен быть указан ИНН перед отправкой счетов."
invoice: "Счёт"
more: "Ещё"
say_no: "Нет"
@@ -364,11 +364,11 @@ ru:
stripe_connect_settings:
edit:
title: "Stripe Connect"
settings: "Settings"
settings: "Настройки"
stripe_connect_enabled: Enable shops to accept payments using Stripe Connect?
no_api_key_msg: No Stripe account exists for this enterprise.
configuration_explanation_html: For detailed instructions on configuring the Stripe Connect integration, please <a href='https://github.com/openfoodfoundation/openfoodnetwork/wiki/Setting-up-Stripe-on-an-OFN-instance' target='_blank'>consult this guide</a>.
status: Status
status: Статус
ok: Ok
instance_secret_key: Instance Secret Key
account_id: Account ID
@@ -383,8 +383,8 @@ ru:
matomo_url: "Matomo URL"
matomo_site_id: "Matomo Site ID"
matomo_tag_manager_url: "URL Диспетчера Тегов Matomo"
info_html: "Matomo is a Web and Mobile Analytics. You can either host Matomo locally or use a cloud-hosted service. See <a href='http://matomo.org' target='_blank'>matomo.org</a> for more information."
config_instructions_html: "Here you can configure the OFN Matomo integration. The Matomo URL below should point to the Matomo instance where the user tracking information will be sent to; if it is left empty, Matomo user trackingwill be disabled. The Site ID field is not mandatory but useful if you are tracking more than one website on a single Matomo instance; it can be found on the Matomo instance console."
info_html: "Matomo - это приложение для Веб и Мобильной аналитики. Вы можете разместить Matomo локально или использовать облачную службу. См. <a href='http://matomo.org' target='_blank'>Matomo.org</a> для получения дополнительной информации."
config_instructions_html: "Здесь вы можете настроить интеграцию ОСП Matomo. Приведенный ниже URL-адрес Matomo должен указывать на экземпляр Matomo, на который будет отправляться отслеживающая информация пользователя; если оставить его пустым, отслеживание пользователей Matomo будет отключено. Поле Site ID не является обязательным, но полезно, если вы отслеживаете более одного веб-сайта на одном экземпляре Matomo; его можно найти на консоли экземпляра Matomo."
config_instructions_tag_manager_html: "Установка URL-адреса Диспетчера Тегов Matomo включает Диспетчер Тегов Matomo. Этот инструмент позволяет настраивать события аналитики. URL-адрес Диспетчера Тегов Matomo скопирован из раздела &quot;Код установки&quot; Диспетчера Тегов Matomo. Убедитесь, что вы выбрали правильный контейнер и среду, поскольку эти параметры изменяют URL-адрес."
customers:
index:
@@ -602,7 +602,7 @@ ru:
order_date: "Завершен в"
max: "Максимум"
product_unit: "Товар: Единица измерения"
weight_volume: "Вес/Объем"
weight_volume: "Вес/Объем (г)"
ask: "Спросить?"
page_title: "Пакетное Управление Заказами"
actions_delete: "Удалить Выбранное"
@@ -815,7 +815,7 @@ ru:
producer: Производитель
change_type_form:
producer_profile: Профиль Производителя
connect_ofn: Connect through OFN
connect_ofn: Подключиться через ОСП
always_free: ВСЕГДА БЕСПЛАТНО
producer_description_text: Добавляйте свои продукты в Открытую Сеть Продуктов, позволяя продуктовым центрам размещать их в своих магазинах.
producer_shop: Магазин Производителя
@@ -996,17 +996,17 @@ ru:
email_confirmation: "Ожидается подтверждение по электронной почте. Мы отправили электронное письмо с подтверждением на %{email}."
not_visible: "%{enterprise} не виден и поэтому не может быть найден на карте или в поисках"
reports:
hidden: HIDDEN
unitsize: UNITSIZE
total: TOTAL
total_items: TOTAL ITEMS
supplier_totals: Order Cycle Supplier Totals
supplier_totals_by_distributor: Order Cycle Supplier Totals by Distributor
totals_by_supplier: Order Cycle Distributor Totals by Supplier
hidden: СКРЫТО
unitsize: РАЗМЕР ЕДИНИЦЫ
total: ВСЕГО
total_items: ИТОГО
supplier_totals: Итоговые данные Поставщика Цикла Заказа
supplier_totals_by_distributor: Итоговые данные Поставщика Цикла Заказа по Дистрибьюторам
totals_by_supplier: Итоговые данные Дистрибьютора за Цикл Заказов по Поставщикам
customer_totals: Итоги по Клиентам Цикла Заказа
all_products: Все товары
inventory: Товарная Номенклатура (в наличии)
lettuce_share: LettuceShare
lettuce_share: Доля Салата
mailing_list: Список Рассылки
addresses: Адреса
payment_methods: Отчет О Способах Оплаты
@@ -1019,7 +1019,7 @@ ru:
name: Заказы и Дистрибьюторы
description: Заказы с информацией о дистрибьюторе
bulk_coop:
name: Bulk Co-Op
name: Массовая Кооперация
description: Отчеты по оптовым заказам кооперативов
payments:
name: Отчеты об Оплате
@@ -1097,11 +1097,11 @@ ru:
invalid_error: Ой! Пожалуйста, заполните все обязательные поля...
allowed_payment_method_types_tip: Only Cash and Stripe payment methods may be used at the moment
credit_card: Кредитная Карта
charges_not_allowed: Charges are not allowed by this customer
no_default_card: Customer has no cards available to charge
card_ok: Customer has a card available to charge
begins_at_placeholder: "Select a Date"
ends_at_placeholder: "Optional"
charges_not_allowed: Этот клиент не разрешает взимать плату
no_default_card: У клиента нет доступных карт для оплаты
card_ok: У клиента есть карта для оплаты
begins_at_placeholder: "Выберите Дату"
ends_at_placeholder: "Необязательный"
loading_flash:
loading: ЗАГРУЗКА ПОДПИСОК
review:
@@ -1148,21 +1148,21 @@ ru:
resource: Stripe Connect configuration
api:
enterprise_logo:
destroy_attachment_does_not_exist: "Logo does not exist"
destroy_attachment_does_not_exist: "Логотип не существует"
enterprise_promo_image:
destroy_attachment_does_not_exist: "Promo image does not exist"
destroy_attachment_does_not_exist: "Промо-изображение не существует"
enterprise_terms_and_conditions:
destroy_attachment_does_not_exist: "Файл Условий и Положений не существует"
orders:
failed_to_update: "Failed to update order"
failed_to_update: "Не удалось обновить заказ"
checkout:
already_ordered:
cart: "корзина"
message_html: "You have an order for this order cycle already. Check the %{cart} to see the items you ordered before. You can also cancel items as long as the order cycle is open."
message_html: "У вас уже есть заказ для этого цикла заказов. Проверьте %{cart}, чтобы увидеть товары, которые вы заказали ранее. Вы также можете отменять позиции, пока открыт цикл заказа."
terms_and_conditions:
message_html: "Размещая этот заказ, вы соглашаетесь с %{terms_and_conditions_link}."
link_text: "Условия Сервиса"
failed: "The checkout failed. Please let us know so that we can process your order."
failed: "Оформить заказ не удалось. Сообщите нам, чтобы мы могли обработать ваш заказ."
shops:
hubs:
show_closed_shops: "Показать закрытые магазины"
@@ -1253,7 +1253,7 @@ ru:
menu_4_url: "/groups"
menu_5_title: "О нас"
menu_5_url: "https://about.openfoodnetwork.ru/"
menu_6_title: "Connect"
menu_6_title: "Подключить"
menu_6_url: "https://about.openfoodnetwork.ru/resources/"
menu_7_title: "Узнать"
menu_7_url: "https://about.openfoodnetwork.ru/resources/"
@@ -1307,7 +1307,7 @@ ru:
label_producers: "Производители"
label_groups: "Группы"
label_about: "О нас"
label_connect: "Connect"
label_connect: "Подключить"
label_learn: "Узнать"
label_blog: "Блог"
label_support: "Поддержка"
@@ -1316,7 +1316,7 @@ ru:
label_logout: "Выйти"
label_signup: "Зарегистрироваться"
label_administration: "Управление"
label_admin: "Admin"
label_admin: "Админ"
label_account: "Профиль"
label_more: "Показать больше"
label_less: "Показать меньше"
@@ -1398,7 +1398,7 @@ ru:
brandstory_part6: "Все мы любим еду. Теперь мы можем так же любить нашу продуктовую систему."
learn_body: "Изучите модели, истории и ресурсы, которые помогут вам развить свой бизнес или организацию по продаже продуктов питания. Найдите обучение, события и другие возможности учиться у соседей."
learn_cta: "Вдохновитесь"
connect_body: "Ищите наши каталоги производителей, центров и групп, чтобы найти честных продавцов продуктами питания рядом с Вами. Зарегистрируйте свой бизнес или организацию в OFN, чтобы покупатели могли найти Вас. Присоединяйтесь к сообществу, чтобы получать советы и решать проблемы вместе."
connect_body: "Ищите наши каталоги производителей, центров и групп, чтобы найти честных продавцов продуктами питания рядом с Вами. Зарегистрируйте свой бизнес или организацию в ОСП, чтобы покупатели могли найти Вас. Присоединяйтесь к сообществу, чтобы получать советы и решать проблемы вместе."
connect_cta: "Исследовать"
system_headline: "Покупки - как это работает."
system_step1: "1. Поиск"
@@ -1460,8 +1460,8 @@ ru:
unsaved_changes_warning: "Есть несохраненные изменения, которые будут потеряны, если вы продолжите."
unsaved_changes_error: "Поля с красными границами содержат ошибки."
products: "Товары"
products_in: "in %{oc}"
products_at: "at %{distributor}"
products_in: "в %{oc}"
products_at: "у %{distributor}"
products_elsewhere: "Товары, найденные в других местах"
email_confirmed: "Спасибо за подтверждение Вашего email адреса."
email_confirmation_activate_account: "Перед тем как сможем активировать Ваш профиль, мы должны подтвердить Ваш email адрес."
@@ -1596,7 +1596,7 @@ ru:
products_edit_cart: "Изменить Вашу корзину"
products_from: от
products_change: "Нет изменений для сохранения."
products_update_error: "Ошибка сохранения со следующей ошибкой:"
products_update_error: "Ошибка сохранения со следующей ошибкой(ми):"
products_update_error_msg: "Сохранение не удалось."
products_update_error_data: "Ошибка сохранения из-за неверных данных:"
products_changes_saved: "Изменения сохранены."
@@ -1703,7 +1703,7 @@ ru:
orders_edit_checkout: Оформить
orders_form_empty_cart: "Очистить корзину"
orders_form_subtotal: Итого
orders_form_admin: Администрирование & Управление
orders_form_admin: Администрирование и Управление
orders_form_total: Всего
orders_oc_expired_headline: Оформление Заказов для этого Цикла Заказа закрыто
orders_oc_expired_text: "Извините, оформление заказов для этого цикла заказов закрыты %{time} назад! Пожалуйста, свяжитесь с вашим центром напрямую, чтобы узнать, могут ли они принимать поздние заказы."
@@ -2139,19 +2139,19 @@ ru:
report_header_relationship: Relationship
report_header_hub: Центр
report_header_hub_address: Адрес Центра
report_header_to_hub: To Hub
report_header_hub_code: Hub Code
report_header_code: Code
report_header_paid: Paid?
report_header_delivery: Delivery?
report_header_to_hub: В Центр
report_header_hub_code: Код Центра
report_header_code: Код
report_header_paid: Оплачен?
report_header_delivery: Доставка?
report_header_shipping: Доставка
report_header_shipping_method: Способ Доставки
report_header_shipping_instructions: Инструкции по Доставке
report_header_ship_street: Ship Street
report_header_ship_street_2: Ship Street 2
report_header_ship_city: Ship City
report_header_ship_postcode: Ship Zip Code
report_header_ship_state: Ship State
report_header_ship_street: Улица Доставки
report_header_ship_street_2: Улица Доставки 2
report_header_ship_city: Город Доставки
report_header_ship_postcode: Индекс Доставки
report_header_ship_state: Область Доставки
report_header_billing_street: Billing Street
report_header_billing_street_2: Billing Street 2
report_header_billing_street_3: Billing Street 3
@@ -2159,20 +2159,20 @@ ru:
report_header_billing_city: Billing City
report_header_billing_postcode: Billing Zip code
report_header_billing_state: Billing State
report_header_incoming_transport: Incoming Transport
report_header_special_instructions: Special Instructions
report_header_incoming_transport: Входящий Транспорт
report_header_special_instructions: Специальные Инструкции
report_header_order_number: Номер заказа
report_header_date: Дата
report_header_confirmation_date: Confirmation Date
report_header_confirmation_date: Дата Подтверждения
report_header_tags: Метки
report_header_items: Items
report_header_items_total: "Items total %{currency_symbol}"
report_header_taxable_items_total: "Taxable Items Total (%{currency_symbol})"
report_header_sales_tax: "Sales Tax (%{currency_symbol})"
report_header_delivery_charge: "Delivery Charge (%{currency_symbol})"
report_header_tax_on_delivery: "Tax on Delivery (%{currency_symbol})"
report_header_tax_on_fees: "Tax on Fees (%{currency_symbol})"
report_header_total_tax: "Total Tax (%{currency_symbol})"
report_header_items: Товары
report_header_items_total: "Всего товаров %{currency_symbol}"
report_header_taxable_items_total: "Итого по статьям налогообложения (%{currency_symbol})"
report_header_sales_tax: "Налог с продаж (%{currency_symbol})"
report_header_delivery_charge: "Стоимость доставки (%{currency_symbol})"
report_header_tax_on_delivery: "Налог на доставку (%{currency_symbol})"
report_header_tax_on_fees: "Налог на сборы (%{currency_symbol})"
report_header_total_tax: "Общий налог (%{currency_symbol})"
report_header_enterprise: Предприятие
report_header_customer: Клиент
report_header_customer_code: Код Клиента
@@ -2181,87 +2181,87 @@ ru:
report_header_quantity: Количество
report_header_max_quantity: Max Количество
report_header_variant: Вариант
report_header_variant_value: Variant Value
report_header_variant_unit: Variant Unit
report_header_variant_value: Значение Варианта
report_header_variant_unit: Единица Варианта
report_header_total_available: Всего доступно
report_header_unallocated: Нераспределенный
report_header_max_quantity_excess: Max Количество Excess
report_header_taxons: Taxons
report_header_max_quantity_excess: Максимальное превышение количества
report_header_taxons: Таксоны
report_header_supplier: Поставщик
report_header_producer: Производитель
report_header_producer_suburb: Город Производителя
report_header_unit: Unit
report_header_unit: Единица измерения
report_header_group_buy_unit_quantity: Group Buy Unit Количество
report_header_cost: Cost
report_header_shipping_cost: Shipping Cost
report_header_curr_cost_per_unit: Curr. Cost per Unit
report_header_total_shipping_cost: Total Shipping Cost
report_header_payment_method: Payment Method
report_header_sells: Sells
report_header_visible: Visible
report_header_cost: Стоимость
report_header_shipping_cost: Стоимость доставки
report_header_curr_cost_per_unit: Текущ. Стоимость за единицу
report_header_total_shipping_cost: Общая стоимость доставки
report_header_payment_method: Способ оплаты
report_header_sells: Продает
report_header_visible: Видимый
report_header_price: Цена
report_header_unit_size: Unit Size
report_header_unit_size: Размер единицы
report_header_distributor: Дистрибьютор
report_header_distributor_address: Адрес Дистрибьютора
report_header_distributor_city: Город Дистрибьютора
report_header_distributor_postcode: Почтовый индекс Дистрибьютора
report_header_delivery_address: Адрес Доставки
report_header_delivery_postcode: Почтовый индекс Доставки
report_header_bulk_unit_size: Bulk Unit Size
report_header_weight: Weight
report_header_sum_total: Sum Total
report_header_date_of_order: Date of Order
report_header_amount_owing: Amount Owing
report_header_amount_paid: Amount Paid
report_header_units_required: Units Required
report_header_remainder: Remainder
report_header_order_date: Order date
report_header_order_id: Order Id
report_header_item_name: Item name
report_header_temp_controlled_items: Temp Controlled Items?
report_header_customer_name: Customer Name
report_header_customer_email: Customer Email
report_header_customer_phone: Customer Phone
report_header_customer_city: Customer City
report_header_bulk_unit_size: Размер оптовой единицы
report_header_weight: Вес
report_header_sum_total: Итого
report_header_date_of_order: Дата Заказа
report_header_amount_owing: Сумма Задолженности
report_header_amount_paid: Выплаченная Сумма
report_header_units_required: Необходимые Единицы
report_header_remainder: Остаток
report_header_order_date: Дата заказа
report_header_order_id: Номер заказа
report_header_item_name: Название товара
report_header_temp_controlled_items: Товары с контролем температуры?
report_header_customer_name: Имя Клиента
report_header_customer_email: Email Клиента
report_header_customer_phone: Телефон Клиента
report_header_customer_city: Город Заказчика
report_header_payment_state: Статус Платежа
report_header_payment_type: Payment Type
report_header_item_price: "Item (%{currency})"
report_header_item_fees_price: "Item + Fees (%{currency})"
report_header_admin_handling_fees: "Admin & Handling (%{currency})"
report_header_ship_price: "Ship (%{currency})"
report_header_pay_fee_price: "Pay fee (%{currency})"
report_header_total_price: "Total (%{currency})"
report_header_product_total_price: "Product Total (%{currency})"
report_header_shipping_total_price: "Shipping Total (%{currency})"
report_header_outstanding_balance_price: "Outstanding Balance (%{currency})"
report_header_payment_type: Способ Оплаты
report_header_item_price: "Товар (%{currency})"
report_header_item_fees_price: "Товар + Комиссии (%{currency})"
report_header_admin_handling_fees: "Администрирование и Обработка (%{currency})"
report_header_ship_price: "Доставка (%{currency})"
report_header_pay_fee_price: "Комиссия за оплату (%{currency})"
report_header_total_price: "Итого (%{currency})"
report_header_product_total_price: "Итого по Продукту (%{currency})"
report_header_shipping_total_price: "Итого за Доставку (%{currency})"
report_header_outstanding_balance_price: "Непогашенный Остаток (%{currency})"
report_header_eft_price: "EFT (%{currency})"
report_header_paypal_price: "PayPal (%{currency})"
report_header_sku: SKU
report_header_amount: К оплате
report_header_balance: Баланс
report_header_total_cost: "Total Cost"
report_header_total_ordered: Total Ordered
report_header_total_max: Total Max
report_header_total_units: Total Units
report_header_sum_max_total: "Sum Max Total"
report_header_total_excl_vat: "Total excl. tax (%{currency_symbol})"
report_header_total_incl_vat: "Total incl. tax (%{currency_symbol})"
report_header_total_cost: "Общая Стоимость"
report_header_total_ordered: Всего Заказано
report_header_total_max: Всего Макс
report_header_total_units: Всего Единиц
report_header_sum_max_total: "Сумма Макс Итого"
report_header_total_excl_vat: "Итого искл. налог (%{currency_symbol})"
report_header_total_incl_vat: "Итого, вкл. налог (%{currency_symbol})"
report_header_temp_controlled: Контроль Температуры?
report_header_is_producer: Производитель?
report_header_not_confirmed: Not Confirmed
report_header_gst_on_income: Tax on Income
report_header_not_confirmed: Не Подтверждено
report_header_gst_on_income: Налог на доход
report_header_gst_free_income: Tax Free Income
report_header_total_untaxable_produce: Total untaxable produce (no tax)
report_header_total_taxable_produce: Total taxable produce (tax inclusive)
report_header_total_untaxable_fees: Total untaxable fees (no tax)
report_header_total_taxable_fees: Total taxable fees (tax inclusive)
report_header_delivery_shipping_cost: Delivery Shipping Cost (tax inclusive)
report_header_transaction_fee: Transaction Fee (no tax)
report_header_total_untaxable_admin: Total untaxable admin adjustments (no tax)
report_header_total_taxable_admin: Total taxable admin adjustments (tax inclusive)
report_header_total_untaxable_produce: Общая не облагаемая налогом продукция (без налога)
report_header_total_taxable_produce: Общая налогооблагаемая продукция (включая налоги)
report_header_total_untaxable_fees: Всего необлагаемых налогом сборов (без налогов)
report_header_total_taxable_fees: Всего налогооблагаемых сборов (включая налоги)
report_header_delivery_shipping_cost: Стоимость Доставки (включая налоги)
report_header_transaction_fee: Комиссия за Операцию (без налога)
report_header_total_untaxable_admin: Всего необлагаемых налогом административных корректировок (без налогов)
report_header_total_taxable_admin: Всего налогооблагаемых административных корректировок (включая налоги)
initial_invoice_number: "Начальный номер счета:"
invoice_date: "Счёт date:"
due_date: "Счёт date:"
invoice_date: "Дата Счёта:"
due_date: "Срок Выполнения:"
account_code: "Код счета:"
equals: "Равно"
contains: "содержит"
@@ -2505,13 +2505,13 @@ ru:
loading_variants: "Загрузка Вариантов"
tag_rules:
shipping_method_tagged_top: "Способы доставки помечены"
shipping_method_tagged_bottom: "are:"
shipping_method_tagged_bottom: "являются:"
payment_method_tagged_top: "Способы оплаты помечены"
payment_method_tagged_bottom: "are:"
payment_method_tagged_bottom: "являются:"
order_cycle_tagged_top: "Циклы заказа помечены"
order_cycle_tagged_bottom: "are:"
order_cycle_tagged_bottom: "являются:"
inventory_tagged_top: "Помечены варианты Товарной Номенклатуры"
inventory_tagged_bottom: "are:"
inventory_tagged_bottom: "являются:"
new_tag_rule_dialog:
select_rule_type: "Выберите тип правила:"
add_rule: "Добавить Правило"
@@ -3111,9 +3111,9 @@ ru:
return_authorizations:
index:
new_return_authorization: "Новое разрешение на возврат"
return_authorizations: "Разрешения на возврат (RMA)"
return_authorizations: "Разрешения на возврат"
back_to_orders_list: "Назад К Списку Заказов"
rma_number: "Номер RMA"
rma_number: "Номер возврата"
status: "Статус"
amount: "Сумма"
cannot_create_returns: "Невозможно оформить возврат. Заказ ещё не отправлен."
@@ -3132,7 +3132,7 @@ ru:
quantity_returned: "Количество возврата"
return_quantity: "возвращенное количество"
amount: "Количество"
rma_value: "Сумма RMA"
rma_value: "Сумма возврата"
reason: "Причина"
stock_location: "Расположение склада"
states:
@@ -3143,7 +3143,7 @@ ru:
index:
listing_orders: "Список Заказов"
new_order: "Новый Заказ"
capture: "Capture"
capture: "Записать"
ship: "Доставка"
edit: "Изменить"
order_not_updated: "Заказ не может быть обновлен"
@@ -3327,10 +3327,10 @@ ru:
table:
select_and_search: "Для получения данных, выберите фильры и нажмите на %{option}."
bulk_coop:
bulk_coop_supplier_report: 'Bulk Co-op - Totals by Supplier'
bulk_coop_allocation: 'Bulk Co-op - Allocation'
bulk_coop_packing_sheets: 'Bulk Co-op - Packing Sheets'
bulk_coop_customer_payments: 'Bulk Co-op - Customer Payments'
bulk_coop_supplier_report: 'Массовая Кооперация - Итоги по Поставщикам'
bulk_coop_allocation: 'Массовая Кооперация - Размещение'
bulk_coop_packing_sheets: 'Массовая Кооперация - Упаковочные листы'
bulk_coop_customer_payments: 'Массовая Кооперация - Клиентские Платежи'
customer_names_message:
customer_names_tip: "Если имена клиентов скрыты для заказов, которые вы предоставили, вы можете связаться с дистрибьютором и спросить, могут ли они обновить настройки своего магазина, чтобы их поставщики могли просматривать имена клиентов."
users:
@@ -3444,7 +3444,7 @@ ru:
order_mailer:
cancel_email:
customer_greeting: "Уважаемый %{name}!"
instructions_html: "Ваш заказ был ОТМЕНЕН. Пожалуйста, сохраните эту информацию об отмене для ваших записей."
instructions_html: "Ваш заказ на <strong>%{distributor}</strong> был ОТМЕНЕН. Сохраните эту информацию об отмене для своих записей."
dont_cancel: "Если вы передумали или не хотите отменять этот заказ, свяжитесь с нами. %{email}"
order_summary_canceled_html: "<strong>Информация по Заказу #%{number} [ОТМЕНЕН]</strong>"
details: "Подробности того, что вы заказали:"

View File

@@ -42,6 +42,9 @@ $ docker/server
* You will then get the trace of the containers in the terminal. You can stop the containers using Ctrl-C in the terminal.
* You can find some useful tips and commands [here](https://github.com/openfoodfoundation/openfoodnetwork/wiki/Docker:-useful-tips-and-commands).
### Troubleshooting
If you are using Windows and having issues related to the ruby-build not finding a definition for the ruby version, you may need to follow these commands [here](https://stackoverflow.com/questions/2517190/how-do-i-force-git-to-use-lf-instead-of-crlf-under-windows/33424884#33424884) to fix your local git config related to line breaks
## Script Summary
* docker/build: This script builds the Docker containers specified for this app, seeds the database, and logs the screen output for these operations. After you use "git clone" to download this repository, run the docker/build script to start the setup process.
* docker/server: Use this script to run this app in the Rails server. This script executes the "docker-compose up" command and logs the results. If all goes well, you will be able to view this app on your local browser at http://localhost:3000/.

View File

@@ -139,7 +139,7 @@ feature 'Enterprises Index' do
expect(page).to have_no_content "supplier2.name"
expect(page).to have_no_content "distributor2.name"
expect(find("#content-header")).to have_link "New Enterprise"
expect(find('.js-admin-section-header')).to have_link "New Enterprise"
end
it "does not give me an option to change or update the package and producer properties of enterprises I manage" do

View File

@@ -151,7 +151,7 @@ feature '
page.has_selector? "table.index tbody[data-hook='admin_order_form_line_items'] tr" # Wait for JS
click_button 'Update'
expect(page).to have_selector 'h1.page-title', text: "Customer Details"
expect(page).to have_selector 'h1.js-admin-page-title', text: "Customer Details"
# The customer selection partial should be visible
expect(page).to have_selector '#select-customer'
@@ -160,7 +160,7 @@ feature '
targetted_select2_search customer.email, from: '#customer_search_override',
dropdown_css: '.select2-drop'
click_button 'Update'
expect(page).to have_selector "h1.page-title", text: "Customer Details"
expect(page).to have_selector "h1.js-admin-page-title", text: "Customer Details"
# Then their addresses should be associated with the order
order = Spree::Order.last

View File

@@ -297,6 +297,31 @@ feature "Product Import", js: true do
end
end
it "handles a unit of kg for inventory import" do
product = create(:simple_product, supplier: enterprise, on_hand: 100, name: 'Beets', unit_value: '1000', variant_unit_scale: 1000)
csv_data = CSV.generate do |csv|
csv << ["name", "distributor", "producer", "category", "on_hand", "price", "unit_type", "units", "on_demand"]
csv << ["Beets", "Another Enterprise", "User Enterprise", "Vegetables", nil, "3.20", "kg", "1", "true"]
end
File.write('/tmp/test.csv', csv_data)
visit main_app.admin_product_import_path
select2_select I18n.t('admin.product_import.index.inventories'), from: "settings_import_into"
attach_file 'file', '/tmp/test.csv'
click_button 'Upload'
proceed_to_validation
expect(page).to have_selector '.item-count', text: "1"
expect(page).to have_no_selector '.invalid-count'
expect(page).to have_selector '.inv-create-count', text: '1'
save_data
expect(page).to have_selector '.inv-created-count', text: '1'
end
it "handles on_demand and on_hand validations with inventory" do
csv_data = CSV.generate do |csv|
csv << ["name", "distributor", "producer", "category", "on_hand", "price", "units", "on_demand"]

View File

@@ -88,6 +88,7 @@ feature "Check out with Stripe", js: true do
create(:stripe_sca_payment_method, distributors: [distributor])
}
let!(:shipping_method) { create(:shipping_method) }
let(:error_message) { "Card was declined: insufficient funds." }
context "with guest checkout" do
before do
@@ -111,8 +112,6 @@ feature "Check out with Stripe", js: true do
end
context "when the card is rejected" do
let(:error_message) { "Card was declined: insufficient funds." }
before do
stub_payment_intents_post_request order: order
stub_failed_capture_request order: order, response: { message: error_message }
@@ -163,8 +162,6 @@ feature "Check out with Stripe", js: true do
end
describe "and the authorization fails" do
let(:error_message) { "Card was declined: insufficient funds." }
before do
stub_failed_capture_request order: order, response: { message: error_message }
end
@@ -181,6 +178,32 @@ feature "Check out with Stripe", js: true do
end
end
end
context "with multiple payment attempts; one failed and one succeeded" do
before do
stub_payment_intents_post_request order: order
end
it "records failed payment attempt and allows order completion" do
# First payment attempt is rejected
stub_failed_capture_request(order: order, response: { message: error_message })
checkout_with_stripe
expect(page).to have_content error_message
expect(order.reload.payments.count).to eq 1
expect(order.state).to eq "cart"
expect(order.payments.first.state).to eq "failed"
# Second payment attempt is accepted
stub_successful_capture_request order: order
place_order
expect(page).to have_content "Confirmed"
expect(order.reload.payments.count).to eq 2
expect(order.state).to eq "complete"
expect(order.payments.last.state).to eq "completed"
end
end
end
end
end

View File

@@ -194,8 +194,6 @@ feature "As a consumer I want to shop with a distributor", js: true do
end
it "returns search results for products where the search term matches one of the product's variant names" do
pending "has been broken for a while"
visit shop_path
fill_in "search", with: "Badg" # For variant with display_name "Badgers"

View File

@@ -2,7 +2,7 @@ require 'spec_helper'
describe AdjustmentMetadata do
it "is valid when built from factory" do
adjustment = build(:adjustment)
expect(adjustment).to be_valid
adjustment_metadata = build(:adjustment_metadata)
expect(adjustment_metadata).to be_valid
end
end

View File

@@ -0,0 +1,116 @@
# frozen_string_literal: true
require 'spec_helper'
describe ProductImport::EntryValidator do
let(:current_user) { double(:current_user) }
let(:import_time) { double(:import_time) }
let(:spreadsheet_data) { double(:spreadsheet_data) }
let(:editable_enterprises) { double(:editable_enterprises) }
let(:inventory_permissions) { double(:inventory_permissions) }
let(:reset_counts) { double(:reset_counts) }
let(:import_settings) { double(:import_settings) }
let(:all_entries) { double(:all_entries) }
let(:entry_validator) do
described_class.new(
current_user,
import_time,
spreadsheet_data,
editable_enterprises,
inventory_permissions,
reset_counts,
import_settings,
all_entries
)
end
let(:enterprise) { create(:enterprise, name: "User Enterprise") }
let(:entry_g) do
ProductImport::SpreadsheetEntry.new(
unscaled_units: "500",
units: "500",
unit_type: "g",
name: 'Tomato',
enterprise: enterprise,
enterprise_id: enterprise.id,
producer: enterprise,
producer_id: enterprise.id,
distributor: enterprise
)
end
let(:entry_kg) do
ProductImport::SpreadsheetEntry.new(
unscaled_units: "1",
units: "1",
unit_type: "kg",
name: 'Potatoes',
enterprise: enterprise,
enterprise_id: enterprise.id,
producer: enterprise,
producer_id: enterprise.id,
distributor: enterprise
)
end
describe "inventory validation" do
before do
allow(entry_validator).to receive(:import_into_inventory?) { true }
allow(entry_validator).to receive(:enterprise_validation) {}
allow(entry_validator).to receive(:producer_validation) {}
allow(entry_validator).to receive(:variant_of_product_validation) {}
end
context "products exist" do
let!(:product_g) {
create(
:simple_product,
supplier: enterprise,
on_hand: '100',
name: 'Tomato',
unit_value: 500,
variant_unit_scale: 1,
variant_unit: 'weight'
)
}
let!(:product_kg) {
create(
:simple_product,
supplier: enterprise,
on_hand: '100',
name: 'Potatoes',
unit_value: 1000,
variant_unit_scale: 1000,
variant_unit: 'weight'
)
}
it "validates a spreadsheet entry in g" do
entries = [entry_g]
entry_validator.validate_all(entries)
expect(entries.first.errors.count).to eq(0)
end
it "validates a spreadsheet entry in kg" do
entries = [entry_kg]
entry_validator.validate_all(entries)
expect(entries.first.errors.count).to eq(0)
end
end
context "products do not exist" do
# stub
end
end
describe "enterprise validation" do
# stub
end
describe "producer_validation" do
# stub
end
end