From d243c4189bd5792fe14b31bf6c085eb155f356b0 Mon Sep 17 00:00:00 2001 From: Florian Lentsch Date: Sun, 23 Aug 2020 08:08:39 +0200 Subject: [PATCH 1/8] First go at #764 Add option to ignore delivered amounts in order group distribution --- app/models/group_order_article.rb | 5 +++-- app/serializers/config_serializer.rb | 2 +- app/views/admin/configs/_tab_others.html.haml | 1 + config/locales/de.yml | 2 ++ config/locales/en.yml | 2 ++ 5 files changed, 9 insertions(+), 3 deletions(-) diff --git a/app/models/group_order_article.rb b/app/models/group_order_article.rb index af31fef09..dfbda17d8 100644 --- a/app/models/group_order_article.rb +++ b/app/models/group_order_article.rb @@ -130,13 +130,14 @@ def calculate_result(total = nil) # Determine quantities to be ordered... order_quantities.each do |goaq| - q = [goaq.quantity, total - total_quantity].min + q = goaq.quantity + q = [q, total - total_quantity].min unless FoodsoftConfig[:ignore_received_units_on_redistribute] total_quantity += q if goaq.group_order_article_id == self.id logger.debug "increasing quantity by #{q}" quantity += q end - break if total_quantity >= total + break if total_quantity >= total && !FoodsoftConfig[:ignore_received_units_on_redistribute] end # Determine tolerance to be ordered... diff --git a/app/serializers/config_serializer.rb b/app/serializers/config_serializer.rb index a196a372d..87257d295 100644 --- a/app/serializers/config_serializer.rb +++ b/app/serializers/config_serializer.rb @@ -5,7 +5,7 @@ class ConfigSerializer < ActiveModel::Serializer # settings attributes :currency_unit, :currency_space, :default_locale, :price_markup, - :tolerance_is_costly, :use_apple_points, :use_tolerance + :tolerance_is_costly, :ignore_received_units_on_redistribute, :use_apple_points, :use_tolerance # layout attributes :page_footer_html, :webstats_tracking_code_html diff --git a/app/views/admin/configs/_tab_others.html.haml b/app/views/admin/configs/_tab_others.html.haml index 96747794f..49ee5598b 100644 --- a/app/views/admin/configs/_tab_others.html.haml +++ b/app/views/admin/configs/_tab_others.html.haml @@ -1,5 +1,6 @@ = config_input form, :use_nick, as: :boolean = config_input form, :tolerance_is_costly, as: :boolean += config_input form, :ignore_received_units_on_redistribute, as: :boolean = config_input form, :disable_invite, as: :boolean = config_input form, :help_url, as: :url, input_html: {class: 'input-xlarge'} = config_input form, :webstats_tracking_code, as: :text, input_html: {class: 'input-xxlarge', rows: 3} diff --git a/config/locales/de.yml b/config/locales/de.yml index 87f667ed9..d4dfc2c55 100644 --- a/config/locales/de.yml +++ b/config/locales/de.yml @@ -597,6 +597,7 @@ de: tasks_upfront_days: Anzahl der Tage, für welche du im Voraus wiederkehrende Aufgaben definieren möchtest tax_default: Standard Mehrwertsteuersatz für neue Artikel tolerance_is_costly: Eine möglichst große Menge im Rahmen der Tolerenz bestellen. Wenn dies nicht aktiviert ist, wird im Rahmen der Toleranz nur so viel bestellt, dass damit komplette Einheiten (Boxen) bestellt werden können. Die Option wirkt sich auch auf die Toleranz des Gesamtpreises einer offenen Mitgliederbestellung aus. + ignore_received_units_on_redistribute: Auch, wenn insgesamt zu wenig geliefert wurde, wird den Bestellgruppen der volle Betrag verrechnet, bis die Menge manuell korrigiert wird. use_apple_points: Wenn das Apfel Punktesystem aktiviert ist, ist es erforderlich, dass Mitglieder Aufgaben erledigen um bestellen zu können. use_boxfill: Wenn aktiviert, können Benutzer nahe am Ende der Bestellung diese nur mehr so verändern, dass sich die Gesamtsumme erhöht. Dies hilft beim auffüllen der verbleibenden Kisten. Es muss trotzdem noch das Kistenauffülldatum bei der Bestellung gesetzt werden. use_iban: Zusätzlich Feld für die internationale Kontonummer bei Benutzern und Lieferanten anzeigen @@ -650,6 +651,7 @@ de: tax_default: Mehrwertsteuer time_zone: Zeitzone tolerance_is_costly: Bestelltoleranz maximal ausnutzen, um möglichst große Mengen zu bestellen + ignore_received_units_on_redistribute: Liefermenge beim Verrechnen der einzelnen Bestellgruppen ignorieren use_apple_points: Apfelpunkte verwenden use_boxfill: Kistenauffüllphase use_iban: IBAN verwenden diff --git a/config/locales/en.yml b/config/locales/en.yml index 2f63d54f6..0b0cfff50 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -597,6 +597,7 @@ en: tasks_upfront_days: For how many days in advance you would like to schedule periodic tasks. tax_default: Default VAT percentage for new articles. tolerance_is_costly: Order as much of the member tolerance as possible (compared to only as much needed to fill the last box). Enabling this also includes the tolerance in the total price of the open member order. + ignore_received_units_on_redistribute: Even, if the supplier hasn't delivered all that was ordered, the order groups will be charged for the full amounts, unless manually changed. use_apple_points: When the apple point system is enabled, members are required to do some tasks to be able to keep ordering. use_boxfill: When enabled, near end of an order, members are only able to change their order when increases the total amount ordered. This helps to fill any remaining boxes. You still need to set a box-fill date for the orders. use_iban: When enabled, supplier and user provide an additonal field for storing the international bank account number. @@ -650,6 +651,7 @@ en: tax_default: Default VAT time_zone: Time zone tolerance_is_costly: Tolerance is costly + ignore_received_units_on_redistribute: Ignore received amounts when charging order groups use_apple_points: Apple points use_boxfill: Box-fill phase use_iban: Use IBAN From 0eed029d6359ab1df558e500ddfefc7d35237914 Mon Sep 17 00:00:00 2001 From: Florian Lentsch Date: Fri, 16 Oct 2020 15:27:35 +0200 Subject: [PATCH 2/8] Removed superfluous comma --- config/locales/en.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/locales/en.yml b/config/locales/en.yml index 0b0cfff50..64e4aac09 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -597,7 +597,7 @@ en: tasks_upfront_days: For how many days in advance you would like to schedule periodic tasks. tax_default: Default VAT percentage for new articles. tolerance_is_costly: Order as much of the member tolerance as possible (compared to only as much needed to fill the last box). Enabling this also includes the tolerance in the total price of the open member order. - ignore_received_units_on_redistribute: Even, if the supplier hasn't delivered all that was ordered, the order groups will be charged for the full amounts, unless manually changed. + ignore_received_units_on_redistribute: Even if the supplier hasn't delivered all that was ordered, the order groups will be charged for the full amounts, unless manually changed. use_apple_points: When the apple point system is enabled, members are required to do some tasks to be able to keep ordering. use_boxfill: When enabled, near end of an order, members are only able to change their order when increases the total amount ordered. This helps to fill any remaining boxes. You still need to set a box-fill date for the orders. use_iban: When enabled, supplier and user provide an additonal field for storing the international bank account number. From 8381a1132b23d0d8ebdad5798e669a44f3a04b88 Mon Sep 17 00:00:00 2001 From: Florian Lentsch Date: Sat, 17 Oct 2020 11:12:20 +0200 Subject: [PATCH 3/8] Adapted #764 according to use select instead of checkbox --- app/models/group_order_article.rb | 4 ++-- app/serializers/config_serializer.rb | 2 +- app/views/admin/configs/_tab_others.html.haml | 5 ++++- config/locales/de.yml | 7 +++++-- config/locales/en.yml | 7 +++++-- config/locales/es.yml | 17 +++++++++++------ config/locales/fr.yml | 13 +++++++++---- config/locales/nl.yml | 5 +++++ lib/foodsoft_config.rb | 1 + 9 files changed, 43 insertions(+), 18 deletions(-) diff --git a/app/models/group_order_article.rb b/app/models/group_order_article.rb index dfbda17d8..42f2d7859 100644 --- a/app/models/group_order_article.rb +++ b/app/models/group_order_article.rb @@ -131,13 +131,13 @@ def calculate_result(total = nil) # Determine quantities to be ordered... order_quantities.each do |goaq| q = goaq.quantity - q = [q, total - total_quantity].min unless FoodsoftConfig[:ignore_received_units_on_redistribute] + q = [q, total - total_quantity].min if FoodsoftConfig[:distribution_strategy] == :first_order_first_serve total_quantity += q if goaq.group_order_article_id == self.id logger.debug "increasing quantity by #{q}" quantity += q end - break if total_quantity >= total && !FoodsoftConfig[:ignore_received_units_on_redistribute] + break if total_quantity >= total && FoodsoftConfig[:distribution_strategy] == :first_order_first_serve end # Determine tolerance to be ordered... diff --git a/app/serializers/config_serializer.rb b/app/serializers/config_serializer.rb index 87257d295..a053435d2 100644 --- a/app/serializers/config_serializer.rb +++ b/app/serializers/config_serializer.rb @@ -5,7 +5,7 @@ class ConfigSerializer < ActiveModel::Serializer # settings attributes :currency_unit, :currency_space, :default_locale, :price_markup, - :tolerance_is_costly, :ignore_received_units_on_redistribute, :use_apple_points, :use_tolerance + :tolerance_is_costly, :distribution_strategy, :use_apple_points, :use_tolerance # layout attributes :page_footer_html, :webstats_tracking_code_html diff --git a/app/views/admin/configs/_tab_others.html.haml b/app/views/admin/configs/_tab_others.html.haml index 49ee5598b..e28d7cf07 100644 --- a/app/views/admin/configs/_tab_others.html.haml +++ b/app/views/admin/configs/_tab_others.html.haml @@ -1,6 +1,9 @@ = config_input form, :use_nick, as: :boolean = config_input form, :tolerance_is_costly, as: :boolean -= config_input form, :ignore_received_units_on_redistribute, as: :boolean +- distribution_options = [[t('config.keys.distribution_strategy_options.first_order_first_serve'), :first_order_first_serve], + [t('config.keys.distribution_strategy_options.no_automatic_distribution'), :no_automatic_distribution]] += config_input form, :distribution_strategy, as: :select, collection: distribution_options, + include_blank: false, input_html: {class: 'input-xxlarge'} = config_input form, :disable_invite, as: :boolean = config_input form, :help_url, as: :url, input_html: {class: 'input-xlarge'} = config_input form, :webstats_tracking_code, as: :text, input_html: {class: 'input-xxlarge', rows: 3} diff --git a/config/locales/de.yml b/config/locales/de.yml index d4dfc2c55..69f317747 100644 --- a/config/locales/de.yml +++ b/config/locales/de.yml @@ -597,7 +597,7 @@ de: tasks_upfront_days: Anzahl der Tage, für welche du im Voraus wiederkehrende Aufgaben definieren möchtest tax_default: Standard Mehrwertsteuersatz für neue Artikel tolerance_is_costly: Eine möglichst große Menge im Rahmen der Tolerenz bestellen. Wenn dies nicht aktiviert ist, wird im Rahmen der Toleranz nur so viel bestellt, dass damit komplette Einheiten (Boxen) bestellt werden können. Die Option wirkt sich auch auf die Toleranz des Gesamtpreises einer offenen Mitgliederbestellung aus. - ignore_received_units_on_redistribute: Auch, wenn insgesamt zu wenig geliefert wurde, wird den Bestellgruppen der volle Betrag verrechnet, bis die Menge manuell korrigiert wird. + distribution_strategy: Wie bei der Verteilung von Artikeln nach dem Empfangen einer Bestellung vorgegangen werden soll. use_apple_points: Wenn das Apfel Punktesystem aktiviert ist, ist es erforderlich, dass Mitglieder Aufgaben erledigen um bestellen zu können. use_boxfill: Wenn aktiviert, können Benutzer nahe am Ende der Bestellung diese nur mehr so verändern, dass sich die Gesamtsumme erhöht. Dies hilft beim auffüllen der verbleibenden Kisten. Es muss trotzdem noch das Kistenauffülldatum bei der Bestellung gesetzt werden. use_iban: Zusätzlich Feld für die internationale Kontonummer bei Benutzern und Lieferanten anzeigen @@ -651,7 +651,10 @@ de: tax_default: Mehrwertsteuer time_zone: Zeitzone tolerance_is_costly: Bestelltoleranz maximal ausnutzen, um möglichst große Mengen zu bestellen - ignore_received_units_on_redistribute: Liefermenge beim Verrechnen der einzelnen Bestellgruppen ignorieren + distribution_strategy: Verteilungs-Strategie + distribution_strategy_options: + first_order_first_serve: Zuerst an die verteilen, die zuerst bestellt haben + no_automatic_distribution: Keine automatische Verteilung use_apple_points: Apfelpunkte verwenden use_boxfill: Kistenauffüllphase use_iban: IBAN verwenden diff --git a/config/locales/en.yml b/config/locales/en.yml index 64e4aac09..c40843e94 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -597,7 +597,7 @@ en: tasks_upfront_days: For how many days in advance you would like to schedule periodic tasks. tax_default: Default VAT percentage for new articles. tolerance_is_costly: Order as much of the member tolerance as possible (compared to only as much needed to fill the last box). Enabling this also includes the tolerance in the total price of the open member order. - ignore_received_units_on_redistribute: Even if the supplier hasn't delivered all that was ordered, the order groups will be charged for the full amounts, unless manually changed. + distribution_strategy: How articles should be distributed after an order has been received. use_apple_points: When the apple point system is enabled, members are required to do some tasks to be able to keep ordering. use_boxfill: When enabled, near end of an order, members are only able to change their order when increases the total amount ordered. This helps to fill any remaining boxes. You still need to set a box-fill date for the orders. use_iban: When enabled, supplier and user provide an additonal field for storing the international bank account number. @@ -651,7 +651,10 @@ en: tax_default: Default VAT time_zone: Time zone tolerance_is_costly: Tolerance is costly - ignore_received_units_on_redistribute: Ignore received amounts when charging order groups + distribution_strategy: Distribution strategy + distribution_strategy_options: + first_order_first_serve: First distribute to those who ordered first + no_automatic_distribution: No automatic distribution use_apple_points: Apple points use_boxfill: Box-fill phase use_iban: Use IBAN diff --git a/config/locales/es.yml b/config/locales/es.yml index 18eb058c5..29a03ab5b 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -268,7 +268,7 @@ es: all_ordergroups: Todos los grupos de pedido all_users: Todos los usuarios all_workgroups: Todos los grupos de trabajo - created_at: creado + created_at: creado first_paragraph: Aquí puedes administrar grupos y usuarios de Foodsoft. groupname: nombre del grupo members: miembros @@ -513,7 +513,7 @@ es: status: Estado (x=saltar) file_label: Por favor elige un archivo compatible options: - convert_units: Mantener unidades actuales, recomputar la cantidad y precio de unidades (como sincronizar). + convert_units: Mantener unidades actuales, recomputar la cantidad y precio de unidades (como sincronizar). outlist_absent: Borrar artículos que no están en el archivo subido. sample: juices: Jugos @@ -561,6 +561,7 @@ es: tasks_upfront_days: Con cuántos días de antelación te gustaría programar las tareas periódicas. tax_default: Porcentaje por defecto del IVA para artículos nuevos. tolerance_is_costly: Pide lo que más permita la tolerancia de los miembros (en lugar de sólo lo necesario para llenar la última caja). Permitir esto también incluye la tolerancia en el precio final del pedido abierto de cada miembro. + distribution_strategy: Cómo se deben distribuir los artículos después de recibir un pedido. use_apple_points: Cuando el sistema de puntos-manzana está habilitado los miembros deberán realizar algunas tareas para poder hacer pedidos. use_boxfill: Cuando está activado, cerca del cierre de un pedido los miembros no podrán cambiar su pedido a menos que se incremente el valor pedido total. Esto ayudará a llenar las cajas que faltan. Igualmente deberás decidir una fecha de llenado de cajas para los pedidos. use_iban: Cuando esta opción está habilitada, el proveedor y el usuario pueden guardan también su número de cuenta bancaria internacional (IBAN). @@ -605,6 +606,10 @@ es: tax_default: IVA por defecto time_zone: Zona horaria tolerance_is_costly: La tolerancia es prioritaria + distribution_strategy: Estrategia de distribución + distribution_strategy_options: + first_order_first_serve: Primero distribuya a quienes ordenaron primero + no_automatic_distribution: Sin distribución automática use_apple_points: Puntos-manzana use_boxfill: Fase de llenar las cajas use_iban: Usar IBAN @@ -1009,7 +1014,7 @@ es: changes_saved: Guarda los cambios. index: my_ordergroup: - last_update: La última actualización fue hace %{when} + last_update: La última actualización fue hace %{when} title: Mi grupo de pedido transactions: title: Últimas transacciones @@ -1098,7 +1103,7 @@ es: error_invite_invalid: Tu invitación no es válida. error_token_invalid: La sesión ha expirado o no es válida. Prueba de nuevo. reset_password: - notice: Si tu email está ya registrado aquí, recibirás un mensaje con un enlace para + notice: Si tu email está ya registrado aquí, recibirás un mensaje con un enlace para update_password: notice: Tu contraseña ha sido actualizada. Prueba a conectarte ahora. forgot_password: @@ -1463,7 +1468,7 @@ es: copy: title: Copia artículo de stock create: - notice: Se ha creado el nuevo producto en stock "%{name}" + notice: Se ha creado el nuevo producto en stock "%{name}" derive: title: Añade un artículo en stock desde plantilla destroy: @@ -1571,7 +1576,7 @@ es: accept_task: Aceptar tarea confirm_delete_group: Estás seguro/a de que quieres borrar esta tarea y todas las tareas subsecuentes? confirm_delete_single: Estás seguro/a de que quieres borrar esta tarea? - confirm_delete_single_from_group: Estás seguro/a de que quieres borrar esta tarea (y mantener las tareas recurrentes relacionadas)? + confirm_delete_single_from_group: Estás seguro/a de que quieres borrar esta tarea (y mantener las tareas recurrentes relacionadas)? delete_group: Borrar esta tarea y las subsecuentes edit_group: Edita recurrencia mark_done: Marca tarea como hecha diff --git a/config/locales/fr.yml b/config/locales/fr.yml index 0e2c3b844..b2219b184 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -14,7 +14,7 @@ fr: gross_price: Prix TTC manufacturer: Product-rice-eur name: Nom - order_number: Numéro + order_number: Numéro order_number_short: Numéro origin: Lieu de production price: Prix HT @@ -403,6 +403,7 @@ fr: hints: homepage: Site de votre coop. name: Le nom de votre coop. + distribution_strategy: Comment procéder à la distribution des articles après réception d'une commande. keys: contact: city: Ville @@ -413,6 +414,10 @@ fr: zip_code: Code postal currency_unit: Monnaie name: Nom + distribution_strategy: Stratégie de distribution + distribution_strategy_options: + first_order_first_serve: Distribuez d'abord à ceux qui ont commandé en premier + no_automatic_distribution: Pas de distribution automatique tabs: language: Langue list: Liste @@ -851,7 +856,7 @@ fr: error_invite_invalid: Ton invitation n'est pas ou plus valide. error_token_invalid: Ton jeton de connexion n'est pas ou plus valide, essaie de cliquer à nouveau sur le lien. reset_password: - notice: Tu vas maintenant recevoir un message contenant un lien qui te permettra de réinitialiser ton mot de passe. + notice: Tu vas maintenant recevoir un message contenant un lien qui te permettra de réinitialiser ton mot de passe. update_password: notice: Ton mot de passe a été mis à jour. Tu peux maintenant de connecter. forgot_password: @@ -1334,7 +1339,7 @@ fr: notice: La description du boulot a été mise à jour. notice_converted: Le boulot a été converti en boulot ordinaire (sans répétition). user: - more: Tu t'ennuies en ce moment? Il y aura sûrement du boulot pour toi %{tasks_link}. + more: Tu t'ennuies en ce moment? Il y aura sûrement du boulot pour toi %{tasks_link}. tasks_link: par là-bas title: Ton boulot title_accepted: Boulots acceptés @@ -1359,7 +1364,7 @@ fr: edit: title: Modifier l'équipe error_last_admin_group: Impossible de supprimer la dernière cellule avec privilèges administratrices. - error_last_admin_role: Les privilèges administratrices ne peuvent pas être retirés à la dernière cellule qui les possède. + error_last_admin_role: Les privilèges administratrices ne peuvent pas être retirés à la dernière cellule qui les possède. index: title: Équipes update: diff --git a/config/locales/nl.yml b/config/locales/nl.yml index a984db6cd..b2b7cfbf4 100644 --- a/config/locales/nl.yml +++ b/config/locales/nl.yml @@ -597,6 +597,7 @@ nl: tasks_upfront_days: Hoeveel dagen vantevoren je periodieke taken wil aanmaken. tax_default: Standaard BTW percentage voor nieuwe artikelen. tolerance_is_costly: Bestel zoveel artikelen als mogelijk in de tolerantie (in plaats van net genoeg om de laatste doos te vullen). Dit zorgt er ook voor dat de tolerantie in de prijs van open ledenbestellingen wordt meegenomen. + distribution_strategy: Hoe verder te gaan met de distributie van artikelen na ontvangst van een bestelling. use_apple_points: Wanneer het appelpunten systeem is geactiveerd, kunnen leden slechts bestellen wanneer ze meewerken aan taken. use_boxfill: Wanneer dit aan staat, kunnen gebruikers aan het einde van de bestelfase hun bestelling alleen wijzigen als het de totale bestelling vergroot. Dit helpt om dozen te vullen. Bij de bestelling moet nog wel de dozen-vul-datum ingevuld worden. use_iban: Om leverancier en gebruiker een extra veld te geven voor het internationale bankrekeningnummer (IBAN). @@ -650,6 +651,10 @@ nl: tax_default: Standaard BTW time_zone: Tijdzone tolerance_is_costly: Tolerantie is duur + distribution_strategy: Distributie strategie + distribution_strategy_options: + first_order_first_serve: Verdeel eerst onder degenen die het eerst hebben besteld + no_automatic_distribution: Geen automatische distributie use_apple_points: Appelpunten use_boxfill: Dozen vullen fase use_iban: IBAN gebruiken diff --git a/lib/foodsoft_config.rb b/lib/foodsoft_config.rb index 316a9b2b7..759490a9f 100644 --- a/lib/foodsoft_config.rb +++ b/lib/foodsoft_config.rb @@ -260,6 +260,7 @@ def get_default_config tasks_period_days: 7, tasks_upfront_days: 49, shared_supplier_article_sync_limit: 200, + distribution_strategy: :first_order_first_serve, # The following keys cannot, by default, be set by foodcoops themselves. protected: { multi_coop_install: true, From 1dddd968322e3b2c64e11333f483daab3e52d3cd Mon Sep 17 00:00:00 2001 From: Florian Lentsch Date: Sat, 17 Oct 2020 20:18:12 +0200 Subject: [PATCH 4/8] On #764: Switched to enum for config options --- app/models/group_order_article.rb | 6 ++++-- app/serializers/config_serializer.rb | 1 - app/views/admin/configs/_tab_others.html.haml | 4 ++-- lib/foodsoft_config.rb | 8 +++++++- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/app/models/group_order_article.rb b/app/models/group_order_article.rb index 42f2d7859..0b30af48c 100644 --- a/app/models/group_order_article.rb +++ b/app/models/group_order_article.rb @@ -128,16 +128,18 @@ def calculate_result(total = nil) order_quantities = GroupOrderArticleQuantity.where(group_order_article_id: order_article.group_order_article_ids).order('created_on') logger.debug "GroupOrderArticleQuantity records found: #{order_quantities.size}" + first_order_first_serve = (FoodsoftConfig[:distribution_strategy] == FoodsoftConfig::DistributionStrategy::FIRST_ORDER_FIRST_SERVE) + # Determine quantities to be ordered... order_quantities.each do |goaq| q = goaq.quantity - q = [q, total - total_quantity].min if FoodsoftConfig[:distribution_strategy] == :first_order_first_serve + q = [q, total - total_quantity].min if first_order_first_serve total_quantity += q if goaq.group_order_article_id == self.id logger.debug "increasing quantity by #{q}" quantity += q end - break if total_quantity >= total && FoodsoftConfig[:distribution_strategy] == :first_order_first_serve + break if total_quantity >= total && first_order_first_serve end # Determine tolerance to be ordered... diff --git a/app/serializers/config_serializer.rb b/app/serializers/config_serializer.rb index a053435d2..d5b6c1386 100644 --- a/app/serializers/config_serializer.rb +++ b/app/serializers/config_serializer.rb @@ -1,5 +1,4 @@ class ConfigSerializer < ActiveModel::Serializer - # details attributes :name, :homepage, :contact diff --git a/app/views/admin/configs/_tab_others.html.haml b/app/views/admin/configs/_tab_others.html.haml index e28d7cf07..6dddffc3e 100644 --- a/app/views/admin/configs/_tab_others.html.haml +++ b/app/views/admin/configs/_tab_others.html.haml @@ -1,7 +1,7 @@ = config_input form, :use_nick, as: :boolean = config_input form, :tolerance_is_costly, as: :boolean -- distribution_options = [[t('config.keys.distribution_strategy_options.first_order_first_serve'), :first_order_first_serve], - [t('config.keys.distribution_strategy_options.no_automatic_distribution'), :no_automatic_distribution]] +- distribution_options = [[t('config.keys.distribution_strategy_options.first_order_first_serve'), FoodsoftConfig::DistributionStrategy::FIRST_ORDER_FIRST_SERVE], + [t('config.keys.distribution_strategy_options.no_automatic_distribution'), FoodsoftConfig::DistributionStrategy::NO_AUTOMATIC_DISTRIBUTION]] = config_input form, :distribution_strategy, as: :select, collection: distribution_options, include_blank: false, input_html: {class: 'input-xxlarge'} = config_input form, :disable_invite, as: :boolean diff --git a/lib/foodsoft_config.rb b/lib/foodsoft_config.rb index 759490a9f..713a954a5 100644 --- a/lib/foodsoft_config.rb +++ b/lib/foodsoft_config.rb @@ -54,6 +54,12 @@ class FoodsoftConfig # Loaded configuration APP_CONFIG = ActiveSupport::HashWithIndifferentAccess.new + # distribution strategy config values enum + module DistributionStrategy + FIRST_ORDER_FIRST_SERVE = 'first_order_first_serve' + NO_AUTOMATIC_DISTRIBUTION = 'no_automatic_distribution' + end + class << self # Load and initialize foodcoop configuration file. @@ -260,7 +266,7 @@ def get_default_config tasks_period_days: 7, tasks_upfront_days: 49, shared_supplier_article_sync_limit: 200, - distribution_strategy: :first_order_first_serve, + distribution_strategy: FoodsoftConfig::DistributionStrategy::FIRST_ORDER_FIRST_SERVE, # The following keys cannot, by default, be set by foodcoops themselves. protected: { multi_coop_install: true, From 1051c1a2a7098dd3bd78082620f39f19e2b77db0 Mon Sep 17 00:00:00 2001 From: Florian Lentsch Date: Sat, 17 Oct 2020 20:47:44 +0200 Subject: [PATCH 5/8] Reverted white-space changes performed by autocorrect on save --- config/locales/es.yml | 12 ++++++------ config/locales/fr.yml | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/config/locales/es.yml b/config/locales/es.yml index 29a03ab5b..464e5f6fb 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -268,7 +268,7 @@ es: all_ordergroups: Todos los grupos de pedido all_users: Todos los usuarios all_workgroups: Todos los grupos de trabajo - created_at: creado + created_at: creado first_paragraph: Aquí puedes administrar grupos y usuarios de Foodsoft. groupname: nombre del grupo members: miembros @@ -513,7 +513,7 @@ es: status: Estado (x=saltar) file_label: Por favor elige un archivo compatible options: - convert_units: Mantener unidades actuales, recomputar la cantidad y precio de unidades (como sincronizar). + convert_units: Mantener unidades actuales, recomputar la cantidad y precio de unidades (como sincronizar). outlist_absent: Borrar artículos que no están en el archivo subido. sample: juices: Jugos @@ -1014,7 +1014,7 @@ es: changes_saved: Guarda los cambios. index: my_ordergroup: - last_update: La última actualización fue hace %{when} + last_update: La última actualización fue hace %{when} title: Mi grupo de pedido transactions: title: Últimas transacciones @@ -1103,7 +1103,7 @@ es: error_invite_invalid: Tu invitación no es válida. error_token_invalid: La sesión ha expirado o no es válida. Prueba de nuevo. reset_password: - notice: Si tu email está ya registrado aquí, recibirás un mensaje con un enlace para + notice: Si tu email está ya registrado aquí, recibirás un mensaje con un enlace para update_password: notice: Tu contraseña ha sido actualizada. Prueba a conectarte ahora. forgot_password: @@ -1468,7 +1468,7 @@ es: copy: title: Copia artículo de stock create: - notice: Se ha creado el nuevo producto en stock "%{name}" + notice: Se ha creado el nuevo producto en stock "%{name}" derive: title: Añade un artículo en stock desde plantilla destroy: @@ -1576,7 +1576,7 @@ es: accept_task: Aceptar tarea confirm_delete_group: Estás seguro/a de que quieres borrar esta tarea y todas las tareas subsecuentes? confirm_delete_single: Estás seguro/a de que quieres borrar esta tarea? - confirm_delete_single_from_group: Estás seguro/a de que quieres borrar esta tarea (y mantener las tareas recurrentes relacionadas)? + confirm_delete_single_from_group: Estás seguro/a de que quieres borrar esta tarea (y mantener las tareas recurrentes relacionadas)? delete_group: Borrar esta tarea y las subsecuentes edit_group: Edita recurrencia mark_done: Marca tarea como hecha diff --git a/config/locales/fr.yml b/config/locales/fr.yml index b2219b184..a3070ac4e 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -14,7 +14,7 @@ fr: gross_price: Prix TTC manufacturer: Product-rice-eur name: Nom - order_number: Numéro + order_number: Numéro order_number_short: Numéro origin: Lieu de production price: Prix HT @@ -856,7 +856,7 @@ fr: error_invite_invalid: Ton invitation n'est pas ou plus valide. error_token_invalid: Ton jeton de connexion n'est pas ou plus valide, essaie de cliquer à nouveau sur le lien. reset_password: - notice: Tu vas maintenant recevoir un message contenant un lien qui te permettra de réinitialiser ton mot de passe. + notice: Tu vas maintenant recevoir un message contenant un lien qui te permettra de réinitialiser ton mot de passe. update_password: notice: Ton mot de passe a été mis à jour. Tu peux maintenant de connecter. forgot_password: @@ -1339,7 +1339,7 @@ fr: notice: La description du boulot a été mise à jour. notice_converted: Le boulot a été converti en boulot ordinaire (sans répétition). user: - more: Tu t'ennuies en ce moment? Il y aura sûrement du boulot pour toi %{tasks_link}. + more: Tu t'ennuies en ce moment? Il y aura sûrement du boulot pour toi %{tasks_link}. tasks_link: par là-bas title: Ton boulot title_accepted: Boulots acceptés @@ -1364,7 +1364,7 @@ fr: edit: title: Modifier l'équipe error_last_admin_group: Impossible de supprimer la dernière cellule avec privilèges administratrices. - error_last_admin_role: Les privilèges administratrices ne peuvent pas être retirés à la dernière cellule qui les possède. + error_last_admin_role: Les privilèges administratrices ne peuvent pas être retirés à la dernière cellule qui les possède. index: title: Équipes update: From 716041ae52f077348a67faa578dacc35a8c32008 Mon Sep 17 00:00:00 2001 From: Florian Lentsch Date: Sat, 17 Oct 2020 21:39:05 +0200 Subject: [PATCH 6/8] Applied suggestion https://github.com/foodcoops/foodsoft/pull/765/files#r506974334 Use label_method instead of manually referring to translations --- app/views/admin/configs/_tab_others.html.haml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/views/admin/configs/_tab_others.html.haml b/app/views/admin/configs/_tab_others.html.haml index 6dddffc3e..4859eb9d1 100644 --- a/app/views/admin/configs/_tab_others.html.haml +++ b/app/views/admin/configs/_tab_others.html.haml @@ -1,9 +1,7 @@ = config_input form, :use_nick, as: :boolean = config_input form, :tolerance_is_costly, as: :boolean -- distribution_options = [[t('config.keys.distribution_strategy_options.first_order_first_serve'), FoodsoftConfig::DistributionStrategy::FIRST_ORDER_FIRST_SERVE], - [t('config.keys.distribution_strategy_options.no_automatic_distribution'), FoodsoftConfig::DistributionStrategy::NO_AUTOMATIC_DISTRIBUTION]] -= config_input form, :distribution_strategy, as: :select, collection: distribution_options, - include_blank: false, input_html: {class: 'input-xxlarge'} += config_input form, :distribution_strategy, as: :select, collection: FoodsoftConfig::DistributionStrategy.constants, + include_blank: false, input_html: {class: 'input-xxlarge'}, label_method: ->(s){ t("config.keys.distribution_strategy_options.#{s}") } = config_input form, :disable_invite, as: :boolean = config_input form, :help_url, as: :url, input_html: {class: 'input-xlarge'} = config_input form, :webstats_tracking_code, as: :text, input_html: {class: 'input-xxlarge', rows: 3} From bd396de610609ee2ddc7c1128a6bb9deaf257b20 Mon Sep 17 00:00:00 2001 From: Florian Lentsch Date: Sat, 17 Oct 2020 21:55:38 +0200 Subject: [PATCH 7/8] distribution_strategy: Fixed error in config enum iteration --- app/views/admin/configs/_tab_others.html.haml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/views/admin/configs/_tab_others.html.haml b/app/views/admin/configs/_tab_others.html.haml index 4859eb9d1..907cf8406 100644 --- a/app/views/admin/configs/_tab_others.html.haml +++ b/app/views/admin/configs/_tab_others.html.haml @@ -1,6 +1,7 @@ = config_input form, :use_nick, as: :boolean = config_input form, :tolerance_is_costly, as: :boolean -= config_input form, :distribution_strategy, as: :select, collection: FoodsoftConfig::DistributionStrategy.constants, +- distribution_strategy_options = FoodsoftConfig::DistributionStrategy.constants.map { |c| FoodsoftConfig::DistributionStrategy.const_get(c) } += config_input form, :distribution_strategy, as: :select, collection: distribution_strategy_options, include_blank: false, input_html: {class: 'input-xxlarge'}, label_method: ->(s){ t("config.keys.distribution_strategy_options.#{s}") } = config_input form, :disable_invite, as: :boolean = config_input form, :help_url, as: :url, input_html: {class: 'input-xlarge'} From 0ea91a5108f8f65c5cae404b9658b2fa18b50ef9 Mon Sep 17 00:00:00 2001 From: Florian Lentsch Date: Fri, 5 Feb 2021 15:50:28 +0100 Subject: [PATCH 8/8] Added some very simple rspec tests for #764 --- .../factories/group_order_article_quantity.rb | 9 +++++++++ spec/models/group_order_article_spec.rb | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 spec/factories/group_order_article_quantity.rb diff --git a/spec/factories/group_order_article_quantity.rb b/spec/factories/group_order_article_quantity.rb new file mode 100644 index 000000000..f3fa5bb66 --- /dev/null +++ b/spec/factories/group_order_article_quantity.rb @@ -0,0 +1,9 @@ +require 'factory_bot' + +FactoryBot.define do + + # requires order_article + factory :group_order_article_quantity do + end + +end diff --git a/spec/models/group_order_article_spec.rb b/spec/models/group_order_article_spec.rb index 9ad21c444..fd47e6036 100644 --- a/spec/models/group_order_article_spec.rb +++ b/spec/models/group_order_article_spec.rb @@ -42,4 +42,23 @@ end end + describe 'distribution strategy' do + let(:article) { create :article, supplier: order.supplier, unit_quantity: 1 } + let(:oa) { order.order_articles.create(:article => article) } + let(:goa) { create :group_order_article, group_order: go, order_article: oa } + let!(:goaq) { create :group_order_article_quantity, group_order_article: goa, quantity: 4 } + + it 'can calculate the result for the distribution strategy "first order first serve"' do + res = goa.calculate_result(2) + expect(res).to eq(quantity: 2, tolerance: 0, total: 2) + end + + it 'can calculate the result for the distribution strategy "no automatic distribution"' do + FoodsoftConfig[:distribution_strategy] = FoodsoftConfig::DistributionStrategy::NO_AUTOMATIC_DISTRIBUTION + + res = goa.calculate_result(2) + expect(res).to eq(quantity: 4, tolerance: 0, total: 4) + end + end + end